
"T`3                 @   s  d  Z  d d l Z d d l m Z d d l m Z d d l m Z d d l m	 Z
 d d l m Z m Z m Z d d l m Z m Z m Z m Z d d	 l m Z m Z e
 j e  Z d
 d i Z d Z d Z e d Z d Z e d d  Z d d   Z Gd d   d e j   Z! d d   Z" d d   Z# d d   Z$ d d e% d d d   Z& e! e j' f f g Z( d  d!   Z) e d" k rd d l* Z* d# Z+ e* j, d$ e+  Z- e- j.   e/ e j0 d e&   d e#   i   d S)%a3  Datasource for Oracle (OCI/Oracle Cloud Infrastructure)

Notes:
 * This datasource does not support OCI Classic. OCI Classic provides an EC2
   lookalike metadata service.
 * The UUID provided in DMI data is not the same as the meta-data provided
   instance-id, but has an equivalent lifespan.
 * We do need to support upgrade from an instance that cloud-init
   identified as OpenStack.
 * Bare metal instances use iSCSI root, virtual machine instances do not.
 * Both bare metal and virtual machine instances provide a chassis-asset-tag of
   OracleCloud.com.
    N)
namedtuple)suppress)dmi)log)netsourcesutil)cmdlinedhcpget_interfaces_by_macis_netfail_master)UrlErrorreadurlconfigure_secondary_nicsFzOracleCloud.comz&http://169.254.169.254/opc/v{version}/z{path}/i(#  OpcMetadataz version instance_data vnics_datac             C   s{  d |  k r d S|  d d k r8 t  j d |  d  d St   } |  d d k r x#d d   |  d D D]Z } | d	 d
 k ri d | k ri | d } | j |  } | s qi qi t |  ri | d =qi Wn |  d d k rwx |  j d i   j   D] \ } } d | k r | j d i   j d  } | r | j |  } | sGq q t |  r | d d =| d =| | d d <q Wd S)aP  
    Search network config physical interfaces to see if any of them are
    a netfailover master.  If found, we prevent matching by MAC as the other
    failover devices have the same MAC but need to be ignored.

    Note: we rely on cloudinit.net changes which prevent netfailover devices
    from being present in the provided network config.  For more details about
    netfailover devices, refer to cloudinit.net module.

    :param network_config
       A v1 or v2 network config dict with the primary NIC, and possibly
       secondary nic configured.  This dict will be mutated.

    versionN      z+Ignoring unknown network config version: %sc             S   s"   g  |  ] } d  | k r |  q S)type ).0cr   r   D/usr/lib/python3/dist-packages/cloudinit/sources/DataSourceOracle.py
<listcomp>I   s   	 z,_ensure_netfailover_safe.<locals>.<listcomp>configr   physicalmac_address	ethernetsmatch
macaddresszset-namename)r   r   )LOGdebugr   getr   items)network_configZmac_to_nameZcfgZmacZcur_name_Zmacaddrr   r   r   _ensure_netfailover_safe/   s:    		
%r'   c                   s   e  Z d  Z d Z d Z d Z e j j e j j	 e j j
 e j j f Z e j Z   f d d   Z d d   Z d d   Z d	 d
   Z d d   Z e d d    Z d d   Z   S)DataSourceOracleZOracleNc                sY   t  t |   j | | |  d  |  _ t j t j | d |  j g i   t g  |  _	 d  S)NZ
datasource)
superr(   __init___vnics_datar   ZmergemanydictZget_cfg_by_pathdsnameBUILTIN_DS_CONFIGds_cfg)selfsys_cfgargskwargs)	__class__r   r   r*   o   s
    	zDataSourceOracle.__init__c             C   s   t    S)z@Check platform environment to report if this datasource may run.)_is_platform_viable)r/   r   r   r   r4   w   s    z$DataSourceOracle._is_platform_viablec             C   s9  |  j    s d St   |  _ |  j j d t d  } t   } t   s\ t j	 t
 j    } |  t d |  } Wd  QRX| j } |  _ t j d | j  |  _ | j |  _ d | d d | d d	 d
 d | d d | d i |  _ d | k r5| d j d  } | rt j |  |  _ | d j d  |  j d <d S)NFr   fetch_vnics_datar   zavailability-zoneZ	ociAdNamezinstance-ididzlaunch-indexr   zlocal-hostnameZhostnamer    ZdisplayNamemetadata	user_dataZssh_authorized_keyspublic_keysT)r4   _read_system_uuidsystem_uuidr.   r#   r-   noop_is_iscsi_rootr
   ZEphemeralDHCPv4r   Zfind_fallback_nicread_opc_metadatainstance_dataZ_crawled_metadataMETADATA_ROOTformatr   Zmetadata_address
vnics_datar+   r7   base64Z	b64decodeZuserdata_raw)r/   r5   Znetwork_contextZfetched_metadatadatar8   r   r   r   	_get_data{   s8    				



zDataSourceOracle._get_datac             C   s   t  j |  j  S)zquickly check (local only) if self.instance_id is still valid

        On Oracle, the dmi-provided system uuid differs from the instance-id
        but has the same life-span.)r   Zinstance_id_matches_system_uuidr;   )r/   r0   r   r   r   check_instance_id   s    z"DataSourceOracle.check_instance_idc             C   s   t  j |  j j d   S)Nr9   )r   Znormalize_pubkey_datar7   r#   )r/   r   r   r   get_public_ssh_keys   s    z$DataSourceOracle.get_public_ssh_keysc             C   s   |  j  t j k r t j   |  _  |  j  s< |  j j   |  _  |  j j d t	 d  r y |  j
   Wn" t k
 r t j t d  Yn Xt |  j   |  j  S)zNetwork config is read from initramfs provided files

        If none is present, then we fall back to fallback configuration.
        r   z0Failed to parse secondary network configuration!)_network_configr   UNSETr	   read_initramfs_configZdistroZgenerate_fallback_configr.   r#   r-   !_add_network_config_from_opc_imds	Exceptionr   logexcr!   r'   )r/   r   r   r   r%      s    		zDataSourceOracle.network_configc             C   sX  |  j  d k r  t j d  d Sd |  j  d k rD t j d  d St   } x|  j  d d  D] } | d j   } | | k r t j d |  qa | | } |  j d	 d k rd
 d d | d i } |  j d j d | d
 d d | d t d | g i  qa |  j d	 d k ra d | d g d t d d d d d d | i i |  j d | <qa Wd S)av  Generate secondary NIC config from IMDS and merge it.

        The primary NIC configuration should not be modified based on the IMDS
        values, as it should continue to be configured for DHCP.  As such, this
        uses the instance's network config dict which is expected to have the
        primary NIC configuration already present.
        It will mutate the network config to include the secondary VNICs.

        :raises:
            Exceptions are not handled within this function.  Likely
            exceptions are KeyError/IndexError
            (if the IMDS returns valid JSON with unexpected contents).
        Nz-Secondary NIC data is UNSET but should not beZnicIndexr   z\VNIC metadata indicates this is a bare metal machine; skipping secondary VNIC configuration.r   ZmacAddrz)Interface with MAC %s not found; skippingr   r   ZstaticZaddressZ	privateIpr   r    r   r   ZmtuZsubnetsr   Z	addressesZdhcp4FZdhcp6r   r   r   )	r+   r!   Zwarningr   lowerr"   rH   appendMTU)r/   Zinterfaces_by_macZ	vnic_dictr   r    Zsubnetr   r   r   rK      s:    		
z2DataSourceOracle._add_network_config_from_opc_imds)__name__
__module____qualname__r,   r;   Zvendordata_purer   ZNetworkConfigSourcer	   ZdsZ	initramfsZ
system_cfgZnetwork_config_sourcesrI   rH   r*   r4   rE   rF   rG   propertyr%   rK   r   r   )r3   r   r(   a   s   				,"r(   c              C   s)   t  j d  }  |  d  k r d  S|  j   S)Nzsystem-uuid)r   read_dmi_datarN   )Zsys_uuidr   r   r   r:     s    r:   c              C   s   t  j d  }  |  t k S)Nzchassis-asset-tag)r   rU   CHASSIS_ASSET_TAG)Z	asset_tagr   r   r   r4     s    r4   c               C   s   t  t j    S)N)boolr	   rJ   r   r   r   r   r=     s    r=   r5   )r5   c                s   d   t  t t d   f d d    } d } y | | d d } Wn* t k
 ro d } | | d d } Yn Xd } |  r y | | d d	 } Wn" t k
 r t j t d
  Yn Xt | | |  S)aC  Fetch metadata from the /opc/ routes.

    :return:
        A namedtuple containing:
          The metadata version as an integer
          The JSON-decoded value of the instance data endpoint on the IMDS
          The JSON-decoded value of the vnics data endpoint if
            `fetch_vnics_data` is True, else None

    r   )metadata_versionpathreturnc                sR   |  d k r d d i n d  } t  d t j d |  d |  d | d    j j   S)	Nr   ZAuthorizationzBearer OracleZurlr   rY   headersretries)r   METADATA_PATTERNrA   Z	_responseZjson)rX   rY   r[   )r\   r   r   _fetch2  s
    z!read_opc_metadata.<locals>._fetchrY   instancer   NZvnicsz0Failed to fetch secondary network configuration!)intstrdictr   r   rM   r!   r   )r5   r^   rX   r?   rB   r   )r\   r   r>   "  s     !		r>   c             C   s   t  j |  t  S)N)r   Zlist_from_dependsdatasources)Zdependsr   r   r   get_datasource_listS  s    rd   __main__z
        Query Oracle Cloud metadata and emit a JSON object with two keys:
        `read_opc_metadata` and `_is_platform_viable`.  The values of each are
        the return values of the corresponding functions defined in
        DataSourceOracle.py.description)1__doc__rC   collectionsr   
contextlibr   r<   Z	cloudinitr   r   Zloggingr   r   r   Zcloudinit.netr	   r
   r   r   Zcloudinit.url_helperr   r   Z	getLoggerrQ   r!   r-   rV   r@   r]   rP   r   r'   Z
DataSourcer(   r:   r4   r=   rW   r>   ZDEP_FILESYSTEMrc   rd   argparserf   ArgumentParserparser
parse_argsprintZ
json_dumpsr   r   r   r   <module>   s@   "
2,
	