o
    f,                     @   s   d dl Z d dlZd dlZd dlmZ d dlmZmZmZ d dl	m
Z
 d dlmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ e eZG d
d dZG dd dejZdd Zdd Zdd ZeejejffgZ dd Z!dS )    N)suppress)gaierrorgetaddrinfo	inet_ntoa)pack)sourcessubp)
url_helper)util)dhcp)ec2c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	CloudStackPasswordServerClienta  
    Implements password fetching from the CloudStack password server.

    http://cloudstack-administration.readthedocs.org/
       en/latest/templates.html#adding-password-management-to-your-templates
    has documentation about the system.  This implementation is following that
    found at
    https://github.com/shankerbalan/cloudstack-scripts/
       blob/master/cloud-set-guest-password-debian
    c                 C   s
   || _ d S N)virtual_router_address)selfr    r   H/usr/lib/python3/dist-packages/cloudinit/sources/DataSourceCloudStack.py__init__+      
z'CloudStackPasswordServerClient.__init__c                 C   s:   t  ddddddddd	d
|d| jg\}}| S )Nwgetz--quietz--tries3z	--timeout20z--output-document-z--headerzDomU_Request: {0}z{0}:8080)r   formatr   strip)r   domu_requestoutput_r   r   r   _do_request.   s   
z*CloudStackPasswordServerClient._do_requestc                 C   s4   |  d}|dv rd S |dkrtd|  d |S )Nsend_my_password) saved_passwordbad_requestz-Error when attempting to fetch root password.r!   )r   RuntimeError)r   passwordr   r   r   get_passwordC   s   

z+CloudStackPasswordServerClient.get_passwordN)__name__
__module____qualname____doc__r   r   r%   r   r   r   r   r      s
    r   c                       sl   e Zd ZdZdZdZdd Zdd Z			d fd	d
	Zdd Z	dd Z
dd Zdd Zedd Z  ZS )DataSourceCloudStack
CloudStackx   2   c                 C   sd   t j| ||| tj|jd| _d| _|| _t	| j| _
| j
s%tdd| j
 d| _i | _d S )NcslatestzNo virtual router found!zhttp:///)r   
DataSourcer   ospathjoinseed_dirapi_verdistroget_vr_addressvr_addrr#   metadata_addresscfg)r   sys_cfgr7   pathsr   r   r   r   U   s   
zDataSourceCloudStack.__init__c                 C   s   t d td}|r|S t d ttj t | jd}|r-|W  d   S W d   n1 s7w   Y  t d| jj	j
 tt | jj	| jj}|dpYd}|W  d   S 1 sfw   Y  t d dS )z
        Try obtaining a "domain-name" DHCP lease parameter:
        - From systemd-networkd lease
        - From dhclient lease
        z.Try obtaining domain name from networkd leases
DOMAINNAMEzHCould not obtain FQDN from networkd leases. Falling back to ISC dhclientzdomain-nameNzBCould not obtain FQDN from ISC dhclient leases. Falling back to %szNo dhcp leases found)LOGdebugr   networkd_get_option_from_leasesr   NoDHCPLeaseMissingDhclientErrorIscDhclientget_key_from_latest_leaser7   dhcp_clientclient_nameFileNotFoundErrorget_newest_leasefallback_interfaceget)r   
domainnamedomain_namelatest_leaser   r   r   _get_domainnamec   s:   


 
z$DataSourceCloudStack._get_domainnameFc                    sn   t  |||}|r5d|jvr5td |  }|r/|j d| }td| t||jS td| |S )z
        Returns instance's hostname / fqdn
        First probes the parent class method.

        If fqdn is requested, and the parent method didn't return it,
        then attach the domain-name from DHCP response.
        .zFQDN requestedzObtained the following FQDN: %szNCould not determine domain name for FQDN. Fall back to hostname as an FQDN: %s)	superget_hostnamehostnamer?   r@   rN   r   DataSourceHostname
is_default)r   fqdn
resolve_ipmetadata_onlyrR   rK   	__class__r   r   rQ      s   
z!DataSourceCloudStack.get_hostnamec                 C   s   |   }|jdkrdS t| jdg}t }tj||j|jt	j
d\}}|r1t	d| t|S t	d|tt |  t|S )Nr   Fzlatest/meta-data/instance-id)urlsmax_waittimeout	status_cbzUsing metadata source: '%s'z>Giving up on waiting for the metadata from %s after %s seconds)get_url_paramsmax_wait_secondsuhelpcombine_urlr:   time	monotonicwait_for_urltimeout_secondsr?   warningr@   criticalintbool)r   
url_paramsrZ   
start_timeurl	_responser   r   r   wait_for_metadata_service   s.   

	z.DataSourceCloudStack.wait_for_metadata_servicec                 C   s   | j S r   )r;   r   r   r   r   get_config_obj   s   z#DataSourceCloudStack.get_config_objc                 C   s  i }t j|| jd dr|d | _|d | _td| j dS zV|  s'W dS t	 }t
| j| j| _t
| j| j| _tdtt	 |  t| j}z| }W n tyg   t td	| j Y W dS w |rsd|d
did| _W dS  ty   t td| j Y dS w )Nr0   )basez	user-dataz	meta-dataz%Using seeded cloudstack data from: %sTFz)Crawl of metadata service took %s secondsz/Failed to fetch password from virtual router %sexpire)
ssh_pwauthr$   chpasswdz(Failed fetching from metadata service %s)r
   read_optional_seedr5   userdata_rawmetadatar?   r@   rn   rb   rc   r   get_instance_userdatar6   r:   get_instance_metadatarh   r   r9   r%   	Exceptionlogexcr;   )r   seed_retrk   password_clientset_passwordr   r   r   	_get_data   s\   


zDataSourceCloudStack._get_datac                 C   
   | j d S )Nzinstance-idrw   ro   r   r   r   get_instance_id   r   z$DataSourceCloudStack.get_instance_idc                 C   r   )Nzavailability-zoner   ro   r   r   r   availability_zone   s   
z&DataSourceCloudStack.availability_zone)FFF)r&   r'   r(   dsnameurl_max_waiturl_timeoutr   rN   rQ   rn   rp   r   r   propertyr   __classcell__r   r   rX   r   r*   M   s     ,0r*   c                  C   s>   zt dd} W n ty   td Y d S w | d d d S )Nzdata-serverP   zDNS Entry data-server not foundr      )r   r   r?   r@   )addrinfor   r   r   get_data_server  s   
r   c                  C   s^   t d } | D ]#}|d}|d dkr,ttdt|d d}td| |  S q	d S )	Nz/proc/net/route	   00000000z<L      z"Found default route, gateway is %s)	r
   load_text_file
splitlinessplitr   r   rh   r?   r@   )lineslineitemsgwr   r   r   get_default_gateway  s   
r   c                 C   s   t  }|rtd| |S td}|rtd| |S ttj! t | d}|r;td| |W  d    S W d    n1 sEw   Y  tt	" | j
| }|ritd|| j
j |W  d    S W d    n1 ssw   Y  td t S )Nz4Found metadata server '%s' via data-server DNS entrySERVER_ADDRESSz-Found SERVER_ADDRESS '%s' via networkd_leaseszdhcp-server-identifierz&Found SERVER_ADDRESS '%s' via dhclientz1Found SERVER_ADDRESS '%s' via ephemeral %s lease z$No DHCP found, using default gateway)r   r?   r@   r   rA   r   rB   rC   rD   rG   rE   rH   rF   r   )r7   latest_addressrM   r   r   r   r8     sJ   


r8   c                 C   s   t | tS r   )r   list_from_dependsdatasources)dependsr   r   r   get_datasource_listR  s   r   )"loggingr2   rb   
contextlibr   socketr   r   r   structr   	cloudinitr   r   r	   r`   r
   cloudinit.netr   cloudinit.sources.helpersr   	getLoggerr&   r?   r   r1   r*   r   r   r8   DEP_FILESYSTEMDEP_NETWORKr   r   r   r   r   r   <module>   s*   
. 72