File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/sources.tar
Back
DataSourceSmartOS.py 0000644 00000104135 15027667240 0010436 0 ustar 00 # Copyright (C) 2013 Canonical Ltd. # Copyright 2019 Joyent, Inc. # # Author: Ben Howard <ben.howard@canonical.com> # # This file is part of cloud-init. See LICENSE file for license information. # Datasource for provisioning on SmartOS. This works on Joyent # and public/private Clouds using SmartOS. # # SmartOS hosts use a serial console (/dev/ttyS1) on KVM Linux Guests # The meta-data is transmitted via key/value pairs made by # requests on the console. For example, to get the hostname, you # would send "GET sdc:hostname" on /dev/ttyS1. # For Linux Guests running in LX-Brand Zones on SmartOS hosts # a socket (/native/.zonecontrol/metadata.sock) is used instead # of a serial console. # # Certain behavior is defined by the DataDictionary # https://eng.joyent.com/mdata/datadict.html # Comments with "@datadictionary" are snippets of the definition import base64 import binascii import errno import fcntl import json import os import random import re import socket import serial from cloudinit import dmi from cloudinit import log as logging from cloudinit import sources, subp, util from cloudinit.event import EventScope, EventType LOG = logging.getLogger(__name__) SMARTOS_ATTRIB_MAP = { # Cloud-init Key : (SmartOS Key, Strip line endings) "instance-id": ("sdc:uuid", True), "local-hostname": ("hostname", True), "public-keys": ("root_authorized_keys", True), "user-script": ("user-script", False), "legacy-user-data": ("user-data", False), "user-data": ("cloud-init:user-data", False), "iptables_disable": ("iptables_disable", True), "motd_sys_info": ("motd_sys_info", True), "availability_zone": ("sdc:datacenter_name", True), "vendor-data": ("sdc:vendor-data", False), "operator-script": ("sdc:operator-script", False), "hostname": ("sdc:hostname", True), "dns_domain": ("sdc:dns_domain", True), } SMARTOS_ATTRIB_JSON = { # Cloud-init Key : (SmartOS Key known JSON) "network-data": "sdc:nics", "dns_servers": "sdc:resolvers", "routes": "sdc:routes", } SMARTOS_ENV_LX_BRAND = "lx-brand" SMARTOS_ENV_KVM = "kvm" DS_NAME = "SmartOS" DS_CFG_PATH = ["datasource", DS_NAME] NO_BASE64_DECODE = [ "iptables_disable", "motd_sys_info", "root_authorized_keys", "sdc:datacenter_name", "sdc:uuiduser-data", "user-script", ] METADATA_SOCKFILE = "/native/.zonecontrol/metadata.sock" SERIAL_DEVICE = "/dev/ttyS1" SERIAL_TIMEOUT = 60 # BUILT-IN DATASOURCE CONFIGURATION # The following is the built-in configuration. If the values # are not set via the system configuration, then these default # will be used: # serial_device: which serial device to use for the meta-data # serial_timeout: how long to wait on the device # no_base64_decode: values which are not base64 encoded and # are fetched directly from SmartOS, not meta-data values # base64_keys: meta-data keys that are delivered in base64 # base64_all: with the exclusion of no_base64_decode values, # treat all meta-data as base64 encoded # disk_setup: describes how to partition the ephemeral drive # fs_setup: describes how to format the ephemeral drive # BUILTIN_DS_CONFIG = { "serial_device": SERIAL_DEVICE, "serial_timeout": SERIAL_TIMEOUT, "metadata_sockfile": METADATA_SOCKFILE, "no_base64_decode": NO_BASE64_DECODE, "base64_keys": [], "base64_all": False, "disk_aliases": {"ephemeral0": "/dev/vdb"}, } BUILTIN_CLOUD_CONFIG = { "disk_setup": { "ephemeral0": { "table_type": "mbr", "layout": False, "overwrite": False, } }, "fs_setup": [ {"label": "ephemeral0", "filesystem": "ext4", "device": "ephemeral0"} ], } # builtin vendor-data is a boothook that writes a script into # /var/lib/cloud/scripts/per-boot. *That* script then handles # executing the 'operator-script' and 'user-script' files # that cloud-init writes into /var/lib/cloud/instance/data/ # if they exist. # # This is all very indirect, but its done like this so that at # some point in the future, perhaps cloud-init wouldn't do it at # all, but rather the vendor actually provide vendor-data that accomplished # their desires. (That is the point of vendor-data). # # cloud-init does cheat a bit, and write the operator-script and user-script # itself. It could have the vendor-script do that, but it seems better # to not require the image to contain a tool (mdata-get) to read those # keys when we have a perfectly good one inside cloud-init. BUILTIN_VENDOR_DATA = """\ #cloud-boothook #!/bin/sh fname="%(per_boot_d)s/01_smartos_vendor_data.sh" mkdir -p "${fname%%/*}" cat > "$fname" <<"END_SCRIPT" #!/bin/sh ## # This file is written as part of the default vendor data for SmartOS. # The SmartOS datasource writes the listed file from the listed metadata key # sdc:operator-script -> %(operator_script)s # user-script -> %(user_script)s # # You can view content with 'mdata-get <key>' # for script in "%(operator_script)s" "%(user_script)s"; do [ -x "$script" ] || continue echo "executing '$script'" 1>&2 "$script" done END_SCRIPT chmod +x "$fname" """ # @datadictionary: this is legacy path for placing files from metadata # per the SmartOS location. It is not preferable, but is done for # legacy reasons LEGACY_USER_D = "/var/db" class DataSourceSmartOS(sources.DataSource): dsname = "Joyent" smartos_type = sources.UNSET md_client = sources.UNSET default_update_events = { EventScope.NETWORK: { EventType.BOOT_NEW_INSTANCE, EventType.BOOT, EventType.BOOT_LEGACY, } } def __init__(self, sys_cfg, distro, paths): sources.DataSource.__init__(self, sys_cfg, distro, paths) self.ds_cfg = util.mergemanydict( [ self.ds_cfg, util.get_cfg_by_path(sys_cfg, DS_CFG_PATH, {}), BUILTIN_DS_CONFIG, ] ) self.metadata = {} self.network_data = None self._network_config = None self.script_base_d = os.path.join(self.paths.get_cpath("scripts")) self._init() def __str__(self): root = sources.DataSource.__str__(self) return "%s [client=%s]" % (root, self.md_client) def _init(self): if self.smartos_type == sources.UNSET: self.smartos_type = get_smartos_environ() if self.smartos_type is None: self.md_client = None if self.md_client == sources.UNSET: self.md_client = jmc_client_factory( smartos_type=self.smartos_type, metadata_sockfile=self.ds_cfg["metadata_sockfile"], serial_device=self.ds_cfg["serial_device"], serial_timeout=self.ds_cfg["serial_timeout"], ) def _set_provisioned(self): """Mark the instance provisioning state as successful. When run in a zone, the host OS will look for /var/svc/provisioning to be renamed as /var/svc/provision_success. This should be done after meta-data is successfully retrieved and from this point the host considers the provision of the zone to be a success and keeps the zone running. """ LOG.debug("Instance provisioning state set as successful") svc_path = "/var/svc" if os.path.exists("/".join([svc_path, "provisioning"])): os.rename( "/".join([svc_path, "provisioning"]), "/".join([svc_path, "provision_success"]), ) def _get_data(self): self._init() md = {} ud = "" if not self.smartos_type: LOG.debug("Not running on smartos") return False if not self.md_client.exists(): LOG.debug( "No metadata device '%r' found for SmartOS datasource", self.md_client, ) return False # Open once for many requests, rather than once for each request self.md_client.open_transport() for ci_noun, attribute in SMARTOS_ATTRIB_MAP.items(): smartos_noun, strip = attribute md[ci_noun] = self.md_client.get(smartos_noun, strip=strip) for ci_noun, smartos_noun in SMARTOS_ATTRIB_JSON.items(): md[ci_noun] = self.md_client.get_json(smartos_noun) self.md_client.close_transport() # @datadictionary: This key may contain a program that is written # to a file in the filesystem of the guest on each boot and then # executed. It may be of any format that would be considered # executable in the guest instance. # # We write 'user-script' and 'operator-script' into the # instance/data directory. The default vendor-data then handles # executing them later. data_d = os.path.join( self.paths.get_cpath(), "instances", md["instance-id"], "data" ) user_script = os.path.join(data_d, "user-script") u_script_l = "%s/user-script" % LEGACY_USER_D write_boot_content( md.get("user-script"), content_f=user_script, link=u_script_l, shebang=True, mode=0o700, ) operator_script = os.path.join(data_d, "operator-script") write_boot_content( md.get("operator-script"), content_f=operator_script, shebang=False, mode=0o700, ) # @datadictionary: This key has no defined format, but its value # is written to the file /var/db/mdata-user-data on each boot prior # to the phase that runs user-script. This file is not to be executed. # This allows a configuration file of some kind to be injected into # the machine to be consumed by the user-script when it runs. u_data = md.get("legacy-user-data") u_data_f = "%s/mdata-user-data" % LEGACY_USER_D write_boot_content(u_data, u_data_f) # Handle the cloud-init regular meta # The hostname may or may not be qualified with the local domain name. # This follows section 3.14 of RFC 2132. if not md["local-hostname"]: if md["hostname"]: md["local-hostname"] = md["hostname"] else: md["local-hostname"] = md["instance-id"] ud = None if md["user-data"]: ud = md["user-data"] if not md["vendor-data"]: md["vendor-data"] = BUILTIN_VENDOR_DATA % { "user_script": user_script, "operator_script": operator_script, "per_boot_d": os.path.join( self.paths.get_cpath("scripts"), "per-boot" ), } self.metadata = util.mergemanydict([md, self.metadata]) self.userdata_raw = ud self.vendordata_raw = md["vendor-data"] self.network_data = md["network-data"] self.routes_data = md["routes"] self._set_provisioned() return True def _get_subplatform(self): return "serial (%s)" % SERIAL_DEVICE def device_name_to_device(self, name): return self.ds_cfg["disk_aliases"].get(name) def get_config_obj(self): if self.smartos_type == SMARTOS_ENV_KVM: return BUILTIN_CLOUD_CONFIG return {} def get_instance_id(self): return self.metadata["instance-id"] @property def network_config(self): # sources.clear_cached_data() may set _network_config to '_unset'. if self._network_config == sources.UNSET: self._network_config = None if self._network_config is None: if self.network_data is not None: self._network_config = convert_smartos_network_data( network_data=self.network_data, dns_servers=self.metadata["dns_servers"], dns_domain=self.metadata["dns_domain"], routes=self.routes_data, ) return self._network_config class JoyentMetadataFetchException(Exception): pass class JoyentMetadataTimeoutException(JoyentMetadataFetchException): pass class JoyentMetadataClient: """ A client implementing v2 of the Joyent Metadata Protocol Specification. The full specification can be found at http://eng.joyent.com/mdata/protocol.html """ line_regex = re.compile( r"V2 (?P<length>\d+) (?P<checksum>[0-9a-f]+)" r" (?P<body>(?P<request_id>[0-9a-f]+) (?P<status>SUCCESS|NOTFOUND)" r"( (?P<payload>.+))?)" ) def __init__(self, smartos_type=None, fp=None): if smartos_type is None: smartos_type = get_smartos_environ() self.smartos_type = smartos_type self.fp = fp def _checksum(self, body): return "{0:08x}".format( binascii.crc32(body.encode("utf-8")) & 0xFFFFFFFF ) def _get_value_from_frame(self, expected_request_id, frame): frame_data = self.line_regex.match(frame).groupdict() if int(frame_data["length"]) != len(frame_data["body"]): raise JoyentMetadataFetchException( "Incorrect frame length given ({0} != {1}).".format( frame_data["length"], len(frame_data["body"]) ) ) expected_checksum = self._checksum(frame_data["body"]) if frame_data["checksum"] != expected_checksum: raise JoyentMetadataFetchException( "Invalid checksum (expected: {0}; got {1}).".format( expected_checksum, frame_data["checksum"] ) ) if frame_data["request_id"] != expected_request_id: raise JoyentMetadataFetchException( "Request ID mismatch (expected: {0}; got {1}).".format( expected_request_id, frame_data["request_id"] ) ) if not frame_data.get("payload", None): LOG.debug("No value found.") return None value = util.b64d(frame_data["payload"]) LOG.debug('Value "%s" found.', value) return value def _readline(self): """ Reads a line a byte at a time until \n is encountered. Returns an ascii string with the trailing newline removed. If a timeout (per-byte) is set and it expires, a JoyentMetadataFetchException will be thrown. """ response = [] def as_ascii(): return b"".join(response).decode("ascii") msg = "Partial response: '%s'" while True: try: byte = self.fp.read(1) if len(byte) == 0: raise JoyentMetadataTimeoutException(msg % as_ascii()) if byte == b"\n": return as_ascii() response.append(byte) except OSError as exc: if exc.errno == errno.EAGAIN: raise JoyentMetadataTimeoutException( msg % as_ascii() ) from exc raise def _write(self, msg): self.fp.write(msg.encode("ascii")) self.fp.flush() def _negotiate(self): LOG.debug("Negotiating protocol V2") self._write("NEGOTIATE V2\n") response = self._readline() LOG.debug('read "%s"', response) if response != "V2_OK": raise JoyentMetadataFetchException( 'Invalid response "%s" to "NEGOTIATE V2"' % response ) LOG.debug("Negotiation complete") def request(self, rtype, param=None): request_id = "{0:08x}".format(random.randint(0, 0xFFFFFFFF)) message_body = " ".join( ( request_id, rtype, ) ) if param: message_body += " " + base64.b64encode(param.encode()).decode() msg = "V2 {0} {1} {2}\n".format( len(message_body), self._checksum(message_body), message_body ) LOG.debug('Writing "%s" to metadata transport.', msg) need_close = False if not self.fp: self.open_transport() need_close = True self._write(msg) response = self._readline() if need_close: self.close_transport() LOG.debug('Read "%s" from metadata transport.', response) if "SUCCESS" not in response: return None value = self._get_value_from_frame(request_id, response) return value def get(self, key, default=None, strip=False): result = self.request(rtype="GET", param=key) if result is None: return default if result and strip: result = result.strip() return result def get_json(self, key, default=None): result = self.get(key, default=default) if result is None: return default return json.loads(result) def list(self): result = self.request(rtype="KEYS") if not result: return [] return result.split("\n") def put(self, key, val): param = b" ".join( [base64.b64encode(i.encode()) for i in (key, val)] ).decode() return self.request(rtype="PUT", param=param) def delete(self, key): return self.request(rtype="DELETE", param=key) def close_transport(self): if self.fp: self.fp.close() self.fp = None def __enter__(self): if self.fp: return self self.open_transport() return self def __exit__(self, exc_type, exc_value, traceback): self.close_transport() return def open_transport(self): raise NotImplementedError class JoyentMetadataSocketClient(JoyentMetadataClient): def __init__(self, socketpath, smartos_type=SMARTOS_ENV_LX_BRAND): super(JoyentMetadataSocketClient, self).__init__(smartos_type) self.socketpath = socketpath def open_transport(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(self.socketpath) self.fp = sock.makefile("rwb") self._negotiate() def exists(self): return os.path.exists(self.socketpath) def __repr__(self): return "%s(socketpath=%s)" % (self.__class__.__name__, self.socketpath) class JoyentMetadataSerialClient(JoyentMetadataClient): def __init__( self, device, timeout=10, smartos_type=SMARTOS_ENV_KVM, fp=None ): super(JoyentMetadataSerialClient, self).__init__(smartos_type, fp) self.device = device self.timeout = timeout def exists(self): return os.path.exists(self.device) def open_transport(self): if self.fp is None: ser = serial.Serial(self.device, timeout=self.timeout) if not ser.isOpen(): raise SystemError("Unable to open %s" % self.device) self.fp = ser fcntl.lockf(ser, fcntl.LOCK_EX) self._flush() self._negotiate() def _flush(self): LOG.debug("Flushing input") # Read any pending data timeout = self.fp.timeout self.fp.timeout = 0.1 while True: try: self._readline() except JoyentMetadataTimeoutException: break LOG.debug("Input empty") # Send a newline and expect "invalid command". Keep trying until # successful. Retry rather frequently so that the "Is the host # metadata service running" appears on the console soon after someone # attaches in an effort to debug. if timeout > 5: self.fp.timeout = 5 else: self.fp.timeout = timeout while True: LOG.debug('Writing newline, expecting "invalid command"') self._write("\n") try: response = self._readline() if response == "invalid command": break if response == "FAILURE": LOG.debug('Got "FAILURE". Retrying.') continue LOG.warning('Unexpected response "%s" during flush', response) except JoyentMetadataTimeoutException: LOG.warning( "Timeout while initializing metadata client. " "Is the host metadata service running?" ) LOG.debug('Got "invalid command". Flush complete.') self.fp.timeout = timeout def __repr__(self): return "%s(device=%s, timeout=%s)" % ( self.__class__.__name__, self.device, self.timeout, ) class JoyentMetadataLegacySerialClient(JoyentMetadataSerialClient): """V1 of the protocol was not safe for all values. Thus, we allowed the user to pass values in as base64 encoded. Users may still reasonably expect to be able to send base64 data and have it transparently decoded. So even though the V2 format is now used, and is safe (using base64 itself), we keep legacy support. The way for a user to do this was: a.) specify 'base64_keys' key whose value is a comma delimited list of keys that were base64 encoded. b.) base64_all: string interpreted as a boolean that indicates if all keys are base64 encoded. c.) set a key named b64-<keyname> with a boolean indicating that <keyname> is base64 encoded.""" def __init__(self, device, timeout=10, smartos_type=None): s = super(JoyentMetadataLegacySerialClient, self) s.__init__(device, timeout, smartos_type) self.base64_keys = None self.base64_all = None def _init_base64_keys(self, reset=False): if reset: self.base64_keys = None self.base64_all = None keys = None if self.base64_all is None: keys = self.list() if "base64_all" in keys: self.base64_all = util.is_true(self._get("base64_all")) else: self.base64_all = False if self.base64_all: # short circuit if base64_all is true return if self.base64_keys is None: if keys is None: keys = self.list() b64_keys = set() if "base64_keys" in keys: b64_keys = set(self._get("base64_keys").split(",")) # now add any b64-<keyname> that has a true value for key in [k[3:] for k in keys if k.startswith("b64-")]: if util.is_true(self._get(key)): b64_keys.add(key) else: if key in b64_keys: b64_keys.remove(key) self.base64_keys = b64_keys def _get(self, key, default=None, strip=False): return super(JoyentMetadataLegacySerialClient, self).get( key, default=default, strip=strip ) def is_b64_encoded(self, key, reset=False): if key in NO_BASE64_DECODE: return False self._init_base64_keys(reset=reset) if self.base64_all: return True return key in self.base64_keys def get(self, key, default=None, strip=False): mdefault = object() val = self._get(key, strip=False, default=mdefault) if val is mdefault: return default if self.is_b64_encoded(key): try: val = base64.b64decode(val.encode()).decode() except binascii.Error: LOG.warning("Failed base64 decoding key '%s': %s", key, val) if strip: val = val.strip() return val def jmc_client_factory( smartos_type=None, metadata_sockfile=METADATA_SOCKFILE, serial_device=SERIAL_DEVICE, serial_timeout=SERIAL_TIMEOUT, uname_version=None, ): if smartos_type is None: smartos_type = get_smartos_environ(uname_version) if smartos_type is None: return None elif smartos_type == SMARTOS_ENV_KVM: return JoyentMetadataLegacySerialClient( device=serial_device, timeout=serial_timeout, smartos_type=smartos_type, ) elif smartos_type == SMARTOS_ENV_LX_BRAND: return JoyentMetadataSocketClient( socketpath=metadata_sockfile, smartos_type=smartos_type ) raise ValueError("Unknown value for smartos_type: %s" % smartos_type) def identify_file(content_f): cmd = ["file", "--brief", "--mime-type", content_f] f_type = None try: (f_type, _err) = subp.subp(cmd) LOG.debug("script %s mime type is %s", content_f, f_type) except subp.ProcessExecutionError as e: util.logexc( LOG, ("Failed to identify script type for %s" % content_f, e) ) return None if f_type is None else f_type.strip() def write_boot_content( content, content_f, link=None, shebang=False, mode=0o400 ): """ Write the content to content_f. Under the following rules: 1. If no content, remove the file 2. Write the content 3. If executable and no file magic, add it 4. If there is a link, create it @param content: what to write @param content_f: the file name @param backup_d: the directory to save the backup at @param link: if defined, location to create a symlink to @param shebang: if no file magic, set shebang @param mode: file mode Becuase of the way that Cloud-init executes scripts (no shell), a script will fail to execute if does not have a magic bit (shebang) set for the file. If shebang=True, then the script will be checked for a magic bit and to the SmartOS default of assuming that bash. """ if not content and os.path.exists(content_f): os.unlink(content_f) if link and os.path.islink(link): os.unlink(link) if not content: return util.write_file(content_f, content, mode=mode) if shebang and not content.startswith("#!"): f_type = identify_file(content_f) if f_type == "text/plain": util.write_file( content_f, "\n".join(["#!/bin/bash", content]), mode=mode ) LOG.debug("added shebang to file %s", content_f) if link: try: if os.path.islink(link): os.unlink(link) if content and os.path.exists(content_f): util.ensure_dir(os.path.dirname(link)) os.symlink(content_f, link) except IOError as e: util.logexc(LOG, "failed establishing content link: %s", e) def get_smartos_environ(uname_version=None, product_name=None): uname = os.uname() # SDC LX-Brand Zones lack dmidecode (no /dev/mem) but # report 'BrandZ virtual linux' as the kernel version if uname_version is None: uname_version = uname[3] if uname_version == "BrandZ virtual linux": return SMARTOS_ENV_LX_BRAND if product_name is None: system_type = dmi.read_dmi_data("system-product-name") else: system_type = product_name if system_type and system_type.startswith("SmartDC"): return SMARTOS_ENV_KVM return None # Convert SMARTOS 'sdc:nics' data to network_config yaml def convert_smartos_network_data( network_data=None, dns_servers=None, dns_domain=None, routes=None ): """Return a dictionary of network_config by parsing provided SMARTOS sdc:nics configuration data sdc:nics data is a dictionary of properties of a nic and the ip configuration desired. Additional nic dictionaries are appended to the list. Converting the format is straightforward though it does include duplicate information as well as data which appears to be relevant to the hostOS rather than the guest. For each entry in the nics list returned from query sdc:nics, we create a type: physical entry, and extract the interface properties: 'mac' -> 'mac_address', 'mtu', 'interface' -> 'name'. The remaining keys are related to ip configuration. For each ip in the 'ips' list we create a subnet entry under 'subnets' pairing the ip to a one in the 'gateways' list. Each route in sdc:routes is mapped to a route on each interface. The sdc:routes properties 'dst' and 'gateway' map to 'network' and 'gateway'. The 'linklocal' sdc:routes property is ignored. """ valid_keys = { "physical": [ "mac_address", "mtu", "name", "params", "subnets", "type", ], "subnet": [ "address", "broadcast", "dns_nameservers", "dns_search", "metric", "pointopoint", "routes", "scope", "type", ], "route": [ "network", "gateway", ], } if dns_servers: if not isinstance(dns_servers, (list, tuple)): dns_servers = [dns_servers] else: dns_servers = [] if dns_domain: if not isinstance(dns_domain, (list, tuple)): dns_domain = [dns_domain] else: dns_domain = [] if not routes: routes = [] def is_valid_ipv4(addr): return "." in addr def is_valid_ipv6(addr): return ":" in addr pgws = { "ipv4": {"match": is_valid_ipv4, "gw": None}, "ipv6": {"match": is_valid_ipv6, "gw": None}, } config = [] for nic in network_data: cfg = dict( (k, v) for k, v in nic.items() if k in valid_keys["physical"] ) cfg.update({"type": "physical", "name": nic["interface"]}) if "mac" in nic: cfg.update({"mac_address": nic["mac"]}) subnets = [] for ip in nic.get("ips", []): if ip == "dhcp": subnet = {"type": "dhcp4"} else: routeents = [] subnet = dict( (k, v) for k, v in nic.items() if k in valid_keys["subnet"] ) subnet.update( { "type": "static", "address": ip, } ) proto = "ipv4" if is_valid_ipv4(ip) else "ipv6" # Only use gateways for 'primary' nics if "primary" in nic and nic.get("primary", False): # the ips and gateways list may be N to M, here # we map the ip index into the gateways list, # and handle the case that we could have more ips # than gateways. we only consume the first gateway if not pgws[proto]["gw"]: gateways = [ gw for gw in nic.get("gateways", []) if pgws[proto]["match"](gw) ] if len(gateways): pgws[proto]["gw"] = gateways[0] subnet.update({"gateway": pgws[proto]["gw"]}) for route in routes: rcfg = dict( (k, v) for k, v in route.items() if k in valid_keys["route"] ) # Linux uses the value of 'gateway' to determine # automatically if the route is a forward/next-hop # (non-local IP for gateway) or an interface/resolver # (local IP for gateway). So we can ignore the # 'interface' attribute of sdc:routes, because SDC # guarantees that the gateway is a local IP for # "interface=true". # # Eventually we should be smart and compare "gateway" # to see if it's in the prefix. We can then smartly # add or not-add this route. But for now, # when in doubt, use brute force! Routes for everyone! rcfg.update({"network": route["dst"]}) routeents.append(rcfg) subnet.update({"routes": routeents}) subnets.append(subnet) cfg.update({"subnets": subnets}) config.append(cfg) if dns_servers: config.append( { "type": "nameserver", "address": dns_servers, "search": dns_domain, } ) return {"version": 1, "config": config} # Used to match classes to dependencies datasources = [ (DataSourceSmartOS, (sources.DEP_FILESYSTEM,)), ] # Return a list of data sources that match this set of dependencies def get_datasource_list(depends): return sources.list_from_depends(depends, datasources) if __name__ == "__main__": import sys jmc = jmc_client_factory() if jmc is None: print("Do not appear to be on smartos.") sys.exit(1) if len(sys.argv) == 1: keys = ( list(SMARTOS_ATTRIB_JSON.keys()) + list(SMARTOS_ATTRIB_MAP.keys()) + ["network_config"] ) else: keys = sys.argv[1:] def load_key(client, key, data): if key in data: return data[key] if key in SMARTOS_ATTRIB_JSON: keyname = SMARTOS_ATTRIB_JSON[key] data[key] = client.get_json(keyname) elif key == "network_config": for depkey in ( "network-data", "dns_servers", "dns_domain", "routes", ): load_key(client, depkey, data) data[key] = convert_smartos_network_data( network_data=data["network-data"], dns_servers=data["dns_servers"], dns_domain=data["dns_domain"], routes=data["routes"], ) else: if key in SMARTOS_ATTRIB_MAP: keyname, strip = SMARTOS_ATTRIB_MAP[key] else: keyname, strip = (key, False) data[key] = client.get(keyname, strip=strip) return data[key] data: dict = {} for key in keys: load_key(client=jmc, key=key, data=data) print(json.dumps(data, indent=1, sort_keys=True, separators=(",", ": "))) # vi: ts=4 expandtab DataSourceOpenStack.py 0000644 00000024755 15027667240 0011006 0 ustar 00 # Copyright (C) 2014 Yahoo! Inc. # # Author: Joshua Harlow <harlowja@yahoo-inc.com> # # This file is part of cloud-init. See LICENSE file for license information. import time from cloudinit import dmi from cloudinit import log as logging from cloudinit import sources, url_helper, util from cloudinit.event import EventScope, EventType from cloudinit.net.dhcp import NoDHCPLeaseError from cloudinit.net.ephemeral import EphemeralDHCPv4 from cloudinit.sources import DataSourceOracle as oracle from cloudinit.sources.helpers import openstack LOG = logging.getLogger(__name__) # Various defaults/constants... DEF_MD_URLS = ["http://[fe80::a9fe:a9fe]", "http://169.254.169.254"] DEFAULT_IID = "iid-dsopenstack" DEFAULT_METADATA = { "instance-id": DEFAULT_IID, } # OpenStack DMI constants DMI_PRODUCT_NOVA = "OpenStack Nova" DMI_PRODUCT_COMPUTE = "OpenStack Compute" VALID_DMI_PRODUCT_NAMES = [DMI_PRODUCT_NOVA, DMI_PRODUCT_COMPUTE] DMI_ASSET_TAG_OPENTELEKOM = "OpenTelekomCloud" # See github.com/sapcc/helm-charts/blob/master/openstack/nova/values.yaml # -> compute.defaults.vmware.smbios_asset_tag for this value DMI_ASSET_TAG_SAPCCLOUD = "SAP CCloud VM" DMI_ASSET_TAG_HUAWEICLOUD = "HUAWEICLOUD" VALID_DMI_ASSET_TAGS = VALID_DMI_PRODUCT_NAMES VALID_DMI_ASSET_TAGS += [ DMI_ASSET_TAG_HUAWEICLOUD, DMI_ASSET_TAG_OPENTELEKOM, DMI_ASSET_TAG_SAPCCLOUD, ] class DataSourceOpenStack(openstack.SourceMixin, sources.DataSource): dsname = "OpenStack" _network_config = sources.UNSET # Used to cache calculated network cfg v1 # Whether we want to get network configuration from the metadata service. perform_dhcp_setup = False supported_update_events = { EventScope.NETWORK: { EventType.BOOT_NEW_INSTANCE, EventType.BOOT, EventType.BOOT_LEGACY, EventType.HOTPLUG, } } def __init__(self, sys_cfg, distro, paths): super(DataSourceOpenStack, self).__init__(sys_cfg, distro, paths) self.metadata_address = None self.ssl_details = util.fetch_ssl_details(self.paths) self.version = None self.files = {} self.ec2_metadata = sources.UNSET self.network_json = sources.UNSET def __str__(self): root = sources.DataSource.__str__(self) mstr = "%s [%s,ver=%s]" % (root, self.dsmode, self.version) return mstr def wait_for_metadata_service(self): urls = self.ds_cfg.get("metadata_urls", DEF_MD_URLS) filtered = [x for x in urls if util.is_resolvable_url(x)] if set(filtered) != set(urls): LOG.debug( "Removed the following from metadata urls: %s", list((set(urls) - set(filtered))), ) if len(filtered): urls = filtered else: LOG.warning("Empty metadata url list! using default list") urls = DEF_MD_URLS md_urls = [] url2base = {} for url in urls: md_url = url_helper.combine_url(url, "openstack") md_urls.append(md_url) url2base[md_url] = url url_params = self.get_url_params() start_time = time.time() avail_url, _response = url_helper.wait_for_url( urls=md_urls, max_wait=url_params.max_wait_seconds, timeout=url_params.timeout_seconds, connect_synchronously=False, ) if avail_url: LOG.debug("Using metadata source: '%s'", url2base[avail_url]) else: LOG.debug( "Giving up on OpenStack md from %s after %s seconds", md_urls, int(time.time() - start_time), ) self.metadata_address = url2base.get(avail_url) return bool(avail_url) def check_instance_id(self, sys_cfg): # quickly (local check only) if self.instance_id is still valid return sources.instance_id_matches_system_uuid(self.get_instance_id()) @property def network_config(self): """Return a network config dict for rendering ENI or netplan files.""" if self._network_config != sources.UNSET: return self._network_config # RELEASE_BLOCKER: SRU to Xenial and Artful SRU should not provide # network_config by default unless configured in /etc/cloud/cloud.cfg*. # Patch Xenial and Artful before release to default to False. if util.is_false(self.ds_cfg.get("apply_network_config", True)): self._network_config = None return self._network_config if self.network_json == sources.UNSET: # this would happen if get_data hadn't been called. leave as UNSET LOG.warning( "Unexpected call to network_config when network_json is None." ) return None LOG.debug("network config provided via network_json") self._network_config = openstack.convert_net_json( self.network_json, known_macs=None ) return self._network_config def _get_data(self): """Crawl metadata, parse and persist that data for this instance. @return: True when metadata discovered indicates OpenStack datasource. False when unable to contact metadata service or when metadata format is invalid or disabled. """ if self.perform_dhcp_setup: # Setup networking in init-local stage. try: with EphemeralDHCPv4( self.fallback_interface, tmp_dir=self.distro.get_tmp_exec_path(), ): results = util.log_time( logfunc=LOG.debug, msg="Crawl of metadata service", func=self._crawl_metadata, ) except (NoDHCPLeaseError, sources.InvalidMetaDataException) as e: util.logexc(LOG, str(e)) return False else: try: results = self._crawl_metadata() except sources.InvalidMetaDataException as e: util.logexc(LOG, str(e)) return False self.dsmode = self._determine_dsmode([results.get("dsmode")]) if self.dsmode == sources.DSMODE_DISABLED: return False md = results.get("metadata", {}) md = util.mergemanydict([md, DEFAULT_METADATA]) self.metadata = md self.ec2_metadata = results.get("ec2-metadata") self.network_json = results.get("networkdata") self.userdata_raw = results.get("userdata") self.version = results["version"] self.files.update(results.get("files", {})) vd = results.get("vendordata") self.vendordata_pure = vd try: self.vendordata_raw = sources.convert_vendordata(vd) except ValueError as e: LOG.warning("Invalid content in vendor-data: %s", e) self.vendordata_raw = None vd2 = results.get("vendordata2") self.vendordata2_pure = vd2 try: self.vendordata2_raw = sources.convert_vendordata(vd2) except ValueError as e: LOG.warning("Invalid content in vendor-data2: %s", e) self.vendordata2_raw = None return True def _crawl_metadata(self): """Crawl metadata service when available. @returns: Dictionary with all metadata discovered for this datasource. @raise: InvalidMetaDataException on unreadable or broken metadata. """ try: if not self.wait_for_metadata_service(): raise sources.InvalidMetaDataException( "No active metadata service found" ) except IOError as e: raise sources.InvalidMetaDataException( "IOError contacting metadata service: {error}".format( error=str(e) ) ) url_params = self.get_url_params() try: result = util.log_time( LOG.debug, "Crawl of openstack metadata service", read_metadata_service, args=[self.metadata_address], kwargs={ "ssl_details": self.ssl_details, "retries": url_params.num_retries, "timeout": url_params.timeout_seconds, }, ) except openstack.NonReadable as e: raise sources.InvalidMetaDataException(str(e)) except (openstack.BrokenMetadata, IOError) as e: msg = "Broken metadata address {addr}".format( addr=self.metadata_address ) raise sources.InvalidMetaDataException(msg) from e return result def ds_detect(self): """Return True when a potential OpenStack platform is detected.""" accept_oracle = "Oracle" in self.sys_cfg.get("datasource_list") if not util.is_x86(): # Non-Intel cpus don't properly report dmi product names return True product_name = dmi.read_dmi_data("system-product-name") if product_name in VALID_DMI_PRODUCT_NAMES: return True elif dmi.read_dmi_data("chassis-asset-tag") in VALID_DMI_ASSET_TAGS: return True elif accept_oracle and oracle._is_platform_viable(): return True elif util.get_proc_env(1).get("product_name") == DMI_PRODUCT_NOVA: return True return False class DataSourceOpenStackLocal(DataSourceOpenStack): """Run in init-local using a dhcp discovery prior to metadata crawl. In init-local, no network is available. This subclass sets up minimal networking with dhclient on a viable nic so that it can talk to the metadata service. If the metadata service provides network configuration then render the network configuration for that instance based on metadata. """ perform_dhcp_setup = True # Get metadata network config if present def read_metadata_service(base_url, ssl_details=None, timeout=5, retries=5): reader = openstack.MetadataReader( base_url, ssl_details=ssl_details, timeout=timeout, retries=retries ) return reader.read_v2() # Used to match classes to dependencies datasources = [ (DataSourceOpenStackLocal, (sources.DEP_FILESYSTEM,)), (DataSourceOpenStack, (sources.DEP_FILESYSTEM, sources.DEP_NETWORK)), ] # Return a list of data sources that match this set of dependencies def get_datasource_list(depends): return sources.list_from_depends(depends, datasources) # vi: ts=4 expandtab DataSourceIBMCloud.py 0000644 00000034067 15027667240 0010512 0 ustar 00 # This file is part of cloud-init. See LICENSE file for license information. """Datasource for IBMCloud. IBMCloud is also know as SoftLayer or BlueMix. IBMCloud hypervisor is xen (2018-03-10). There are 2 different api exposed launch methods. * template: This is the legacy method of launching instances. When booting from an image template, the system boots first into a "provisioning" mode. There, host <-> guest mechanisms are utilized to execute code in the guest and configure it. The configuration includes configuring the system network and possibly installing packages and other software stack. After the provisioning is finished, the system reboots. * os_code: Essentially "launch by OS Code" (Operating System Code). This is a more modern approach. There is no specific "provisioning" boot. Instead, cloud-init does all the customization. With or without user-data provided, an OpenStack ConfigDrive like disk is attached. Only disks with label 'config-2' and UUID '9796-932E' are considered. This is to avoid this datasource claiming ConfigDrive. This does mean that 1 in 8^16 (~4 billion) Xen ConfigDrive systems will be incorrectly identified as IBMCloud. The combination of these 2 launch methods and with or without user-data creates 6 boot scenarios. A. os_code with user-data B. os_code without user-data Cloud-init is fully operational in this mode. There is a block device attached with label 'config-2'. As it differs from OpenStack's config-2, we have to differentiate. We do so by requiring the UUID on the filesystem to be "9796-932E". This disk will have the following files. Specifically note, there is no versioned path to the meta-data, only 'latest': openstack/latest/meta_data.json openstack/latest/network_data.json openstack/latest/user_data [optional] openstack/latest/vendor_data.json vendor_data.json as of 2018-04 looks like this: {"cloud-init":"#!/bin/bash\necho 'root:$6$<snip>' | chpasswd -e"} The only difference between A and B in this mode is the presence of user_data on the config disk. C. template, provisioning boot with user-data D. template, provisioning boot without user-data. With ds-identify cloud-init is fully disabled in this mode. Without ds-identify, cloud-init None datasource will be used. This is currently identified by the presence of /root/provisioningConfiguration.cfg . That file is placed into the system before it is booted. The difference between C and D is the presence of the METADATA disk as described in E below. There is no METADATA disk attached unless user-data is provided. E. template, post-provisioning boot with user-data. Cloud-init is fully operational in this mode. This is identified by a block device with filesystem label "METADATA". The looks similar to a version-1 OpenStack config drive. It will have the following files: openstack/latest/user_data openstack/latest/meta_data.json openstack/content/interfaces meta.js meta.js contains something similar to user_data. cloud-init ignores it. cloud-init ignores the 'interfaces' style file here. In this mode, cloud-init has networking code disabled. It relies on the provisioning boot to have configured networking. F. template, post-provisioning boot without user-data. With ds-identify, cloud-init will be fully disabled. Without ds-identify, cloud-init None datasource will be used. There is no information available to identify this scenario. The user will be able to SSH in as as root with their public keys that have been installed into /root/ssh/.authorized_keys during the provisioning stage. TODO: * is uuid (/sys/hypervisor/uuid) stable for life of an instance? it seems it is not the same as data's uuid in the os_code case but is in the template case. """ import base64 import json import os from cloudinit import log as logging from cloudinit import sources, subp, util from cloudinit.sources.helpers import openstack LOG = logging.getLogger(__name__) IBM_CONFIG_UUID = "9796-932E" class Platforms: TEMPLATE_LIVE_METADATA = "Template/Live/Metadata" TEMPLATE_LIVE_NODATA = "UNABLE TO BE IDENTIFIED." TEMPLATE_PROVISIONING_METADATA = "Template/Provisioning/Metadata" TEMPLATE_PROVISIONING_NODATA = "Template/Provisioning/No-Metadata" OS_CODE = "OS-Code/Live" PROVISIONING = ( Platforms.TEMPLATE_PROVISIONING_METADATA, Platforms.TEMPLATE_PROVISIONING_NODATA, ) class DataSourceIBMCloud(sources.DataSource): dsname = "IBMCloud" system_uuid = None def __init__(self, sys_cfg, distro, paths): super(DataSourceIBMCloud, self).__init__(sys_cfg, distro, paths) self.source = None self._network_config = None self.network_json = None self.platform = None def __str__(self): root = super(DataSourceIBMCloud, self).__str__() mstr = "%s [%s %s]" % (root, self.platform, self.source) return mstr def _get_data(self): results = read_md() if results is None: return False self.source = results["source"] self.platform = results["platform"] self.metadata = results["metadata"] self.userdata_raw = results.get("userdata") self.network_json = results.get("networkdata") vd = results.get("vendordata") self.vendordata_pure = vd self.system_uuid = results["system-uuid"] try: self.vendordata_raw = sources.convert_vendordata(vd) except ValueError as e: LOG.warning("Invalid content in vendor-data: %s", e) self.vendordata_raw = None return True def _get_subplatform(self): """Return the subplatform metadata source details.""" return "%s (%s)" % (self.platform, self.source) def check_instance_id(self, sys_cfg): """quickly (local check only) if self.instance_id is still valid in Template mode, the system uuid (/sys/hypervisor/uuid) is the same as found in the METADATA disk. But that is not true in OS_CODE mode. So we read the system_uuid and keep that for later compare.""" if self.system_uuid is None: return False return self.system_uuid == _read_system_uuid() @property def network_config(self): if self.platform != Platforms.OS_CODE: # If deployed from template, an agent in the provisioning # environment handles networking configuration. Not cloud-init. return {"config": "disabled", "version": 1} if self._network_config is None: if self.network_json is not None: LOG.debug("network config provided via network_json") self._network_config = openstack.convert_net_json( self.network_json, known_macs=None ) else: LOG.debug("no network configuration available.") return self._network_config def _read_system_uuid(): uuid_path = "/sys/hypervisor/uuid" if not os.path.isfile(uuid_path): return None return util.load_file(uuid_path).strip().lower() def _is_xen(): return os.path.exists("/proc/xen") def _is_ibm_provisioning( prov_cfg="/root/provisioningConfiguration.cfg", inst_log="/root/swinstall.log", boot_ref="/proc/1/environ", ): """Return boolean indicating if this boot is ibm provisioning boot.""" if os.path.exists(prov_cfg): msg = "config '%s' exists." % prov_cfg result = True if os.path.exists(inst_log): if os.path.exists(boot_ref): result = ( os.stat(inst_log).st_mtime > os.stat(boot_ref).st_mtime ) msg += " log '%s' from %s boot." % ( inst_log, "current" if result else "previous", ) else: msg += " log '%s' existed, but no reference file '%s'." % ( inst_log, boot_ref, ) result = False else: msg += " log '%s' did not exist." % inst_log else: result, msg = (False, "config '%s' did not exist." % prov_cfg) LOG.debug("ibm_provisioning=%s: %s", result, msg) return result def get_ibm_platform(): """Return a tuple (Platform, path) If this is Not IBM cloud, then the return value is (None, None). An instance in provisioning mode is considered running on IBM cloud.""" label_mdata = "METADATA" label_cfg2 = "CONFIG-2" not_found = (None, None) if not _is_xen(): return not_found # fslabels contains only the first entry with a given label. fslabels = {} try: devs = util.blkid() except subp.ProcessExecutionError as e: LOG.warning("Failed to run blkid: %s", e) return (None, None) for dev in sorted(devs.keys()): data = devs[dev] label = data.get("LABEL", "").upper() uuid = data.get("UUID", "").upper() if label not in (label_mdata, label_cfg2): continue if label in fslabels: LOG.warning( "Duplicate fslabel '%s'. existing=%s current=%s", label, fslabels[label], data, ) continue if label == label_cfg2 and uuid != IBM_CONFIG_UUID: LOG.debug( "Skipping %s with LABEL=%s due to uuid != %s: %s", dev, label, uuid, data, ) continue fslabels[label] = data metadata_path = fslabels.get(label_mdata, {}).get("DEVNAME") cfg2_path = fslabels.get(label_cfg2, {}).get("DEVNAME") if cfg2_path: return (Platforms.OS_CODE, cfg2_path) elif metadata_path: if _is_ibm_provisioning(): return (Platforms.TEMPLATE_PROVISIONING_METADATA, metadata_path) else: return (Platforms.TEMPLATE_LIVE_METADATA, metadata_path) elif _is_ibm_provisioning(): return (Platforms.TEMPLATE_PROVISIONING_NODATA, None) return not_found def read_md(): """Read data from IBM Cloud. @return: None if not running on IBM Cloud. dictionary with guaranteed fields: metadata, version and optional fields: userdata, vendordata, networkdata. Also includes the system uuid from /sys/hypervisor/uuid.""" platform, path = get_ibm_platform() if platform is None: LOG.debug("This is not an IBMCloud platform.") return None elif platform in PROVISIONING: LOG.debug("Cloud-init is disabled during provisioning: %s.", platform) return None ret = { "platform": platform, "source": path, "system-uuid": _read_system_uuid(), } try: if os.path.isdir(path): results = metadata_from_dir(path) else: results = util.mount_cb(path, metadata_from_dir) except sources.BrokenMetadata as e: raise RuntimeError( "Failed reading IBM config disk (platform=%s path=%s): %s" % (platform, path, e) ) from e ret.update(results) return ret def metadata_from_dir(source_dir): """Walk source_dir extracting standardized metadata. Certain metadata keys are renamed to present a standardized set of metadata keys. This function has a lot in common with ConfigDriveReader.read_v2 but there are a number of inconsistencies, such key renames and as only presenting a 'latest' version which make it an unlikely candidate to share code. @return: Dict containing translated metadata, userdata, vendordata, networkdata as present. """ def opath(fname): return os.path.join("openstack", "latest", fname) def load_json_bytes(blob): return json.loads(blob.decode("utf-8")) files = [ # tuples of (results_name, path, translator) ("metadata_raw", opath("meta_data.json"), load_json_bytes), ("userdata", opath("user_data"), None), ("vendordata", opath("vendor_data.json"), load_json_bytes), ("networkdata", opath("network_data.json"), load_json_bytes), ] results = {} for (name, path, transl) in files: fpath = os.path.join(source_dir, path) raw = None try: raw = util.load_file(fpath, decode=False) except IOError as e: LOG.debug("Failed reading path '%s': %s", fpath, e) if raw is None or transl is None: data = raw else: try: data = transl(raw) except Exception as e: raise sources.BrokenMetadata( "Failed decoding %s: %s" % (path, e) ) results[name] = data if results.get("metadata_raw") is None: raise sources.BrokenMetadata( "%s missing required file 'meta_data.json'" % source_dir ) results["metadata"] = {} md_raw = results["metadata_raw"] md = results["metadata"] if "random_seed" in md_raw: try: md["random_seed"] = base64.b64decode(md_raw["random_seed"]) except (ValueError, TypeError) as e: raise sources.BrokenMetadata( "Badly formatted metadata random_seed entry: %s" % e ) renames = ( ("public_keys", "public-keys"), ("hostname", "local-hostname"), ("uuid", "instance-id"), ) for mdname, newname in renames: if mdname in md_raw: md[newname] = md_raw[mdname] return results # Used to match classes to dependencies datasources = [ (DataSourceIBMCloud, (sources.DEP_FILESYSTEM,)), ] # Return a list of data sources that match this set of dependencies def get_datasource_list(depends): return sources.list_from_depends(depends, datasources) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Query IBM Cloud Metadata") args = parser.parse_args() data = read_md() print(util.json_dumps(data)) # vi: ts=4 expandtab DataSourceAltCloud.py 0000644 00000020451 15027667240 0010613 0 ustar 00 # Copyright (C) 2009-2010 Canonical Ltd. # Copyright (C) 2012, 2013 Hewlett-Packard Development Company, L.P. # Copyright (C) 2012 Yahoo! Inc. # # Author: Joe VLcek <JVLcek@RedHat.com> # Author: Juerg Haefliger <juerg.haefliger@hp.com> # # This file is part of cloud-init. See LICENSE file for license information. """ This file contains code used to gather the user data passed to an instance on RHEVm and vSphere. """ import errno import os import os.path from cloudinit import dmi from cloudinit import log as logging from cloudinit import sources, subp, util LOG = logging.getLogger(__name__) # Needed file paths CLOUD_INFO_FILE = "/etc/sysconfig/cloud-info" # Shell command lists CMD_PROBE_FLOPPY = ["modprobe", "floppy"] META_DATA_NOT_SUPPORTED = { "block-device-mapping": {}, "instance-id": 455, "local-hostname": "localhost", "placement": {}, } def read_user_data_callback(mount_dir): """ Description: This callback will be applied by util.mount_cb() on the mounted file. Deltacloud file name contains deltacloud. Those not using Deltacloud but instead instrumenting the injection, could drop deltacloud from the file name. Input: mount_dir - Mount directory Returns: User Data """ deltacloud_user_data_file = mount_dir + "/deltacloud-user-data.txt" user_data_file = mount_dir + "/user-data.txt" # First try deltacloud_user_data_file. On failure try user_data_file. try: user_data = util.load_file(deltacloud_user_data_file).strip() except IOError: try: user_data = util.load_file(user_data_file).strip() except IOError: util.logexc(LOG, "Failed accessing user data file.") return None return user_data class DataSourceAltCloud(sources.DataSource): dsname = "AltCloud" def __init__(self, sys_cfg, distro, paths): sources.DataSource.__init__(self, sys_cfg, distro, paths) self.seed = None self.supported_seed_starts = ("/", "file://") def __str__(self): root = sources.DataSource.__str__(self) return "%s [seed=%s]" % (root, self.seed) def get_cloud_type(self): """ Description: Get the type for the cloud back end this instance is running on by examining the string returned by reading either: CLOUD_INFO_FILE or the dmi data. Input: None Returns: One of the following strings: 'RHEV', 'VSPHERE' or 'UNKNOWN' """ if os.path.exists(CLOUD_INFO_FILE): try: cloud_type = util.load_file(CLOUD_INFO_FILE).strip().upper() except IOError: util.logexc( LOG, "Unable to access cloud info file at %s.", CLOUD_INFO_FILE, ) return "UNKNOWN" return cloud_type system_name = dmi.read_dmi_data("system-product-name") if not system_name: return "UNKNOWN" sys_name = system_name.upper() if sys_name.startswith("RHEV"): return "RHEV" if sys_name.startswith("VMWARE"): return "VSPHERE" return "UNKNOWN" def _get_data(self): """ Description: User Data is passed to the launching instance which is used to perform instance configuration. Cloud providers expose the user data differently. It is necessary to determine which cloud provider the current instance is running on to determine how to access the user data. Images built with image factory will contain a CLOUD_INFO_FILE which contains a string identifying the cloud provider. Images not built with Imagefactory will try to determine what the cloud provider is based on system information. """ LOG.debug("Invoked get_data()") cloud_type = self.get_cloud_type() LOG.debug("cloud_type: %s", str(cloud_type)) if "RHEV" in cloud_type: if self.user_data_rhevm(): return True elif "VSPHERE" in cloud_type: if self.user_data_vsphere(): return True else: # there was no recognized alternate cloud type # indicating this handler should not be used. return False # No user data found util.logexc(LOG, "Failed accessing user data.") return False def _get_subplatform(self): """Return the subplatform metadata details.""" cloud_type = self.get_cloud_type() if not hasattr(self, "source"): self.source = sources.METADATA_UNKNOWN if cloud_type == "RHEV": self.source = "/dev/fd0" return "%s (%s)" % (cloud_type.lower(), self.source) def user_data_rhevm(self): """ RHEVM specific userdata read If on RHEV-M the user data will be contained on the floppy device in file <user_data_file> To access it: modprobe floppy Leverage util.mount_cb to: mkdir <tmp mount dir> mount /dev/fd0 <tmp mount dir> The call back passed to util.mount_cb will do: read <tmp mount dir>/<user_data_file> """ return_str = None # modprobe floppy try: modprobe_floppy() except subp.ProcessExecutionError as e: util.logexc(LOG, "Failed modprobe: %s", e) return False floppy_dev = "/dev/fd0" # udevadm settle for floppy device try: util.udevadm_settle(exists=floppy_dev, timeout=5) except (subp.ProcessExecutionError, OSError) as e: util.logexc(LOG, "Failed udevadm_settle: %s\n", e) return False try: return_str = util.mount_cb(floppy_dev, read_user_data_callback) except OSError as err: if err.errno != errno.ENOENT: raise except util.MountFailedError: util.logexc( LOG, "Failed to mount %s when looking for user data", floppy_dev, ) self.userdata_raw = return_str self.metadata = META_DATA_NOT_SUPPORTED if return_str: return True else: return False def user_data_vsphere(self): """ vSphere specific userdata read If on vSphere the user data will be contained on the cdrom device in file <user_data_file> To access it: Leverage util.mount_cb to: mkdir <tmp mount dir> mount /dev/fd0 <tmp mount dir> The call back passed to util.mount_cb will do: read <tmp mount dir>/<user_data_file> """ return_str = None cdrom_list = util.find_devs_with("LABEL=CDROM") for cdrom_dev in cdrom_list: try: return_str = util.mount_cb(cdrom_dev, read_user_data_callback) if return_str: self.source = cdrom_dev break except OSError as err: if err.errno != errno.ENOENT: raise except util.MountFailedError: util.logexc( LOG, "Failed to mount %s when looking for user data", cdrom_dev, ) self.userdata_raw = return_str self.metadata = META_DATA_NOT_SUPPORTED if return_str: return True else: return False def modprobe_floppy(): out, _err = subp.subp(CMD_PROBE_FLOPPY) LOG.debug("Command: %s\nOutput%s", " ".join(CMD_PROBE_FLOPPY), out) # Used to match classes to dependencies # Source DataSourceAltCloud does not really depend on networking. # In the future 'dsmode' like behavior can be added to offer user # the ability to run before networking. datasources = [ (DataSourceAltCloud, (sources.DEP_FILESYSTEM, sources.DEP_NETWORK)), ] # Return a list of data sources that match this set of dependencies def get_datasource_list(depends): return sources.list_from_depends(depends, datasources) # vi: ts=4 expandtab DataSourceScaleway.py 0000644 00000022735 15027667240 0010663 0 ustar 00 # Author: Julien Castets <castets.j@gmail.com> # # This file is part of cloud-init. See LICENSE file for license information. # Scaleway API: # https://developer.scaleway.com/#metadata import json import os import socket import time import requests # Note: `urllib3` is transitively installed by `requests` from urllib3.connection import HTTPConnection from urllib3.poolmanager import PoolManager from cloudinit import dmi from cloudinit import log as logging from cloudinit import net, sources, url_helper, util from cloudinit.event import EventScope, EventType from cloudinit.net.dhcp import NoDHCPLeaseError from cloudinit.net.ephemeral import EphemeralDHCPv4 from cloudinit.sources import DataSourceHostname LOG = logging.getLogger(__name__) DS_BASE_URL = "http://169.254.42.42" BUILTIN_DS_CONFIG = { "metadata_url": DS_BASE_URL + "/conf?format=json", "userdata_url": DS_BASE_URL + "/user_data/cloud-init", "vendordata_url": DS_BASE_URL + "/vendor_data/cloud-init", } DEF_MD_RETRIES = 5 DEF_MD_TIMEOUT = 10 def on_scaleway(): """ There are three ways to detect if you are on Scaleway: * check DMI data: not yet implemented by Scaleway, but the check is made to be future-proof. * the initrd created the file /var/run/scaleway. * "scaleway" is in the kernel cmdline. """ vendor_name = dmi.read_dmi_data("system-manufacturer") if vendor_name == "Scaleway": return True if os.path.exists("/var/run/scaleway"): return True cmdline = util.get_cmdline() if "scaleway" in cmdline: return True return False class SourceAddressAdapter(requests.adapters.HTTPAdapter): """ Adapter for requests to choose the local address to bind to. """ def __init__(self, source_address, **kwargs): self.source_address = source_address super(SourceAddressAdapter, self).__init__(**kwargs) def init_poolmanager(self, connections, maxsize, block=False): socket_options = HTTPConnection.default_socket_options + [ (socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) ] self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, source_address=self.source_address, socket_options=socket_options, ) def query_data_api_once(api_address, timeout, requests_session): """ Retrieve user data or vendor data. Scaleway user/vendor data API returns HTTP/404 if user/vendor data is not set. This function calls `url_helper.readurl` but instead of considering HTTP/404 as an error that requires a retry, it considers it as empty user/vendor data. Also, be aware the user data/vendor API requires the source port to be below 1024 to ensure the client is root (since non-root users can't bind ports below 1024). If requests raises ConnectionError (EADDRINUSE), the caller should retry to call this function on an other port. """ try: resp = url_helper.readurl( api_address, data=None, timeout=timeout, # It's the caller's responsability to recall this function in case # of exception. Don't let url_helper.readurl() retry by itself. retries=0, session=requests_session, # If the error is a HTTP/404 or a ConnectionError, go into raise # block below and don't bother retrying. exception_cb=lambda _, exc: exc.code != 404 and ( not isinstance(exc.cause, requests.exceptions.ConnectionError) ), ) return util.decode_binary(resp.contents) except url_helper.UrlError as exc: # Empty user data. if exc.code == 404: return None raise def query_data_api(api_type, api_address, retries, timeout): """Get user or vendor data. Handle the retrying logic in case the source port is used. Scaleway metadata service requires the source port of the client to be a privileged port (<1024). This is done to ensure that only a privileged user on the system can access the metadata service. """ # Query user/vendor data. Try to make a request on the first privileged # port available. for port in range(1, max(retries, 2)): try: LOG.debug( "Trying to get %s data (bind on port %d)...", api_type, port ) requests_session = requests.Session() requests_session.mount( "http://", SourceAddressAdapter(source_address=("0.0.0.0", port)), ) data = query_data_api_once( api_address, timeout=timeout, requests_session=requests_session ) LOG.debug("%s-data downloaded", api_type) return data except url_helper.UrlError as exc: # Local port already in use or HTTP/429. LOG.warning("Error while trying to get %s data: %s", api_type, exc) time.sleep(5) last_exc = exc continue # Max number of retries reached. raise last_exc class DataSourceScaleway(sources.DataSource): dsname = "Scaleway" default_update_events = { EventScope.NETWORK: { EventType.BOOT_NEW_INSTANCE, EventType.BOOT, EventType.BOOT_LEGACY, } } def __init__(self, sys_cfg, distro, paths): super(DataSourceScaleway, self).__init__(sys_cfg, distro, paths) self.ds_cfg = util.mergemanydict( [ util.get_cfg_by_path(sys_cfg, ["datasource", "Scaleway"], {}), BUILTIN_DS_CONFIG, ] ) self.metadata_address = self.ds_cfg["metadata_url"] self.userdata_address = self.ds_cfg["userdata_url"] self.vendordata_address = self.ds_cfg["vendordata_url"] self.retries = int(self.ds_cfg.get("retries", DEF_MD_RETRIES)) self.timeout = int(self.ds_cfg.get("timeout", DEF_MD_TIMEOUT)) self._fallback_interface = None self._network_config = sources.UNSET def _crawl_metadata(self): resp = url_helper.readurl( self.metadata_address, timeout=self.timeout, retries=self.retries ) self.metadata = json.loads(util.decode_binary(resp.contents)) self.userdata_raw = query_data_api( "user-data", self.userdata_address, self.retries, self.timeout ) self.vendordata_raw = query_data_api( "vendor-data", self.vendordata_address, self.retries, self.timeout ) def _get_data(self): if not on_scaleway(): return False if self._fallback_interface is None: self._fallback_interface = net.find_fallback_nic() try: with EphemeralDHCPv4( self._fallback_interface, tmp_dir=self.distro.get_tmp_exec_path(), ): util.log_time( logfunc=LOG.debug, msg="Crawl of metadata service", func=self._crawl_metadata, ) except (NoDHCPLeaseError) as e: util.logexc(LOG, str(e)) return False return True @property def network_config(self): """ Configure networking according to data received from the metadata API. """ if self._network_config is None: LOG.warning( "Found None as cached _network_config. Resetting to %s", sources.UNSET, ) self._network_config = sources.UNSET if self._network_config != sources.UNSET: return self._network_config if self._fallback_interface is None: self._fallback_interface = net.find_fallback_nic() netcfg = {"type": "physical", "name": "%s" % self._fallback_interface} subnets = [{"type": "dhcp4"}] if self.metadata["ipv6"]: subnets += [ { "type": "static", "address": "%s" % self.metadata["ipv6"]["address"], "netmask": "%s" % self.metadata["ipv6"]["netmask"], "routes": [ { "network": "::", "prefix": "0", "gateway": "%s" % self.metadata["ipv6"]["gateway"], } ], } ] netcfg["subnets"] = subnets self._network_config = {"version": 1, "config": [netcfg]} return self._network_config @property def launch_index(self): return None def get_instance_id(self): return self.metadata["id"] def get_public_ssh_keys(self): ssh_keys = [key["key"] for key in self.metadata["ssh_public_keys"]] akeypre = "AUTHORIZED_KEY=" plen = len(akeypre) for tag in self.metadata.get("tags", []): if not tag.startswith(akeypre): continue ssh_keys.append(tag[:plen].replace("_", " ")) return ssh_keys def get_hostname(self, fqdn=False, resolve_ip=False, metadata_only=False): return DataSourceHostname(self.metadata["hostname"], False) @property def availability_zone(self): return None @property def region(self): return None datasources = [ (DataSourceScaleway, (sources.DEP_FILESYSTEM,)), ] def get_datasource_list(depends): return sources.list_from_depends(depends, datasources) DataSourceAzure.py 0000644 00000211271 15027667240 0010174 0 ustar 00 # Copyright (C) 2013 Canonical Ltd. # # Author: Scott Moser <scott.moser@canonical.com> # # This file is part of cloud-init. See LICENSE file for license information. import base64 import crypt import os import os.path import re import xml.etree.ElementTree as ET from enum import Enum from pathlib import Path from time import sleep, time from typing import Any, Dict, List, Optional from cloudinit import dmi from cloudinit import log as logging from cloudinit import net, sources, ssh_util, subp, util from cloudinit.event import EventScope, EventType from cloudinit.net.dhcp import ( NoDHCPLeaseError, NoDHCPLeaseInterfaceError, NoDHCPLeaseMissingDhclientError, ) from cloudinit.net.ephemeral import EphemeralDHCPv4 from cloudinit.reporting import events from cloudinit.sources.azure import imds from cloudinit.sources.helpers import netlink from cloudinit.sources.helpers.azure import ( DEFAULT_WIRESERVER_ENDPOINT, BrokenAzureDataSource, ChassisAssetTag, NonAzureDataSource, OvfEnvXml, azure_ds_reporter, azure_ds_telemetry_reporter, build_minimal_ovf, dhcp_log_cb, get_boot_telemetry, get_ip_from_lease_value, get_metadata_from_fabric, get_system_info, is_byte_swapped, push_log_to_kvp, report_diagnostic_event, report_failure_to_fabric, ) from cloudinit.url_helper import UrlError LOG = logging.getLogger(__name__) DS_NAME = "Azure" DEFAULT_METADATA = {"instance-id": "iid-AZURE-NODE"} # azure systems will always have a resource disk, and 66-azure-ephemeral.rules # ensures that it gets linked to this path. RESOURCE_DISK_PATH = "/dev/disk/cloud/azure_resource" DEFAULT_FS = "ext4" AGENT_SEED_DIR = "/var/lib/waagent" DEFAULT_PROVISIONING_ISO_DEV = "/dev/sr0" class PPSType(Enum): NONE = "None" OS_DISK = "PreprovisionedOSDisk" RUNNING = "Running" SAVABLE = "Savable" UNKNOWN = "Unknown" PLATFORM_ENTROPY_SOURCE: Optional[str] = "/sys/firmware/acpi/tables/OEM0" # List of static scripts and network config artifacts created by # stock ubuntu supported images. UBUNTU_EXTENDED_NETWORK_SCRIPTS = [ "/etc/netplan/90-hotplug-azure.yaml", "/usr/local/sbin/ephemeral_eth.sh", "/etc/udev/rules.d/10-net-device-added.rules", "/run/network/interfaces.ephemeral.d", ] # This list is used to blacklist devices that will be considered # for renaming or fallback interfaces. # # On Azure network devices using these drivers are automatically # configured by the platform and should not be configured by # cloud-init's network configuration. # # Note: # Azure Dv4 and Ev4 series VMs always have mlx5 hardware. # https://docs.microsoft.com/en-us/azure/virtual-machines/dv4-dsv4-series # https://docs.microsoft.com/en-us/azure/virtual-machines/ev4-esv4-series # Earlier D and E series VMs (such as Dv2, Dv3, and Ev3 series VMs) # can have either mlx4 or mlx5 hardware, with the older series VMs # having a higher chance of coming with mlx4 hardware. # https://docs.microsoft.com/en-us/azure/virtual-machines/dv2-dsv2-series # https://docs.microsoft.com/en-us/azure/virtual-machines/dv3-dsv3-series # https://docs.microsoft.com/en-us/azure/virtual-machines/ev3-esv3-series BLACKLIST_DRIVERS = ["mlx4_core", "mlx5_core"] def find_storvscid_from_sysctl_pnpinfo(sysctl_out, deviceid): # extract the 'X' from dev.storvsc.X. if deviceid matches """ dev.storvsc.1.%pnpinfo: classid=32412632-86cb-44a2-9b5c-50d1417354f5 deviceid=00000000-0001-8899-0000-000000000000 """ for line in sysctl_out.splitlines(): if re.search(r"pnpinfo", line): fields = line.split() if len(fields) >= 3: columns = fields[2].split("=") if ( len(columns) >= 2 and columns[0] == "deviceid" and columns[1].startswith(deviceid) ): comps = fields[0].split(".") return comps[2] return None def find_busdev_from_disk(camcontrol_out, disk_drv): # find the scbusX from 'camcontrol devlist -b' output # if disk_drv matches the specified disk driver, i.e. blkvsc1 """ scbus0 on ata0 bus 0 scbus1 on ata1 bus 0 scbus2 on blkvsc0 bus 0 scbus3 on blkvsc1 bus 0 scbus4 on storvsc2 bus 0 scbus5 on storvsc3 bus 0 scbus-1 on xpt0 bus 0 """ for line in camcontrol_out.splitlines(): if re.search(disk_drv, line): items = line.split() return items[0] return None def find_dev_from_busdev(camcontrol_out: str, busdev: str) -> Optional[str]: # find the daX from 'camcontrol devlist' output # if busdev matches the specified value, i.e. 'scbus2' """ <Msft Virtual CD/ROM 1.0> at scbus1 target 0 lun 0 (cd0,pass0) <Msft Virtual Disk 1.0> at scbus2 target 0 lun 0 (da0,pass1) <Msft Virtual Disk 1.0> at scbus3 target 1 lun 0 (da1,pass2) """ for line in camcontrol_out.splitlines(): if re.search(busdev, line): items = line.split("(") if len(items) == 2: dev_pass = items[1].split(",") return dev_pass[0] return None def normalize_mac_address(mac: str) -> str: """Normalize mac address with colons and lower-case.""" if len(mac) == 12: mac = ":".join( [mac[0:2], mac[2:4], mac[4:6], mac[6:8], mac[8:10], mac[10:12]] ) return mac.lower() @azure_ds_telemetry_reporter def get_hv_netvsc_macs_normalized() -> List[str]: """Get Hyper-V NICs as normalized MAC addresses.""" return [ normalize_mac_address(n[1]) for n in net.get_interfaces() if n[2] == "hv_netvsc" ] @azure_ds_telemetry_reporter def determine_device_driver_for_mac(mac: str) -> Optional[str]: """Determine the device driver to match on, if any.""" drivers = [ i[2] for i in net.get_interfaces(blacklist_drivers=BLACKLIST_DRIVERS) if mac == normalize_mac_address(i[1]) ] if "hv_netvsc" in drivers: return "hv_netvsc" if len(drivers) == 1: report_diagnostic_event( "Assuming driver for interface with mac=%s drivers=%r" % (mac, drivers), logger_func=LOG.debug, ) return drivers[0] report_diagnostic_event( "Unable to specify driver for interface with mac=%s drivers=%r" % (mac, drivers), logger_func=LOG.warning, ) return None def execute_or_debug(cmd, fail_ret=None) -> str: try: return subp.subp(cmd).stdout # pyright: ignore except subp.ProcessExecutionError: LOG.debug("Failed to execute: %s", " ".join(cmd)) return fail_ret def get_dev_storvsc_sysctl(): return execute_or_debug(["sysctl", "dev.storvsc"], fail_ret="") def get_camcontrol_dev_bus(): return execute_or_debug(["camcontrol", "devlist", "-b"]) def get_camcontrol_dev(): return execute_or_debug(["camcontrol", "devlist"]) def get_resource_disk_on_freebsd(port_id) -> Optional[str]: g0 = "00000000" if port_id > 1: g0 = "00000001" port_id = port_id - 2 g1 = "000" + str(port_id) g0g1 = "{0}-{1}".format(g0, g1) # search 'X' from # 'dev.storvsc.X.%pnpinfo: # classid=32412632-86cb-44a2-9b5c-50d1417354f5 # deviceid=00000000-0001-8899-0000-000000000000' sysctl_out = get_dev_storvsc_sysctl() storvscid = find_storvscid_from_sysctl_pnpinfo(sysctl_out, g0g1) if not storvscid: LOG.debug("Fail to find storvsc id from sysctl") return None camcontrol_b_out = get_camcontrol_dev_bus() camcontrol_out = get_camcontrol_dev() # try to find /dev/XX from 'blkvsc' device blkvsc = "blkvsc{0}".format(storvscid) scbusx = find_busdev_from_disk(camcontrol_b_out, blkvsc) if scbusx: devname = find_dev_from_busdev(camcontrol_out, scbusx) if devname is None: LOG.debug("Fail to find /dev/daX") return None return devname # try to find /dev/XX from 'storvsc' device storvsc = "storvsc{0}".format(storvscid) scbusx = find_busdev_from_disk(camcontrol_b_out, storvsc) if scbusx: devname = find_dev_from_busdev(camcontrol_out, scbusx) if devname is None: LOG.debug("Fail to find /dev/daX") return None return devname return None # update the FreeBSD specific information if util.is_FreeBSD(): DEFAULT_FS = "freebsd-ufs" res_disk = get_resource_disk_on_freebsd(1) if res_disk is not None: LOG.debug("resource disk is not None") RESOURCE_DISK_PATH = "/dev/" + res_disk else: LOG.debug("resource disk is None") # TODO Find where platform entropy data is surfaced PLATFORM_ENTROPY_SOURCE = None BUILTIN_DS_CONFIG = { "data_dir": AGENT_SEED_DIR, "disk_aliases": {"ephemeral0": RESOURCE_DISK_PATH}, "apply_network_config": True, # Use IMDS published network configuration } BUILTIN_CLOUD_EPHEMERAL_DISK_CONFIG = { "disk_setup": { "ephemeral0": { "table_type": "gpt", "layout": [100], "overwrite": True, }, }, "fs_setup": [{"filesystem": DEFAULT_FS, "device": "ephemeral0.1"}], } DS_CFG_PATH = ["datasource", DS_NAME] DS_CFG_KEY_PRESERVE_NTFS = "never_destroy_ntfs" DEF_EPHEMERAL_LABEL = "Temporary Storage" # The redacted password fails to meet password complexity requirements # so we can safely use this to mask/redact the password in the ovf-env.xml DEF_PASSWD_REDACTION = "REDACTED" @azure_ds_telemetry_reporter def is_platform_viable(seed_dir: Optional[Path]) -> bool: """Check platform environment to report if this datasource may run.""" chassis_tag = ChassisAssetTag.query_system() if chassis_tag is not None: return True # If no valid chassis tag, check for seeded ovf-env.xml. if seed_dir is None: return False return (seed_dir / "ovf-env.xml").exists() class DataSourceAzure(sources.DataSource): dsname = "Azure" default_update_events = { EventScope.NETWORK: { EventType.BOOT_NEW_INSTANCE, EventType.BOOT, } } _negotiated = False _metadata_imds = sources.UNSET _ci_pkl_version = 1 def __init__(self, sys_cfg, distro, paths): sources.DataSource.__init__(self, sys_cfg, distro, paths) self.seed_dir = os.path.join(paths.seed_dir, "azure") self.cfg = {} self.seed = None self.ds_cfg = util.mergemanydict( [util.get_cfg_by_path(sys_cfg, DS_CFG_PATH, {}), BUILTIN_DS_CONFIG] ) self._iso_dev = None self._network_config = None self._ephemeral_dhcp_ctx = None self._wireserver_endpoint = DEFAULT_WIRESERVER_ENDPOINT self._reported_ready_marker_file = os.path.join( paths.cloud_dir, "data", "reported_ready" ) def _unpickle(self, ci_pkl_version: int) -> None: super()._unpickle(ci_pkl_version) self._ephemeral_dhcp_ctx = None self._iso_dev = None self._wireserver_endpoint = DEFAULT_WIRESERVER_ENDPOINT self._reported_ready_marker_file = os.path.join( self.paths.cloud_dir, "data", "reported_ready" ) def __str__(self): root = sources.DataSource.__str__(self) return "%s [seed=%s]" % (root, self.seed) def _get_subplatform(self): """Return the subplatform metadata source details.""" if self.seed is None: subplatform_type = "unknown" elif self.seed.startswith("/dev"): subplatform_type = "config-disk" elif self.seed.lower() == "imds": subplatform_type = "imds" else: subplatform_type = "seed-dir" return "%s (%s)" % (subplatform_type, self.seed) @azure_ds_telemetry_reporter def _setup_ephemeral_networking( self, *, iface: Optional[str] = None, retry_sleep: int = 1, timeout_minutes: int = 5, ) -> None: """Setup ephemeral networking. Keep retrying DHCP up to specified number of minutes. This does not kill dhclient, so the timeout in practice may be up to timeout_minutes + the system-configured timeout for dhclient. :param timeout_minutes: Number of minutes to keep retrying for. :raises NoDHCPLeaseError: If unable to obtain DHCP lease. """ if self._ephemeral_dhcp_ctx is not None: raise RuntimeError( "Bringing up networking when already configured." ) LOG.debug("Requested ephemeral networking (iface=%s)", iface) self._ephemeral_dhcp_ctx = EphemeralDHCPv4( iface=iface, dhcp_log_func=dhcp_log_cb, tmp_dir=self.distro.get_tmp_exec_path(), ) lease = None timeout = timeout_minutes * 60 + time() with events.ReportEventStack( name="obtain-dhcp-lease", description="obtain dhcp lease", parent=azure_ds_reporter, ): while lease is None: try: lease = self._ephemeral_dhcp_ctx.obtain_lease() except NoDHCPLeaseInterfaceError: # Interface not found, continue after sleeping 1 second. report_diagnostic_event( "Interface not found for DHCP", logger_func=LOG.warning ) except NoDHCPLeaseMissingDhclientError: # No dhclient, no point in retrying. report_diagnostic_event( "dhclient executable not found", logger_func=LOG.error ) self._ephemeral_dhcp_ctx = None raise except NoDHCPLeaseError: # Typical DHCP failure, continue after sleeping 1 second. report_diagnostic_event( "Failed to obtain DHCP lease (iface=%s)" % iface, logger_func=LOG.error, ) except subp.ProcessExecutionError as error: # udevadm settle, ip link set dev eth0 up, etc. report_diagnostic_event( "Command failed: " "cmd=%r stderr=%r stdout=%r exit_code=%s" % ( error.cmd, error.stderr, error.stdout, error.exit_code, ), logger_func=LOG.error, ) # Sleep before retrying, otherwise break if we're past timeout. if lease is None and time() + retry_sleep < timeout: sleep(retry_sleep) else: break if lease is None: self._ephemeral_dhcp_ctx = None raise NoDHCPLeaseError() else: # Ensure iface is set. self._ephemeral_dhcp_ctx.iface = lease["interface"] # Update wireserver IP from DHCP options. if "unknown-245" in lease: self._wireserver_endpoint = get_ip_from_lease_value( lease["unknown-245"] ) @azure_ds_telemetry_reporter def _teardown_ephemeral_networking(self) -> None: """Teardown ephemeral networking.""" if self._ephemeral_dhcp_ctx is None: return self._ephemeral_dhcp_ctx.clean_network() self._ephemeral_dhcp_ctx = None def _is_ephemeral_networking_up(self) -> bool: """Check if networking is configured.""" return not ( self._ephemeral_dhcp_ctx is None or self._ephemeral_dhcp_ctx.lease is None ) @azure_ds_telemetry_reporter def crawl_metadata(self): """Walk all instance metadata sources returning a dict on success. @return: A dictionary of any metadata content for this instance. @raise: InvalidMetaDataException when the expected metadata service is unavailable, broken or disabled. """ crawled_data = {} # azure removes/ejects the cdrom containing the ovf-env.xml # file on reboot. So, in order to successfully reboot we # need to look in the datadir and consider that valid ddir = self.ds_cfg["data_dir"] # The order in which the candidates are inserted matters here, because # it determines the value of ret. More specifically, the first one in # the candidate list determines the path to take in order to get the # metadata we need. ovf_source = None md = {"local-hostname": ""} cfg = {"system_info": {"default_user": {"name": ""}}} userdata_raw = "" files = {} for src in list_possible_azure_ds(self.seed_dir, ddir): try: if src.startswith("/dev/"): if util.is_FreeBSD(): md, userdata_raw, cfg, files = util.mount_cb( src, load_azure_ds_dir, mtype="udf" ) else: md, userdata_raw, cfg, files = util.mount_cb( src, load_azure_ds_dir ) # save the device for ejection later self._iso_dev = src else: md, userdata_raw, cfg, files = load_azure_ds_dir(src) ovf_source = src report_diagnostic_event( "Found provisioning metadata in %s" % ovf_source, logger_func=LOG.debug, ) break except NonAzureDataSource: report_diagnostic_event( "Did not find Azure data source in %s" % src, logger_func=LOG.debug, ) continue except util.MountFailedError: report_diagnostic_event( "%s was not mountable" % src, logger_func=LOG.debug ) continue except BrokenAzureDataSource as exc: msg = "BrokenAzureDataSource: %s" % exc report_diagnostic_event(msg, logger_func=LOG.error) raise sources.InvalidMetaDataException(msg) else: msg = ( "Unable to find provisioning media, falling back to IMDS " "metadata. Be aware that IMDS metadata does not support " "admin passwords or custom-data (user-data only)." ) report_diagnostic_event(msg, logger_func=LOG.warning) # If we read OVF from attached media, we are provisioning. If OVF # is not found, we are probably provisioning on a system which does # not have UDF support. In either case, require IMDS metadata. # If we require IMDS metadata, try harder to obtain networking, waiting # for at least 20 minutes. Otherwise only wait 5 minutes. requires_imds_metadata = bool(self._iso_dev) or ovf_source is None timeout_minutes = 20 if requires_imds_metadata else 5 try: self._setup_ephemeral_networking(timeout_minutes=timeout_minutes) except NoDHCPLeaseError: pass imds_md = {} if self._is_ephemeral_networking_up(): imds_md = self.get_metadata_from_imds() if not imds_md and ovf_source is None: msg = "No OVF or IMDS available" report_diagnostic_event(msg) raise sources.InvalidMetaDataException(msg) # Refresh PPS type using metadata. pps_type = self._determine_pps_type(cfg, imds_md) if pps_type != PPSType.NONE: if util.is_FreeBSD(): msg = "Free BSD is not supported for PPS VMs" report_diagnostic_event(msg, logger_func=LOG.error) raise sources.InvalidMetaDataException(msg) if pps_type == PPSType.SAVABLE: self._wait_for_all_nics_ready() elif pps_type == PPSType.OS_DISK: self._report_ready_for_pps(create_marker=False) self._wait_for_pps_os_disk_shutdown() md, userdata_raw, cfg, files = self._reprovision() # fetch metadata again as it has changed after reprovisioning imds_md = self.get_metadata_from_imds() # Report errors if IMDS network configuration is missing data. self.validate_imds_network_metadata(imds_md=imds_md) self.seed = ovf_source or "IMDS" crawled_data.update( { "cfg": cfg, "files": files, "metadata": util.mergemanydict([md, {"imds": imds_md}]), "userdata_raw": userdata_raw, } ) imds_username = _username_from_imds(imds_md) imds_hostname = _hostname_from_imds(imds_md) imds_disable_password = _disable_password_from_imds(imds_md) if imds_username: LOG.debug("Username retrieved from IMDS: %s", imds_username) cfg["system_info"]["default_user"]["name"] = imds_username if imds_hostname: LOG.debug("Hostname retrieved from IMDS: %s", imds_hostname) crawled_data["metadata"]["local-hostname"] = imds_hostname if imds_disable_password: LOG.debug( "Disable password retrieved from IMDS: %s", imds_disable_password, ) crawled_data["metadata"][ "disable_password" ] = imds_disable_password if self.seed == "IMDS" and not crawled_data["files"]: try: contents = build_minimal_ovf( username=imds_username, # pyright: ignore hostname=imds_hostname, # pyright: ignore disableSshPwd=imds_disable_password, # pyright: ignore ) crawled_data["files"] = {"ovf-env.xml": contents} except Exception as e: report_diagnostic_event( "Failed to construct OVF from IMDS data %s" % e, logger_func=LOG.debug, ) # only use userdata from imds if OVF did not provide custom data # userdata provided by IMDS is always base64 encoded if not userdata_raw: imds_userdata = _userdata_from_imds(imds_md) if imds_userdata: LOG.debug("Retrieved userdata from IMDS") try: crawled_data["userdata_raw"] = base64.b64decode( "".join(imds_userdata.split()) ) except Exception: report_diagnostic_event( "Bad userdata in IMDS", logger_func=LOG.warning ) if ovf_source == ddir: report_diagnostic_event( "using files cached in %s" % ddir, logger_func=LOG.debug ) seed = _get_random_seed() if seed: crawled_data["metadata"]["random_seed"] = seed crawled_data["metadata"]["instance-id"] = self._iid() if self._negotiated is False and self._is_ephemeral_networking_up(): # Report ready and fetch public-keys from Wireserver, if required. pubkey_info = self._determine_wireserver_pubkey_info( cfg=cfg, imds_md=imds_md ) try: ssh_keys = self._report_ready(pubkey_info=pubkey_info) except Exception: # Failed to report ready, but continue with best effort. pass else: LOG.debug("negotiating returned %s", ssh_keys) if ssh_keys: crawled_data["metadata"]["public-keys"] = ssh_keys self._cleanup_markers() self._negotiated = True return crawled_data @azure_ds_telemetry_reporter def get_metadata_from_imds(self, retries: int = 10) -> Dict: try: return imds.fetch_metadata_with_api_fallback(retries=retries) except (UrlError, ValueError) as error: report_diagnostic_event( "Ignoring IMDS metadata due to: %s" % error, logger_func=LOG.warning, ) return {} def clear_cached_attrs(self, attr_defaults=()): """Reset any cached class attributes to defaults.""" super(DataSourceAzure, self).clear_cached_attrs(attr_defaults) self._metadata_imds = sources.UNSET @azure_ds_telemetry_reporter def _get_data(self): """Crawl and process datasource metadata caching metadata as attrs. @return: True on success, False on error, invalid or disabled datasource. """ if not is_platform_viable(Path(self.seed_dir)): return False try: get_boot_telemetry() except Exception as e: LOG.warning("Failed to get boot telemetry: %s", e) try: get_system_info() except Exception as e: LOG.warning("Failed to get system information: %s", e) self.distro.networking.blacklist_drivers = BLACKLIST_DRIVERS try: crawled_data = util.log_time( logfunc=LOG.debug, msg="Crawl of metadata service", func=self.crawl_metadata, ) except Exception as e: report_diagnostic_event( "Could not crawl Azure metadata: %s" % e, logger_func=LOG.error ) self._report_failure() return False finally: self._teardown_ephemeral_networking() if ( self.distro and self.distro.name == "ubuntu" and self.ds_cfg.get("apply_network_config") ): maybe_remove_ubuntu_network_config_scripts() # Process crawled data and augment with various config defaults # Only merge in default cloud config related to the ephemeral disk # if the ephemeral disk exists devpath = RESOURCE_DISK_PATH if os.path.exists(devpath): report_diagnostic_event( "Ephemeral resource disk '%s' exists. " "Merging default Azure cloud ephemeral disk configs." % devpath, logger_func=LOG.debug, ) self.cfg = util.mergemanydict( [crawled_data["cfg"], BUILTIN_CLOUD_EPHEMERAL_DISK_CONFIG] ) else: report_diagnostic_event( "Ephemeral resource disk '%s' does not exist. " "Not merging default Azure cloud ephemeral disk configs." % devpath, logger_func=LOG.debug, ) self.cfg = crawled_data["cfg"] self._metadata_imds = crawled_data["metadata"]["imds"] self.metadata = util.mergemanydict( [crawled_data["metadata"], DEFAULT_METADATA] ) self.userdata_raw = crawled_data["userdata_raw"] # walinux agent writes files world readable, but expects # the directory to be protected. write_files( self.ds_cfg["data_dir"], crawled_data["files"], dirmode=0o700 ) return True def get_instance_id(self): if not self.metadata or "instance-id" not in self.metadata: return self._iid() return str(self.metadata["instance-id"]) def device_name_to_device(self, name): return self.ds_cfg["disk_aliases"].get(name) @azure_ds_telemetry_reporter def get_public_ssh_keys(self) -> List[str]: """ Retrieve public SSH keys. """ try: return self._get_public_keys_from_imds(self.metadata["imds"]) except (KeyError, ValueError): pass return self._get_public_keys_from_ovf() def _get_public_keys_from_imds(self, imds_md: dict) -> List[str]: """Get SSH keys from IMDS metadata. :raises KeyError: if IMDS metadata is malformed/missing. :raises ValueError: if key format is not supported. :returns: List of keys. """ try: ssh_keys = [ public_key["keyData"] for public_key in imds_md["compute"]["publicKeys"] ] except KeyError: log_msg = "No SSH keys found in IMDS metadata" report_diagnostic_event(log_msg, logger_func=LOG.debug) raise if any(not _key_is_openssh_formatted(key=key) for key in ssh_keys): log_msg = "Key(s) not in OpenSSH format" report_diagnostic_event(log_msg, logger_func=LOG.debug) raise ValueError(log_msg) log_msg = "Retrieved {} keys from IMDS".format(len(ssh_keys)) report_diagnostic_event(log_msg, logger_func=LOG.debug) return ssh_keys def _get_public_keys_from_ovf(self) -> List[str]: """Get SSH keys that were fetched from wireserver. :returns: List of keys. """ ssh_keys = [] try: ssh_keys = self.metadata["public-keys"] log_msg = "Retrieved {} keys from OVF".format(len(ssh_keys)) report_diagnostic_event(log_msg, logger_func=LOG.debug) except KeyError: log_msg = "No keys available from OVF" report_diagnostic_event(log_msg, logger_func=LOG.debug) return ssh_keys def get_config_obj(self): return self.cfg def check_instance_id(self, sys_cfg): # quickly (local check only) if self.instance_id is still valid return sources.instance_id_matches_system_uuid(self.get_instance_id()) def _iid(self, previous=None): prev_iid_path = os.path.join( self.paths.get_cpath("data"), "instance-id" ) # Older kernels than 4.15 will have UPPERCASE product_uuid. # We don't want Azure to react to an UPPER/lower difference as a new # instance id as it rewrites SSH host keys. # LP: #1835584 system_uuid = dmi.read_dmi_data("system-uuid") if system_uuid is None: raise RuntimeError("failed to read system-uuid") iid = system_uuid.lower() if os.path.exists(prev_iid_path): previous = util.load_file(prev_iid_path).strip() if previous.lower() == iid: # If uppercase/lowercase equivalent, return the previous value # to avoid new instance id. return previous if is_byte_swapped(previous.lower(), iid): return previous return iid @azure_ds_telemetry_reporter def _wait_for_nic_detach(self, nl_sock): """Use the netlink socket provided to wait for nic detach event. NOTE: The function doesn't close the socket. The caller owns closing the socket and disposing it safely. """ try: ifname = None # Preprovisioned VM will only have one NIC, and it gets # detached immediately after deployment. with events.ReportEventStack( name="wait-for-nic-detach", description="wait for nic detach", parent=azure_ds_reporter, ): ifname = netlink.wait_for_nic_detach_event(nl_sock) if ifname is None: msg = ( "Preprovisioned nic not detached as expected. " "Proceeding without failing." ) report_diagnostic_event(msg, logger_func=LOG.warning) else: report_diagnostic_event( "The preprovisioned nic %s is detached" % ifname, logger_func=LOG.warning, ) except AssertionError as error: report_diagnostic_event(str(error), logger_func=LOG.error) raise @azure_ds_telemetry_reporter def wait_for_link_up( self, ifname: str, retries: int = 100, retry_sleep: float = 0.1 ): for i in range(retries): if self.distro.networking.try_set_link_up(ifname): report_diagnostic_event( "The link %s is up." % ifname, logger_func=LOG.info ) break if (i + 1) < retries: sleep(retry_sleep) else: report_diagnostic_event( "The link %s is not up after %f seconds, continuing anyways." % (ifname, retries * retry_sleep), logger_func=LOG.info, ) @azure_ds_telemetry_reporter def _create_report_ready_marker(self): path = self._reported_ready_marker_file LOG.info("Creating a marker file to report ready: %s", path) util.write_file( path, "{pid}: {time}\n".format(pid=os.getpid(), time=time()) ) report_diagnostic_event( "Successfully created reported ready marker file " "while in the preprovisioning pool.", logger_func=LOG.debug, ) @azure_ds_telemetry_reporter def _report_ready_for_pps( self, *, create_marker: bool = True, expect_url_error: bool = False, ) -> None: """Report ready for PPS, creating the marker file upon completion. :raises sources.InvalidMetaDataException: On error reporting ready. """ try: self._report_ready() except Exception as error: # Ignore HTTP failures for Savable PPS as the call may appear to # fail if the network interface is unplugged or the VM is # suspended before we process the response. Worst case scenario # is that we failed to report ready for source PPS and this VM # will be discarded shortly, no harm done. if expect_url_error and isinstance(error, UrlError): report_diagnostic_event( "Ignoring http call failure, it was expected.", logger_func=LOG.debug, ) # The iso was ejected prior to reporting ready. self._iso_dev = None else: msg = ( "Failed reporting ready while in the preprovisioning pool." ) report_diagnostic_event(msg, logger_func=LOG.error) raise sources.InvalidMetaDataException(msg) from error if create_marker: self._create_report_ready_marker() @azure_ds_telemetry_reporter def _wait_for_pps_os_disk_shutdown(self): report_diagnostic_event( "Waiting for host to shutdown VM...", logger_func=LOG.info, ) sleep(31536000) raise BrokenAzureDataSource("Shutdown failure for PPS disk.") @azure_ds_telemetry_reporter def _check_if_nic_is_primary(self, ifname: str) -> bool: """Check if a given interface is the primary nic or not.""" # For now, only a VM's primary NIC can contact IMDS and WireServer. If # DHCP fails for a NIC, we have no mechanism to determine if the NIC is # primary or secondary. In this case, retry DHCP until successful. self._setup_ephemeral_networking(iface=ifname, timeout_minutes=20) # Primary nic detection will be optimized in the future. The fact that # primary nic is being attached first helps here. Otherwise each nic # could add several seconds of delay. imds_md = self.get_metadata_from_imds(retries=300) if imds_md: # Only primary NIC will get a response from IMDS. LOG.info("%s is the primary nic", ifname) return True # If we are not the primary nic, then clean the dhcp context. LOG.warning( "Failed to fetch IMDS metadata using nic %s. " "Assuming this is not the primary nic.", ifname, ) self._teardown_ephemeral_networking() return False @azure_ds_telemetry_reporter def _wait_for_hot_attached_primary_nic(self, nl_sock): """Wait until the primary nic for the vm is hot-attached.""" LOG.info("Waiting for primary nic to be hot-attached") try: nics_found = [] primary_nic_found = False # Wait for netlink nic attach events. After the first nic is # attached, we are already in the customer vm deployment path and # so everything from then on should happen fast and avoid # unnecessary delays wherever possible. while True: ifname = None with events.ReportEventStack( name="wait-for-nic-attach", description=( "wait for nic attach after %d nics have been attached" % len(nics_found) ), parent=azure_ds_reporter, ): ifname = netlink.wait_for_nic_attach_event( nl_sock, nics_found ) # wait_for_nic_attach_event guarantees that ifname it not None nics_found.append(ifname) report_diagnostic_event( "Detected nic %s attached." % ifname, logger_func=LOG.info ) # Attempt to bring the interface's operating state to # UP in case it is not already. self.wait_for_link_up(ifname) # If primary nic is not found, check if this is it. The # platform will attach the primary nic first so we # won't be in primary_nic_found = false state for long. if not primary_nic_found: LOG.info("Checking if %s is the primary nic", ifname) primary_nic_found = self._check_if_nic_is_primary(ifname) # Exit criteria: check if we've discovered primary nic if primary_nic_found: LOG.info("Found primary nic for this VM.") break except AssertionError as error: report_diagnostic_event(str(error), logger_func=LOG.error) @azure_ds_telemetry_reporter def _wait_for_all_nics_ready(self): """Wait for nic(s) to be hot-attached. There may be multiple nics depending on the customer request. But only primary nic would be able to communicate with wireserver and IMDS. So we detect and save the primary nic to be used later. """ nl_sock = None try: nl_sock = netlink.create_bound_netlink_socket() self._report_ready_for_pps(expect_url_error=True) try: self._teardown_ephemeral_networking() except subp.ProcessExecutionError as e: report_diagnostic_event( "Ignoring failure while tearing down networking, " "NIC was likely unplugged: %r" % e, logger_func=LOG.info, ) self._ephemeral_dhcp_ctx = None self._wait_for_nic_detach(nl_sock) self._wait_for_hot_attached_primary_nic(nl_sock) except netlink.NetlinkCreateSocketError as e: report_diagnostic_event(str(e), logger_func=LOG.warning) raise finally: if nl_sock: nl_sock.close() @azure_ds_telemetry_reporter def _poll_imds(self): """Poll IMDS for the new provisioning data until we get a valid response. Then return the returned JSON object.""" nl_sock = None report_ready = bool( not os.path.isfile(self._reported_ready_marker_file) ) dhcp_attempts = 0 if report_ready: # Networking must be up for netlink to detect # media disconnect/connect. It may be down to due # initial DHCP failure, if so check for it and retry, # ensuring we flag it as required. if not self._is_ephemeral_networking_up(): self._setup_ephemeral_networking(timeout_minutes=20) try: if ( self._ephemeral_dhcp_ctx is None or self._ephemeral_dhcp_ctx.iface is None ): raise RuntimeError("Missing ephemeral context") iface = self._ephemeral_dhcp_ctx.iface nl_sock = netlink.create_bound_netlink_socket() self._report_ready_for_pps() LOG.debug( "Wait for vnetswitch to happen on %s", iface, ) with events.ReportEventStack( name="wait-for-media-disconnect-connect", description="wait for vnet switch", parent=azure_ds_reporter, ): try: netlink.wait_for_media_disconnect_connect( nl_sock, iface ) except AssertionError as e: report_diagnostic_event( "Error while waiting for vnet switch: %s" % e, logger_func=LOG.error, ) except netlink.NetlinkCreateSocketError as e: report_diagnostic_event( "Failed to create bound netlink socket: %s" % e, logger_func=LOG.warning, ) raise sources.InvalidMetaDataException( "Failed to report ready while in provisioning pool." ) from e except NoDHCPLeaseError as e: report_diagnostic_event( "DHCP failed while in provisioning pool", logger_func=LOG.warning, ) raise sources.InvalidMetaDataException( "Failed to report ready while in provisioning pool." ) from e finally: if nl_sock: nl_sock.close() # Teardown old network configuration. self._teardown_ephemeral_networking() reprovision_data = None while not reprovision_data: if not self._is_ephemeral_networking_up(): dhcp_attempts += 1 try: self._setup_ephemeral_networking(timeout_minutes=5) except NoDHCPLeaseError: continue with events.ReportEventStack( name="get-reprovision-data-from-imds", description="get reprovision data from imds", parent=azure_ds_reporter, ): try: reprovision_data = imds.fetch_reprovision_data() except UrlError: self._teardown_ephemeral_networking() continue report_diagnostic_event( "attempted dhcp %d times after reuse" % dhcp_attempts, logger_func=LOG.debug, ) return reprovision_data @azure_ds_telemetry_reporter def _report_failure(self) -> bool: """Tells the Azure fabric that provisioning has failed. @param description: A description of the error encountered. @return: The success status of sending the failure signal. """ if self._is_ephemeral_networking_up(): try: report_diagnostic_event( "Using cached ephemeral dhcp context " "to report failure to Azure", logger_func=LOG.debug, ) report_failure_to_fabric(endpoint=self._wireserver_endpoint) return True except Exception as e: report_diagnostic_event( "Failed to report failure using " "cached ephemeral dhcp context: %s" % e, logger_func=LOG.error, ) try: report_diagnostic_event( "Using new ephemeral dhcp to report failure to Azure", logger_func=LOG.debug, ) self._teardown_ephemeral_networking() try: self._setup_ephemeral_networking(timeout_minutes=20) except NoDHCPLeaseError: # Reporting failure will fail, but it will emit telemetry. pass report_failure_to_fabric(endpoint=self._wireserver_endpoint) return True except Exception as e: report_diagnostic_event( "Failed to report failure using new ephemeral dhcp: %s" % e, logger_func=LOG.debug, ) return False @azure_ds_telemetry_reporter def _report_ready( self, *, pubkey_info: Optional[List[str]] = None ) -> Optional[List[str]]: """Tells the fabric provisioning has completed. :param pubkey_info: Fingerprints of keys to request from Wireserver. :raises Exception: if failed to report. :returns: List of SSH keys, if requested. """ try: data = get_metadata_from_fabric( endpoint=self._wireserver_endpoint, iso_dev=self._iso_dev, pubkey_info=pubkey_info, ) except Exception as e: report_diagnostic_event( "Error communicating with Azure fabric; You may experience " "connectivity issues: %s" % e, logger_func=LOG.warning, ) raise # Reporting ready ejected OVF media, no need to do so again. self._iso_dev = None return data def _ppstype_from_imds(self, imds_md: dict) -> Optional[str]: try: return imds_md["extended"]["compute"]["ppsType"] except Exception as e: report_diagnostic_event( "Could not retrieve pps configuration from IMDS: %s" % e, logger_func=LOG.debug, ) return None def _determine_pps_type(self, ovf_cfg: dict, imds_md: dict) -> PPSType: """Determine PPS type using OVF, IMDS data, and reprovision marker.""" if os.path.isfile(self._reported_ready_marker_file): pps_type = PPSType.UNKNOWN elif ( ovf_cfg.get("PreprovisionedVMType", None) == PPSType.SAVABLE.value or self._ppstype_from_imds(imds_md) == PPSType.SAVABLE.value ): pps_type = PPSType.SAVABLE elif ( ovf_cfg.get("PreprovisionedVMType", None) == PPSType.OS_DISK.value or self._ppstype_from_imds(imds_md) == PPSType.OS_DISK.value ): pps_type = PPSType.OS_DISK elif ( ovf_cfg.get("PreprovisionedVm") is True or ovf_cfg.get("PreprovisionedVMType", None) == PPSType.RUNNING.value or self._ppstype_from_imds(imds_md) == PPSType.RUNNING.value ): pps_type = PPSType.RUNNING else: pps_type = PPSType.NONE report_diagnostic_event( "PPS type: %s" % pps_type.value, logger_func=LOG.info ) return pps_type @azure_ds_telemetry_reporter def _reprovision(self): """Initiate the reprovisioning workflow. Ephemeral networking is up upon successful reprovisioning. """ contents = self._poll_imds() with events.ReportEventStack( name="reprovisioning-read-azure-ovf", description="read azure ovf during reprovisioning", parent=azure_ds_reporter, ): md, ud, cfg = read_azure_ovf(contents) return (md, ud, cfg, {"ovf-env.xml": contents}) @azure_ds_telemetry_reporter def _determine_wireserver_pubkey_info( self, *, cfg: dict, imds_md: dict ) -> Optional[List[str]]: """Determine the fingerprints we need to retrieve from Wireserver. :return: List of keys to request from Wireserver, if any, else None. """ pubkey_info: Optional[List[str]] = None try: self._get_public_keys_from_imds(imds_md) except (KeyError, ValueError): pubkey_info = cfg.get("_pubkeys", None) log_msg = "Retrieved {} fingerprints from OVF".format( len(pubkey_info) if pubkey_info is not None else 0 ) report_diagnostic_event(log_msg, logger_func=LOG.debug) return pubkey_info def _cleanup_markers(self): """Cleanup any marker files.""" util.del_file(self._reported_ready_marker_file) @azure_ds_telemetry_reporter def activate(self, cfg, is_new_instance): instance_dir = self.paths.get_ipath_cur() try: address_ephemeral_resize( instance_dir, is_new_instance=is_new_instance, preserve_ntfs=self.ds_cfg.get(DS_CFG_KEY_PRESERVE_NTFS, False), ) finally: push_log_to_kvp(self.sys_cfg["def_log_file"]) return @property def availability_zone(self): return ( self.metadata.get("imds", {}) .get("compute", {}) .get("platformFaultDomain") ) @azure_ds_telemetry_reporter def _generate_network_config(self): """Generate network configuration according to configuration.""" # Use IMDS network metadata, if configured. if ( self._metadata_imds and self._metadata_imds != sources.UNSET and self.ds_cfg.get("apply_network_config") ): try: return generate_network_config_from_instance_network_metadata( self._metadata_imds["network"] ) except Exception as e: LOG.error( "Failed generating network config " "from IMDS network metadata: %s", str(e), ) # Generate fallback configuration. try: return _generate_network_config_from_fallback_config() except Exception as e: LOG.error("Failed generating fallback network config: %s", str(e)) return {} @property def network_config(self): """Provide network configuration v2 dictionary.""" # Use cached config, if present. if self._network_config and self._network_config != sources.UNSET: return self._network_config self._network_config = self._generate_network_config() return self._network_config @property def region(self): return self.metadata.get("imds", {}).get("compute", {}).get("location") @azure_ds_telemetry_reporter def validate_imds_network_metadata(self, imds_md: dict) -> bool: """Validate IMDS network config and report telemetry for errors.""" local_macs = get_hv_netvsc_macs_normalized() try: network_config = imds_md["network"] imds_macs = [ normalize_mac_address(i["macAddress"]) for i in network_config["interface"] ] except KeyError: report_diagnostic_event( "IMDS network metadata has incomplete configuration: %r" % imds_md.get("network"), logger_func=LOG.warning, ) return False missing_macs = [m for m in local_macs if m not in imds_macs] if not missing_macs: return True report_diagnostic_event( "IMDS network metadata is missing configuration for NICs %r: %r" % (missing_macs, network_config), logger_func=LOG.warning, ) if not self._ephemeral_dhcp_ctx or not self._ephemeral_dhcp_ctx.iface: # No primary interface to check against. return False primary_mac = net.get_interface_mac(self._ephemeral_dhcp_ctx.iface) if not primary_mac or not isinstance(primary_mac, str): # Unexpected data for primary interface. return False primary_mac = normalize_mac_address(primary_mac) if primary_mac in missing_macs: report_diagnostic_event( "IMDS network metadata is missing primary NIC %r: %r" % (primary_mac, network_config), logger_func=LOG.warning, ) return False def _username_from_imds(imds_data): try: return imds_data["compute"]["osProfile"]["adminUsername"] except KeyError: return None def _userdata_from_imds(imds_data): try: return imds_data["compute"]["userData"] except KeyError: return None def _hostname_from_imds(imds_data): try: return imds_data["compute"]["osProfile"]["computerName"] except KeyError: return None def _disable_password_from_imds(imds_data): try: return ( imds_data["compute"]["osProfile"]["disablePasswordAuthentication"] == "true" ) except KeyError: return None def _key_is_openssh_formatted(key): """ Validate whether or not the key is OpenSSH-formatted. """ # See https://bugs.launchpad.net/cloud-init/+bug/1910835 if "\r\n" in key.strip(): return False parser = ssh_util.AuthKeyLineParser() try: akl = parser.parse(key) except TypeError: return False return akl.keytype is not None def _partitions_on_device(devpath, maxnum=16): # return a list of tuples (ptnum, path) for each part on devpath for suff in ("-part", "p", ""): found = [] for pnum in range(1, maxnum): ppath = devpath + suff + str(pnum) if os.path.exists(ppath): found.append((pnum, os.path.realpath(ppath))) if found: return found return [] @azure_ds_telemetry_reporter def _has_ntfs_filesystem(devpath): ntfs_devices = util.find_devs_with("TYPE=ntfs", no_cache=True) LOG.debug("ntfs_devices found = %s", ntfs_devices) return os.path.realpath(devpath) in ntfs_devices @azure_ds_telemetry_reporter def can_dev_be_reformatted(devpath, preserve_ntfs): """Determine if the ephemeral drive at devpath should be reformatted. A fresh ephemeral disk is formatted by Azure and will: a.) have a partition table (dos or gpt) b.) have 1 partition that is ntfs formatted, or have 2 partitions with the second partition ntfs formatted. (larger instances with >2TB ephemeral disk have gpt, and will have a microsoft reserved partition as part 1. LP: #1686514) c.) the ntfs partition will have no files other than possibly 'dataloss_warning_readme.txt' User can indicate that NTFS should never be destroyed by setting DS_CFG_KEY_PRESERVE_NTFS in dscfg. If data is found on NTFS, user is warned to set DS_CFG_KEY_PRESERVE_NTFS to make sure cloud-init does not accidentally wipe their data. If cloud-init cannot mount the disk to check for data, destruction will be allowed, unless the dscfg key is set.""" if preserve_ntfs: msg = "config says to never destroy NTFS (%s.%s), skipping checks" % ( ".".join(DS_CFG_PATH), DS_CFG_KEY_PRESERVE_NTFS, ) return False, msg if not os.path.exists(devpath): return False, "device %s does not exist" % devpath LOG.debug( "Resolving realpath of %s -> %s", devpath, os.path.realpath(devpath) ) # devpath of /dev/sd[a-z] or /dev/disk/cloud/azure_resource # where partitions are "<devpath>1" or "<devpath>-part1" or "<devpath>p1" partitions = _partitions_on_device(devpath) if len(partitions) == 0: return False, "device %s was not partitioned" % devpath elif len(partitions) > 2: msg = "device %s had 3 or more partitions: %s" % ( devpath, " ".join([p[1] for p in partitions]), ) return False, msg elif len(partitions) == 2: cand_part, cand_path = partitions[1] else: cand_part, cand_path = partitions[0] if not _has_ntfs_filesystem(cand_path): msg = "partition %s (%s) on device %s was not ntfs formatted" % ( cand_part, cand_path, devpath, ) return False, msg @azure_ds_telemetry_reporter def count_files(mp): ignored = set(["dataloss_warning_readme.txt"]) return len([f for f in os.listdir(mp) if f.lower() not in ignored]) bmsg = "partition %s (%s) on device %s was ntfs formatted" % ( cand_part, cand_path, devpath, ) with events.ReportEventStack( name="mount-ntfs-and-count", description="mount-ntfs-and-count", parent=azure_ds_reporter, ) as evt: try: file_count = util.mount_cb( cand_path, count_files, mtype="ntfs", update_env_for_mount={"LANG": "C"}, ) except util.MountFailedError as e: evt.description = "cannot mount ntfs" if "unknown filesystem type 'ntfs'" in str(e): return ( True, ( bmsg + " but this system cannot mount NTFS," " assuming there are no important files." " Formatting allowed." ), ) return False, bmsg + " but mount of %s failed: %s" % (cand_part, e) if file_count != 0: evt.description = "mounted and counted %d files" % file_count LOG.warning( "it looks like you're using NTFS on the ephemeral" " disk, to ensure that filesystem does not get wiped," " set %s.%s in config", ".".join(DS_CFG_PATH), DS_CFG_KEY_PRESERVE_NTFS, ) return False, bmsg + " but had %d files on it." % file_count return True, bmsg + " and had no important files. Safe for reformatting." @azure_ds_telemetry_reporter def address_ephemeral_resize( instance_dir: str, devpath: str = RESOURCE_DISK_PATH, is_new_instance: bool = False, preserve_ntfs: bool = False, ): if not os.path.exists(devpath): report_diagnostic_event( "Ephemeral resource disk '%s' does not exist." % devpath, logger_func=LOG.debug, ) return else: report_diagnostic_event( "Ephemeral resource disk '%s' exists." % devpath, logger_func=LOG.debug, ) result = False msg = None if is_new_instance: result, msg = (True, "First instance boot.") else: result, msg = can_dev_be_reformatted(devpath, preserve_ntfs) LOG.debug("reformattable=%s: %s", result, msg) if not result: return for mod in ["disk_setup", "mounts"]: sempath = os.path.join(instance_dir, "sem", "config_" + mod) bmsg = 'Marker "%s" for module "%s"' % (sempath, mod) if os.path.exists(sempath): try: os.unlink(sempath) LOG.debug("%s removed.", bmsg) except FileNotFoundError as e: LOG.warning("%s: remove failed! (%s)", bmsg, e) else: LOG.debug("%s did not exist.", bmsg) return @azure_ds_telemetry_reporter def write_files(datadir, files, dirmode=None): def _redact_password(cnt, fname): """Azure provides the UserPassword in plain text. So we redact it""" try: root = ET.fromstring(cnt) for elem in root.iter(): if ( "UserPassword" in elem.tag and elem.text != DEF_PASSWD_REDACTION ): elem.text = DEF_PASSWD_REDACTION return ET.tostring(root) except Exception: LOG.critical("failed to redact userpassword in %s", fname) return cnt if not datadir: return if not files: files = {} util.ensure_dir(datadir, dirmode) for (name, content) in files.items(): fname = os.path.join(datadir, name) if "ovf-env.xml" in name: content = _redact_password(content, fname) util.write_file(filename=fname, content=content, mode=0o600) @azure_ds_telemetry_reporter def read_azure_ovf(contents): """Parse OVF XML contents. :return: Tuple of metadata, configuration, userdata dicts. :raises NonAzureDataSource: if XML is not in Azure's format. :raises BrokenAzureDataSource: if XML is unparseable or invalid. """ ovf_env = OvfEnvXml.parse_text(contents) md: Dict[str, Any] = {} cfg = {} ud = ovf_env.custom_data or "" if ovf_env.hostname: md["local-hostname"] = ovf_env.hostname if ovf_env.public_keys: cfg["_pubkeys"] = ovf_env.public_keys if ovf_env.disable_ssh_password_auth is not None: cfg["ssh_pwauth"] = not ovf_env.disable_ssh_password_auth elif ovf_env.password: cfg["ssh_pwauth"] = True defuser = {} if ovf_env.username: defuser["name"] = ovf_env.username if ovf_env.password: defuser["lock_passwd"] = False if DEF_PASSWD_REDACTION != ovf_env.password: defuser["hashed_passwd"] = encrypt_pass(ovf_env.password) if defuser: cfg["system_info"] = {"default_user": defuser} cfg["PreprovisionedVm"] = ovf_env.preprovisioned_vm report_diagnostic_event( "PreprovisionedVm: %s" % ovf_env.preprovisioned_vm, logger_func=LOG.info, ) cfg["PreprovisionedVMType"] = ovf_env.preprovisioned_vm_type report_diagnostic_event( "PreprovisionedVMType: %s" % ovf_env.preprovisioned_vm_type, logger_func=LOG.info, ) return (md, ud, cfg) def encrypt_pass(password, salt_id="$6$"): return crypt.crypt(password, salt_id + util.rand_str(strlen=16)) @azure_ds_telemetry_reporter def _check_freebsd_cdrom(cdrom_dev): """Return boolean indicating path to cdrom device has content.""" try: with open(cdrom_dev) as fp: fp.read(1024) return True except IOError: LOG.debug("cdrom (%s) is not configured", cdrom_dev) return False @azure_ds_telemetry_reporter def _get_random_seed(source=PLATFORM_ENTROPY_SOURCE): """Return content random seed file if available, otherwise, return None.""" # azure / hyper-v provides random data here # now update ds_cfg to reflect contents pass in config if source is None: return None seed = util.load_file(source, quiet=True, decode=False) # The seed generally contains non-Unicode characters. load_file puts # them into bytes (in python 3). # bytes is a non-serializable type, and the handler load_file # uses applies b64 encoding *again* to handle it. The simplest solution # is to just b64encode the data and then decode it to a serializable # string. Same number of bits of entropy, just with 25% more zeroes. # There's no need to undo this base64-encoding when the random seed is # actually used in cc_seed_random.py. return base64.b64encode(seed).decode() # pyright: ignore @azure_ds_telemetry_reporter def list_possible_azure_ds(seed, cache_dir): yield seed yield DEFAULT_PROVISIONING_ISO_DEV if util.is_FreeBSD(): cdrom_dev = "/dev/cd0" if _check_freebsd_cdrom(cdrom_dev): yield cdrom_dev else: for fstype in ("iso9660", "udf"): yield from util.find_devs_with("TYPE=%s" % fstype) if cache_dir: yield cache_dir @azure_ds_telemetry_reporter def load_azure_ds_dir(source_dir): ovf_file = os.path.join(source_dir, "ovf-env.xml") if not os.path.isfile(ovf_file): raise NonAzureDataSource("No ovf-env file found") with open(ovf_file, "rb") as fp: contents = fp.read() md, ud, cfg = read_azure_ovf(contents) return (md, ud, cfg, {"ovf-env.xml": contents}) @azure_ds_telemetry_reporter def generate_network_config_from_instance_network_metadata( network_metadata: dict, ) -> dict: """Convert imds network metadata dictionary to network v2 configuration. :param: network_metadata: Dict of "network" key from instance metdata. :return: Dictionary containing network version 2 standard configuration. """ netconfig: Dict[str, Any] = {"version": 2, "ethernets": {}} for idx, intf in enumerate(network_metadata["interface"]): has_ip_address = False # First IPv4 and/or IPv6 address will be obtained via DHCP. # Any additional IPs of each type will be set as static # addresses. nicname = "eth{idx}".format(idx=idx) dhcp_override = {"route-metric": (idx + 1) * 100} dev_config: Dict[str, Any] = { "dhcp4": True, "dhcp4-overrides": dhcp_override, "dhcp6": False, } for addr_type in ("ipv4", "ipv6"): addresses = intf.get(addr_type, {}).get("ipAddress", []) # If there are no available IP addresses, then we don't # want to add this interface to the generated config. if not addresses: LOG.debug("No %s addresses found for: %r", addr_type, intf) continue has_ip_address = True if addr_type == "ipv4": default_prefix = "24" else: default_prefix = "128" if addresses: dev_config["dhcp6"] = True # non-primary interfaces should have a higher # route-metric (cost) so default routes prefer # primary nic due to lower route-metric value dev_config["dhcp6-overrides"] = dhcp_override for addr in addresses[1:]: # Append static address config for ip > 1 netPrefix = intf[addr_type]["subnet"][0].get( "prefix", default_prefix ) privateIp = addr["privateIpAddress"] if not dev_config.get("addresses"): dev_config["addresses"] = [] dev_config["addresses"].append( "{ip}/{prefix}".format(ip=privateIp, prefix=netPrefix) ) if dev_config and has_ip_address: mac = normalize_mac_address(intf["macAddress"]) dev_config.update( {"match": {"macaddress": mac.lower()}, "set-name": nicname} ) driver = determine_device_driver_for_mac(mac) if driver: dev_config["match"]["driver"] = driver netconfig["ethernets"][nicname] = dev_config continue LOG.debug( "No configuration for: %s (dev_config=%r) (has_ip_address=%r)", nicname, dev_config, has_ip_address, ) return netconfig @azure_ds_telemetry_reporter def _generate_network_config_from_fallback_config() -> dict: """Generate fallback network config excluding blacklisted devices. @return: Dictionary containing network version 2 standard configuration. """ cfg = net.generate_fallback_config( blacklist_drivers=BLACKLIST_DRIVERS, config_driver=True ) if cfg is None: return {} return cfg @azure_ds_telemetry_reporter def maybe_remove_ubuntu_network_config_scripts(paths=None): """Remove Azure-specific ubuntu network config for non-primary nics. @param paths: List of networking scripts or directories to remove when present. In certain supported ubuntu images, static udev rules or netplan yaml config is delivered in the base ubuntu image to support dhcp on any additional interfaces which get attached by a customer at some point after initial boot. Since the Azure datasource can now regenerate network configuration as metadata reports these new devices, we no longer want the udev rules or netplan's 90-hotplug-azure.yaml to configure networking on eth1 or greater as it might collide with cloud-init's configuration. Remove the any existing extended network scripts if the datasource is enabled to write network per-boot. """ if not paths: paths = UBUNTU_EXTENDED_NETWORK_SCRIPTS logged = False for path in paths: if os.path.exists(path): if not logged: LOG.info( "Removing Ubuntu extended network scripts because" " cloud-init updates Azure network configuration on the" " following events: %s.", [EventType.BOOT.value, EventType.BOOT_LEGACY.value], ) logged = True if os.path.isdir(path): util.del_dir(path) else: util.del_file(path) # Legacy: Must be present in case we load an old pkl object DataSourceAzureNet = DataSourceAzure # Used to match classes to dependencies datasources = [ (DataSourceAzure, (sources.DEP_FILESYSTEM,)), ] # Return a list of data sources that match this set of dependencies def get_datasource_list(depends): return sources.list_from_depends(depends, datasources) # vi: ts=4 expandtab __pycache__/DataSourceNoCloud.cpython-310.pyc 0000644 00000016700 15027667240 0015010 0 ustar 00 o �Ad�1 � @ s� d dl Z d dlZd dlmZ d dlmZ d dlmZmZ d dlm Z e� e�ZG dd� dej �Zddd �Zdd d�Zddd �Zdd� ZG dd� de�ZeejffeejejffgZdd� ZdS )� N)�dmi)�log)�sources�util)�enic @ s` e Zd ZdZdd� Zdd� Zdd� Zdd � Zed d� �Z dd � Z dd� Zdd� Zedd� �Z dS )�DataSourceNoCloud�NoCloudc C sJ t j�| |||� d | _tj�|jd�tj�|jd�g| _d | _d| _ d S )N�nocloudznocloud-net)�/zfile://) r � DataSource�__init__�seed�os�path�join�seed_dir� seed_dirs�supported_seed_starts��self�sys_cfg�distro�paths� r �E/usr/lib/python3/dist-packages/cloudinit/sources/DataSourceNoCloud.pyr s � zDataSourceNoCloud.__init__c C s t j�| �}d|| j| jf S )Nz%s [seed=%s][dsmode=%s])r r �__str__r �dsmode)r �rootr r r r $ s zDataSourceNoCloud.__str__c C s| t �d�}|�t �d�� t �d|�� �}|�t �d|�� �� |�t �d| �� tt|�t|�@ �}|jdd� |S )Nz TYPE=vfatzTYPE=iso9660zLABEL=%szLABEL_FATBOOT=%sT)�reverse)r �find_devs_with�extend�upper�lower�list�set�sort)r �label�fslist� label_list�devlistr r r �_get_devices( s zDataSourceNoCloud._get_devicesc C s� d| j d�}g }i ddd d�}zi }t�d�}|r*t||�r*|�d� t|d|i�}W n ty; t�t d� Y d S w zi }t|�rO|�d � t|d|i�}W n ty` t�t d� Y d S w ddgd dgd�}| j D ]'}ztj|fi |��}|�|� t �d|� t||�}W n t y� Y qmw | j�d�r�|�d� | jd |d d<