3 \me#8@sdZddlZddlZddlZddlZddlmZmZmZm Z ddl m Z ej e ZdZGdddZejejfZGdd d ejZd d Zd d ZdddZddZddZddZeejffgZddZe dkrddlZej ddZ!e!j"Z#eZ$e%ej&e$dS)a,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 echo 'root:$6$' | 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. N) atomic_helpersourcessubputil) openstackz 9796-932Ec@s eZdZdZdZdZdZdZdS) PlatformszTemplate/Live/MetadatazUNABLE TO BE IDENTIFIED.zTemplate/Provisioning/Metadataz!Template/Provisioning/No-Metadataz OS-Code/LiveN)__name__ __module__ __qualname__TEMPLATE_LIVE_METADATAZTEMPLATE_LIVE_NODATATEMPLATE_PROVISIONING_METADATATEMPLATE_PROVISIONING_NODATAOS_CODErr(/usr/lib/python3.6/DataSourceIBMCloud.pyrls rcsTeZdZdZdZfddZfddZddZd d Zd d Z e d dZ Z S)DataSourceIBMCloudZIBMCloudNcs0tt|j|||d|_d|_d|_d|_dS)N)superr__init__source_network_config network_jsonplatform)selfsys_cfgZdistropaths) __class__rrrs zDataSourceIBMCloud.__init__cs$tt|j}d||j|jf}|S)Nz %s [%s %s])rr__str__rr)rrootZmstr)rrrrszDataSourceIBMCloud.__str__cCst}|dkrdS|d|_|d|_|d|_|jd|_|jd|_|jd}||_|d|_yt j ||_ Wn4t k r}zt jd |d|_ WYdd}~XnXd S) NFrrmetadatauserdata networkdata vendordataz system-uuidz"Invalid content in vendor-data: %sT)read_mdrrrgetZ userdata_rawrZvendordata_pure system_uuidrZconvert_vendordataZvendordata_raw ValueErrorLOGwarning)rresultsZvderrr _get_datas"        zDataSourceIBMCloud._get_datacCsd|j|jfS)z/Return the subplatform metadata source details.z%s (%s))rr)rrrr_get_subplatformsz#DataSourceIBMCloud._get_subplatformcCs|jdkrdS|jtkS)aquickly (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.NF)r$_read_system_uuid)rrrrrcheck_instance_ids z$DataSourceIBMCloud.check_instance_idcCsX|jtjkrdddS|jdkrR|jdk rHtjdtj|jdd|_n tjd|jS)NZdisabled)configversionz(network config provided via network_json)Z known_macsz#no network configuration available.) rrrrrr&debugrZconvert_net_json)rrrrnetwork_configs      z!DataSourceIBMCloud.network_config) rr r Zdsnamer$rrr*r+r-propertyr2 __classcell__rr)rrrzs   rcCs&d}tjj|sdStj|jjS)Nz/sys/hypervisor/uuid)ospathisfiler load_filestriplower)Z uuid_pathrrrr,s r,cCs tjjdS)Nz /proc/xen)r5r6existsrrrr_is_xensr<#/root/provisioningConfiguration.cfg/root/swinstall.log/proc/1/environcCstjj|rd|}d}tjj|rxtjj|rbtj|jtj|jk}|d||rVdndf7}q|d||f7}d}q|d|7}ndd |}}tjd |||S) z@Return boolean indicating if this boot is ibm provisioning boot.zconfig '%s' exists.Tz log '%s' from %s boot.ZcurrentZpreviousz. log '%s' existed, but no reference file '%s'.Fz log '%s' did not exist.zconfig '%s' did not exist.zibm_provisioning=%s: %s)r5r6r;statst_mtimer&r1)Zprov_cfgZinst_logZboot_refmsgresultrrr_is_ibm_provisionings"    rDc CsZd}d}d }ts|Si}y tj}Wn.tjk rT}ztjd|d Sd}~XnXxt|jD]}||}|j ddj }|j ddj } |||fkrqd||krtjd||||qd||kr| t krtj d ||| |qd|||<qdW|j |ij d } |j |ij d } | r t j| fS| rDtr8t j| fSt j| fSntrVt jdfS|S) zReturn 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.ZMETADATAzCONFIG-2NzFailed to run blkid: %sZLABELZUUIDz.Duplicate fslabel '%s'. existing=%s current=%sz/Skipping %s with LABEL=%s due to uuid != %s: %sZDEVNAME)NN)NN)r<rZblkidrZProcessExecutionErrorr&r'sortedkeysr#upperIBM_CONFIG_UUIDr1rrrDr r r ) Z label_mdataZ label_cfg2Z not_foundZfslabelsZdevsr)ZdevdataZlabeluuidZ metadata_pathZ cfg2_pathrrrget_ibm_platformsX        rLcCst\}}|dkr tjddS|tkr8tjd|dS||td}y&tjj|r^t|}n t j |t}Wn8t j k r}zt d|||f|WYdd}~XnX|j||S)aRead 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.Nz!This is not an IBMCloud platform.z/Cloud-init is disabled during provisioning: %s.)rrz system-uuidz8Failed reading IBM config disk (platform=%s path=%s): %s)rLr&r1 PROVISIONINGr,r5r6isdirmetadata_from_dirrZmount_cbrBrokenMetadata RuntimeErrorupdate)rr6retr(r)rrrr"&s*        r"c Csdd}dd}d|d|fd|dd fd |d |fd |d |fg}i}x|D]\}}}tjj||}d } ytj|dd} Wn0tk r} ztjd|| WYd d } ~ XnX| d ks|d kr| } nDy || } Wn6tk r} zt j d|| fWYd d } ~ XnX| ||<qNW|j dd kr2t j d|i|d<|d} |d} d| kryt j | d| d<Wn6ttfk r} zt j d| WYd d } ~ XnXd}x(|D] \}}|| kr| || |<qW|S) aWalk 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. cSstjjdd|S)NrZlatest)r5r6join)ZfnamerrropathYsz metadata_from_dir..opathcSstj|jdS)Nzutf-8)jsonloadsdecode)Zblobrrrload_json_bytes\sz*metadata_from_dir..load_json_bytesZ metadata_rawzmeta_data.jsonrZ user_dataNr!zvendor_data.jsonr znetwork_data.jsonF)rXzFailed reading path '%s': %szFailed decoding %s: %sz)%s missing required file 'meta_data.json'rZ random_seedz.Badly formatted metadata random_seed entry: %s public_keys public-keyshostnamelocal-hostnamerK instance-idrZr[r\r]rKr^)r_r`ra)r5r6rTrr8IOErrorr&r1 ExceptionrrPr#base64Z b64decoder% TypeError)Z source_dirrUrYfilesr(namer6ZtranslZfpathrawr)rJZmd_rawZmdrenamesZmdnameZnewnamerrrrOJsR          rOcCs tj|tS)N)rZlist_from_depends datasources)Zdependsrrrget_datasource_listsrk__main__zQuery IBM Cloud Metadata) description)r=r>r?)'__doc__rdrVZloggingr5Z cloudinitrrrrZcloudinit.sources.helpersrZ getLoggerrr&rIrr r rMZ DataSourcerr,r<rDrLr"rOZDEP_FILESYSTEMrjrkargparseArgumentParserparser parse_argsargsrJprintZ json_dumpsrrrr^s8   E <$Q