diff options
Diffstat (limited to 'cloudinit/sources/DataSourceConfigDrive.py')
-rw-r--r-- | cloudinit/sources/DataSourceConfigDrive.py | 218 |
1 files changed, 109 insertions, 109 deletions
diff --git a/cloudinit/sources/DataSourceConfigDrive.py b/cloudinit/sources/DataSourceConfigDrive.py index 2db4a76a..ca4bb7cf 100644 --- a/cloudinit/sources/DataSourceConfigDrive.py +++ b/cloudinit/sources/DataSourceConfigDrive.py @@ -14,54 +14,61 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -import cloudinit.DataSource as DataSource - -from cloudinit import seeddir as base_seeddir -from cloudinit import log -import cloudinit.util as util -import os.path -import os import json -import subprocess - -DEFAULT_IID = "iid-dsconfigdrive" +import os +from cloudinit import log as logging +from cloudinit import sources +from cloudinit import util -class DataSourceConfigDrive(DataSource.DataSource): - seed = None - seeddir = base_seeddir + '/config_drive' - cfg = {} - userdata_raw = None - metadata = None - dsmode = "local" +LOG = logging.getLogger(__name__) +DEFAULT_IID = "iid-dsconfigdrive" +DEFAULT_MODE = 'pass' +CFG_DRIVE_FILES = [ + "etc/network/interfaces", + "root/.ssh/authorized_keys", + "meta.js", +] +DEFAULT_METADATA = { + "instance-id": DEFAULT_IID, + "dsmode": DEFAULT_MODE, +} +IF_UP_CMD = ['ifup', '--all'] +CFG_DRIVE_DEV_ENV = 'CLOUD_INIT_CONFIG_DRIVE_DEVICE' + + +class DataSourceConfigDrive(sources.DataSource): + def __init__(self, sys_cfg, distro, paths): + sources.DataSource.__init__(self, sys_cfg, distro, paths) + self.seed = None + self.cfg = {} + self.dsmode = 'local' + self.seed_dir = os.path.join(self.paths.seed_dir, 'config_drive') def __str__(self): - mstr = "DataSourceConfigDrive[%s]" % self.dsmode - mstr = mstr + " [seed=%s]" % self.seed - return(mstr) + mstr = "%s[%s]" % (util.obj_name(self), self.dsmode) + mstr = mstr + " [seed=%s]" % (self.seed) + return mstr def get_data(self): found = None md = {} ud = "" - defaults = {"instance-id": DEFAULT_IID, "dsmode": "pass"} - - if os.path.isdir(self.seeddir): + if os.path.isdir(self.seed_dir): try: - (md, ud) = read_config_drive_dir(self.seeddir) - found = self.seeddir - except nonConfigDriveDir: - pass - + (md, ud) = read_config_drive_dir(self.seed_dir) + found = self.seed_dir + except NonConfigDriveDir: + LOG.exception("Failed reading config drive from %s", + self.seed_dir) if not found: - dev = cfg_drive_device() + dev = find_cfg_drive_device() if dev: try: - (md, ud) = util.mount_callback_umount(dev, - read_config_drive_dir) + (md, ud) = util.mount_cb(dev, read_config_drive_dir) found = dev - except (nonConfigDriveDir, util.mountFailedError): + except (NonConfigDriveDir, util.MountFailedError): pass if not found: @@ -70,25 +77,24 @@ class DataSourceConfigDrive(DataSource.DataSource): if 'dsconfig' in md: self.cfg = md['dscfg'] - md = util.mergedict(md, defaults) + md = util.mergedict(md, DEFAULT_METADATA) - # update interfaces and ifup only on the local datasource + # Update interfaces and ifup only on the local datasource # this way the DataSourceConfigDriveNet doesn't do it also. if 'network-interfaces' in md and self.dsmode == "local": if md['dsmode'] == "pass": - log.info("updating network interfaces from configdrive") + LOG.info("Updating network interfaces from configdrive") else: - log.debug("updating network interfaces from configdrive") + LOG.debug("Updating network interfaces from configdrive") - util.write_file("/etc/network/interfaces", - md['network-interfaces']) + self.distro.apply_network(md['network-interfaces']) try: - (out, err) = util.subp(['ifup', '--all']) - if len(out) or len(err): - log.warn("ifup --all had stderr: %s" % err) - - except subprocess.CalledProcessError as exc: - log.warn("ifup --all failed: %s" % (exc.output[1])) + (_out, err) = util.subp(IF_UP_CMD) + if len(err): + LOG.warn("Running %s resulted in stderr output: %s", + IF_UP_CMD, err) + except util.ProcessExecutionError: + LOG.exception("Running %s failed", IF_UP_CMD) self.seed = found self.metadata = md @@ -97,99 +103,107 @@ class DataSourceConfigDrive(DataSource.DataSource): if md['dsmode'] == self.dsmode: return True - log.debug("%s: not claiming datasource, dsmode=%s" % - (self, md['dsmode'])) + LOG.debug("%s: not claiming datasource, dsmode=%s", self, md['dsmode']) return False def get_public_ssh_keys(self): if not 'public-keys' in self.metadata: - return([]) - return(self.metadata['public-keys']) + return [] + return list(self.metadata['public-keys']) - # the data sources' config_obj is a cloud-config formated + # The data sources' config_obj is a cloud-config formated # object that came to it from ways other than cloud-config # because cloud-config content would be handled elsewhere def get_config_obj(self): - return(self.cfg) + return self.cfg class DataSourceConfigDriveNet(DataSourceConfigDrive): - dsmode = "net" + def __init__(self, sys_cfg, paths): + DataSourceConfigDrive.__init__(self, sys_cfg, paths) + self.dsmode = 'net' -class nonConfigDriveDir(Exception): +class NonConfigDriveDir(Exception): pass -def cfg_drive_device(): - """ get the config drive device. return a string like '/dev/vdb' +def find_cfg_drive_device(): + """ Get the config drive device. Return a string like '/dev/vdb' or None (if there is no non-root device attached). This does not check the contents, only reports that if there *were* a config_drive attached, it would be this device. - per config_drive documentation, this is - "associated as the last available disk on the instance" + Note: per config_drive documentation, this is + "associated as the last available disk on the instance" """ - if 'CLOUD_INIT_CONFIG_DRIVE_DEVICE' in os.environ: - return(os.environ['CLOUD_INIT_CONFIG_DRIVE_DEVICE']) - - # we are looking for a raw block device (sda, not sda1) with a vfat - # filesystem on it. + # This seems to be for debugging?? + if CFG_DRIVE_DEV_ENV in os.environ: + return os.environ[CFG_DRIVE_DEV_ENV] + # We are looking for a raw block device (sda, not sda1) with a vfat + # filesystem on it.... letters = "abcdefghijklmnopqrstuvwxyz" devs = util.find_devs_with("TYPE=vfat") - # filter out anything not ending in a letter (ignore partitions) + # Filter out anything not ending in a letter (ignore partitions) devs = [f for f in devs if f[-1] in letters] - # sort them in reverse so "last" device is first + # Sort them in reverse so "last" device is first devs.sort(reverse=True) - if len(devs): - return(devs[0]) + if devs: + return devs[0] - return(None) + return None def read_config_drive_dir(source_dir): """ read_config_drive_dir(source_dir): read source_dir, and return a tuple with metadata dict and user-data - string populated. If not a valid dir, raise a nonConfigDriveDir + string populated. If not a valid dir, raise a NonConfigDriveDir """ - md = {} - ud = "" - flist = ("etc/network/interfaces", "root/.ssh/authorized_keys", "meta.js") - found = [f for f in flist if os.path.isfile("%s/%s" % (source_dir, f))] - keydata = "" + # TODO: fix this for other operating systems... + # Ie: this is where https://fedorahosted.org/netcf/ or similar should + # be hooked in... (or could be) + found = {} + for af in CFG_DRIVE_FILES: + fn = os.path.join(source_dir, af) + if os.path.isfile(fn): + found[af] = fn if len(found) == 0: - raise nonConfigDriveDir("%s: %s" % (source_dir, "no files found")) + raise NonConfigDriveDir("%s: %s" % (source_dir, "no files found")) + md = {} + ud = "" + keydata = "" if "etc/network/interfaces" in found: - with open("%s/%s" % (source_dir, "/etc/network/interfaces")) as fp: - md['network-interfaces'] = fp.read() + fn = found["etc/network/interfaces"] + md['network-interfaces'] = util.load_file(fn) if "root/.ssh/authorized_keys" in found: - with open("%s/%s" % (source_dir, "root/.ssh/authorized_keys")) as fp: - keydata = fp.read() + fn = found["root/.ssh/authorized_keys"] + keydata = util.load_file(fn) meta_js = {} - if "meta.js" in found: - content = '' - with open("%s/%s" % (source_dir, "meta.js")) as fp: - content = fp.read() - md['meta_js'] = content + fn = found['meta.js'] + content = util.load_file(fn) try: + # Just check if its really json... meta_js = json.loads(content) - except ValueError: - raise nonConfigDriveDir("%s: %s" % - (source_dir, "invalid json in meta.js")) + if not isinstance(meta_js, (dict)): + raise TypeError("Dict expected for meta.js root node") + except (ValueError, TypeError) as e: + raise NonConfigDriveDir("%s: %s, %s" % + (source_dir, "invalid json in meta.js", e)) + md['meta_js'] = content + # Key data override?? keydata = meta_js.get('public-keys', keydata) - if keydata: lines = keydata.splitlines() md['public-keys'] = [l for l in lines @@ -202,30 +216,16 @@ def read_config_drive_dir(source_dir): if 'user-data' in meta_js: ud = meta_js['user-data'] - return(md, ud) + return (md, ud) + -datasources = ( - (DataSourceConfigDrive, (DataSource.DEP_FILESYSTEM, )), - (DataSourceConfigDriveNet, - (DataSource.DEP_FILESYSTEM, DataSource.DEP_NETWORK)), -) +# Used to match classes to dependencies +datasources = [ + (DataSourceConfigDrive, (sources.DEP_FILESYSTEM, )), + (DataSourceConfigDriveNet, (sources.DEP_FILESYSTEM, sources.DEP_NETWORK)), +] -# return a list of data sources that match this set of dependencies +# Used to match classes to dependencies def get_datasource_list(depends): - return(DataSource.list_from_depends(depends, datasources)) - -if __name__ == "__main__": - def main(): - import sys - import pprint - print cfg_drive_device() - (md, ud) = read_config_drive_dir(sys.argv[1]) - print "=== md ===" - pprint.pprint(md) - print "=== ud ===" - print(ud) - - main() - -# vi: ts=4 expandtab + return sources.list_from_depends(depends, datasources) |