Your IP : 216.73.217.13


Current Path : /lib/python3/dist-packages/cloudinit/sources/helpers/__pycache__/
Upload File :
Current File : //lib/python3/dist-packages/cloudinit/sources/helpers/__pycache__/azure.cpython-38.pyc

U

�Ad(��	@s�ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddlmZddl
mZddlmZmZddlmZmZmZmZmZddlmZddlmZdd	lmZmZmZmZm Z m!Z!m"Z"dd
l#m$Z$ddl%m&Z&e�'e(�Z)dZ*d
Z+dZ,dZ-dZ.dZ/dZ0e$j1dddd�Z2dZ3ed�Z4ede4fede4fd�dd�Z5dd�Z6e5dd ��Z7e5d!d"��Z8dd#�e9e$j:d$�d%d&�Z;d'd(�Z<e5e&d)fd*d+��Z=e5d,d-��Z>ed.d/��Z?d0d1�Z@e5dd2d3d4�e9eAeeBeCeCe jDd5�d6d7��ZEe9e9e9eBd8�d9d:�ZFGd;d<�d<�ZGGd=d>�d>eH�ZIGd?d@�d@�ZJGdAdB�dB�ZKGdCdD�dD�ZLGdEdF�dF�ZMe5dWe9eee9ee9dG�dHdI��ZNe5e9dJ�dKdL��ZOdMdN�ZPGdOdP�dPeH�ZQGdQdR�dReH�ZRGdSdT�dTejS�ZTGdUdV�dV�ZUdS)X�N)�contextmanager)�datetime)�ENOENT)�sleep�time)�Callable�List�Optional�TypeVar�Union)�ElementTree)�escape)�distros�dmi�subp�
temp_utils�
url_helper�util�version)�events)�CFG_BUILTINz
168.63.129.16�boot-telemetryzsystem-infoZ
diagnosticZ
compressedi�z'/run/cloud-init/log_pushed_to_kvp_indexzazure-dsz initialize reporter for azure dsT)�name�descriptionZreporting_enabledz�The VM encountered an error during deployment. Please visit https://aka.ms/linuxprovisioningerror for more information on remediation.�T.)�func�returncs�fdd�}|S)Nc
s6tj�j�jtd���||�W5QR�SQRXdS)N�rr�parent)r�ReportEventStack�__name__�azure_ds_reporter)�args�kwargs�r��A/usr/lib/python3/dist-packages/cloudinit/sources/helpers/azure.py�impl9s�z)azure_ds_telemetry_reporter.<locals>.implr%)rr'r%r$r&�azure_ds_telemetry_reporter8sr(cCs\||krdSd
dd�}|�d�}d�||d�||d�||d�|d|d	g�}||kS)z�
    Azure stores the instance ID with an incorrect byte ordering for the
    first parts. This corrects the byte order such that it is consistent with
    that returned by the metadata service.
    F�cSs(dd�t�|d�D�}|��d�|�S)NcSsg|]}|�qSr%r%)�.0Zbyter%r%r&�
<listcomp>Nsz<is_byte_swapped.<locals>.swap_bytestring.<locals>.<listcomp>r)�)�textwrapZwrap�reverse�join)�s�widthZddr%r%r&�swap_bytestringMsz(is_byte_swapped.<locals>.swap_bytestring�-r���)r))�splitr/)Zprevious_idZ
current_idr2�partsZ
swapped_idr%r%r&�is_byte_swappedDs




��
r9c
Cs8t��std��t�d�ztt��tt���}Wn,t	k
r`}ztd�|�W5d}~XYnXzXt
j
ddddgd	d
�\}}d}|r�d|kr�|�d�d}|s�td
��|t|�d}Wnbt
jk
r�}ztd|�|�W5d}~XYn2t	k
�r}ztd|�|�W5d}~XYnXz`t
j
dddddgd	d
�\}}d}|�r^d|k�r^|�d�d}|�sltd��|t|�d}Wndt
jk
�r�}ztd|�|�W5d}~XYn2t	k
�r�}ztd|�|�W5d}~XYnXt
�tddt�|���dt�|���dt�|���dft
j�}t
�|�|S)z[Report timestamps related to kernel initialization and systemd
    activation of cloud-initz1distro not using systemd, skipping boot telemetryzCollecting boot telemetryz*Failed to determine kernel start timestampNZ	systemctlZshowz-pZUserspaceTimestampMonotonicT)�capture�=r4z8Failed to parse UserspaceTimestampMonotonic from systemdi@Bz-Failed to get UserspaceTimestampMonotonic: %sz<Failed to parse UserspaceTimestampMonotonic from systemd: %szcloud-init-localZInactiveExitTimestampMonotonicz;Failed to parse InactiveExitTimestampMonotonic from systemdz0Failed to get InactiveExitTimestampMonotonic: %sz?Failed to parse InactiveExitTimestampMonotonic from systemd: %srz5kernel_start=%s user_start=%s cloudinit_activation=%s�Z)rZuses_systemd�RuntimeError�LOG�debug�floatrrZuptime�
ValueErrorrr7ZProcessExecutionErrorr�ReportingEvent�BOOT_EVENT_TYPErZutcfromtimestampZ	isoformat�DEFAULT_EVENT_ORIGIN�report_event)Zkernel_start�e�out�_ZtsmZ
user_startZcloudinit_activation�evtr%r%r&�get_boot_telemetry`s�

�
�������

���������
rJc
Csbt��}t�tddt��|d|d|dd|dd|dd|d	ftj�}t�|�|S)
z%Collect and report system informationzsystem informationztcloudinit_version=%s, kernel_version=%s, variant=%s, distro_name=%s, distro_version=%s, flavor=%s, python_version=%s�releaseZvariantZdistrr4r)�python)	rZsystem_inforrB�SYSTEMINFO_EVENT_TYPErZversion_stringrDrE)�inforIr%r%r&�get_system_info�s$


���
rO��logger_func)�msgrcCs6t|�r||�t�td|tj�}tj|dhd�|S)zReport a diagnostic eventzdiagnostic message�log�Zexcluded_handler_types)�callablerrB�DIAGNOSTIC_EVENT_TYPErDrE)rRrQrIr%r%r&�report_diagnostic_event�s�rWcCsPt�t�|��}d|�d�d�}t�t|t�	|�tj
�}tj|dddhd�|S)zReport a compressed eventzgz+b64�ascii)�encoding�datarS�printZwebhookrT)�base64Zencodebytes�zlib�compress�decoderrB�COMPRESSED_EVENT_TYPE�json�dumpsrDrE)Z
event_nameZ
event_contentZcompressed_dataZ
event_datarIr%r%r&�report_compressed_event�s���rcZdef_log_filec
Cs@t�}t�d�z�t|d��t}|�dtj�t|��t	|�}t
d�|��||�tjd�|�|tj�t
d|���t�tt|����W5QRXWn8tk
r�}zt
dt|�tjd�W5d}~XYnXt�d	�z$tjd
gddd
�\}}t
d
|�Wn:tk
�r:}zt
dt|�tjd�W5d}~XYnXdS)azPush a portion of cloud-init.log file or the whole file to KVP
    based on the file size.
    The first time this function is called after VM boot, It will push the last
    n bytes of the log file such that n < MAX_LOG_TO_KVP_LENGTH
    If called again on the same boot, it continues from where it left off.
    In addition to cloud-init.log, dmesg log will also be collected.z"Dumping cloud-init.log file to KVP�rbrzMDumping last {0} bytes of cloud-init.log file to KVP starting from index: {1}rPzcloud-init.logz#Exception when dumping log file: %sNzDumping dmesg log to KVPZdmesgFT)r_r:z$Exception when dumping dmesg log: %s)�%get_last_log_byte_pushed_to_kvp_indexr>r?�open�seek�os�SEEK_END�max�tell�MAX_LOG_TO_KVP_LENGTHrW�format�SEEK_SETrc�readrZ
write_file�LOG_PUSHED_TO_KVP_INDEX_FILE�str�	Exception�repr�warningr)�	file_nameZstart_index�fZ
seek_index�exrGrHr%r%r&�push_log_to_kvp�s<	

��"
�

�rxc
Cs�z0ttd��}t|���W5QR�WSQRXWn�tk
rr}z$|jtkrbtdt|�t	j
d�W5d}~XYnntk
r�}ztdt|�t	j
d�W5d}~XYn8tk
r�}ztdt|�t	j
d�W5d}~XYnXdS)N�rz0Reading LOG_PUSHED_TO_KVP_INDEX_FILE failed: %s.rPz2Invalid value in LOG_PUSHED_TO_KVP_INDEX_FILE: %s.z2Failed to get the last log byte pushed to KVP: %s.r)
rfrp�intro�IOError�errnorrWrsr>rtrArr)rvrFr%r%r&res($

�
�
�rec	cs6t��}t�tj�|��z
dVW5t�|�XdS�N)rh�getcwd�chdir�path�
expanduser)ZnewdirZprevdirr%r%r&�cd7s

r�cCsx|�dd�}t|�dkrdd}|�d�D] }t|�dkr>d|}||7}q&t�dt|�dd�d��}n
|�d	�}t�|�S)
N�\r,r6�:r4�0z>L��utf-8)	�replace�lenr7�structZpackrz�encode�socketZ	inet_ntoa)Zfallback_lease_valueZunescaped_valueZ
hex_stringZhex_pairZpacked_bytesr%r%r&�get_ip_from_lease_valueAs

r���)rZ�retry_sleep�timeout_minutes)�url�headersrZr�r�rc	
Cs�|dt�}d}d}|s�|d7}ztj|||dd�}Wq�Wn`tjk
r�}z@td||||j|jftjd�t�||ks�d	t	|�kr��W5d}~XYnXt
|�qtd
||ftjd�|S)z�Readurl wrapper for querying wireserver.

    :param retry_sleep: Time to sleep before retrying.
    :param timeout_minutes: Retry up to specified number of minutes.
    :raises UrlError: on error fetching data.
    �<rNr4)r�r�)r�rZ�timeoutzdFailed HTTP request with Azure endpoint %s during attempt %d with exception: %s (code=%r headers=%r)rPzNetwork is unreachablez@Successful HTTP request with Azure endpoint %s after %d attempts)rrZreadurlZUrlErrorrW�coder�r>r?rqr)	r�r�rZr�r�r�Zattempt�responserFr%r%r&�http_with_retriesOsB���
�
�
��r�)�username�hostname�
disableSshPwdrcCs$t�d�}|j|||d�}|�d�S)Na.        <ns0:Environment xmlns:ns0="http://schemas.dmtf.org/ovf/environment/1"
         xmlns:ns1="http://schemas.microsoft.com/windowsazure"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          <ns1:ProvisioningSection>
            <ns1:Version>1.0</ns1:Version>
            <ns1:LinuxProvisioningConfigurationSet>
              <ns1:ConfigurationSetType>LinuxProvisioningConfiguration
              </ns1:ConfigurationSetType>
              <ns1:UserName>{username}</ns1:UserName>
              <ns1:DisableSshPasswordAuthentication>{disableSshPwd}
              </ns1:DisableSshPasswordAuthentication>
              <ns1:HostName>{hostname}</ns1:HostName>
            </ns1:LinuxProvisioningConfigurationSet>
          </ns1:ProvisioningSection>
          <ns1:PlatformSettingsSection>
            <ns1:Version>1.0</ns1:Version>
            <ns1:PlatformSettings>
              <ns1:ProvisionGuestAgent>true</ns1:ProvisionGuestAgent>
            </ns1:PlatformSettings>
          </ns1:PlatformSettingsSection>
        </ns0:Environment>
        )r�r�r�r�)r-�dedentrmr�)r�r�r�ZOVF_ENV_TEMPLATEZretr%r%r&�build_minimal_ovf�s��r�c@sHeZdZddd�Zdd�Zdejd�dd	�Zdee	ejd�dd
�Z
d
S)�AzureEndpointHttpClientZWALinuxAgentz
2012-11-30)zx-ms-agent-namezx-ms-versioncCsd|d�|_dS)NZDES_EDE3_CBC)zx-ms-cipher-namez!x-ms-guest-agent-public-x509-cert)�extra_secure_headers)�self�certificater%r%r&�__init__�s�z AzureEndpointHttpClient.__init__F�rcCs,|j}|r |j��}|�|j�t||d�S)N)r�)r��copy�updater�r�)r�r��securer�r%r%r&�get�s

zAzureEndpointHttpClient.getN)rZrcCs0|j}|dk	r"|j��}|�|�t|||d�S)N)rZr�)r�r�r�r�)r�r�rZ�
extra_headersr�r%r%r&�post�s


zAzureEndpointHttpClient.post)F)NN)r �
__module__�__qualname__r�r�r�UrlResponser�r	�bytesr�r%r%r%r&r��s���r�c@seZdZdZdS)�InvalidGoalStateXMLExceptionz9Raised when GoalState XML is invalid or has missing data.N)r r�r��__doc__r%r%r%r&r��sr�c@s2eZdZdeeefeedd�dd�Zdd�Z	dS)	�	GoalStateTN)�unparsed_xml�azure_endpoint_client�need_certificaterc
Cs||_zt�|�|_Wn8tjk
rN}ztd|tjd��W5d}~XYnX|�d�|_	|�d�|_
|�d�|_dD]0}t||�dkrxd|}t|tjd�t
|��qxd|_|�d	�}|dk	�r|�rtjd
dtd��.|jj|d
d�j|_|jdk�rt
d��W5QRXdS)ahParses a GoalState XML string and returns a GoalState object.

        @param unparsed_xml: string representing a GoalState XML.
        @param azure_endpoint_client: instance of AzureEndpointHttpClient.
        @param need_certificate: switch to know if certificates is needed.
        @return: GoalState object representing the GoalState XML string.
        z!Failed to parse GoalState XML: %srPNz./Container/ContainerIdz4./Container/RoleInstanceList/RoleInstance/InstanceIdz
./Incarnation)�container_id�instance_id�incarnationzMissing %s in GoalState XMLzD./Container/RoleInstanceList/RoleInstance/Configuration/Certificateszget-certificates-xmlzget certificates xmlrT)r�z/Azure endpoint returned empty certificates xml.)r�r�
fromstring�root�
ParseErrorrWr>rt�_text_from_xpathr�r�r��getattrr��certificates_xmlrrr!r��contents)r�r�r�r�rF�attrrRr�r%r%r&r��sJ
��
���
�zGoalState.__init__cCs|j�|�}|dk	r|jSdSr})r��find�text)r�Zxpath�elementr%r%r&r�szGoalState._text_from_xpath)T)
r r�r�rrqr�r��boolr�r�r%r%r%r&r��s�
�7r�c@s�eZdZddd�Zdd�Zdd�Zedd	��Zejd
d	��Ze	dd��Z
ee	d
d���Ze	dd��Z
e	dd��Ze	dd��Ze	dd��ZdS)�OpenSSLManagerzTransportPrivate.pemzTransportCert.pem)�private_keyr�cCst��|_d|_|��dSr})rZmkdtemp�tmpdir�_certificate�generate_certificate�r�r%r%r&r�s
zOpenSSLManager.__init__cCst�|j�dSr})rZdel_dirr�r�r%r%r&�clean_upszOpenSSLManager.clean_upcCs|jSr}�r�r�r%r%r&r�szOpenSSLManager.certificatecCs
||_dSr}r�)r��valuer%r%r&r�scCs�t�d�|jdk	r"t�d�dSt|j��jt�ddddddd	d
ddd
|jdd|jdg�d}t|jd�D]}d|krr||��7}qr||_W5QRXt�d�dS)Nz7Generating certificate for communication with fabric...zCertificate already generated.�opensslZreqz-x509z-nodesz-subjz/CN=LinuxTransportz-daysZ32768z-newkeyzrsa:2048z-keyoutr�z-outr�r,ZCERTIFICATEzNew certificate generated.)	r>r?r�r�r�r�certificate_namesrf�rstrip)r�r��liner%r%r&r� s8


��z#OpenSSLManager.generate_certificatecCs"ddd|g}tj||d�\}}|S)Nr�Zx509z-noout�rZ)r)�actionZcert�cmd�resultrHr%r%r&�_run_x509_action@szOpenSSLManager._run_x509_actioncCs2|�d|�}ddddddg}tj||d�\}}|S)	Nz-pubkeyz
ssh-keygenz-iz-mZPKCS8z-fz
/dev/stdinr�)r�r)r�r�Zpub_keyZ
keygen_cmd�ssh_keyrHr%r%r&�_get_ssh_key_from_certGsz%OpenSSLManager._get_ssh_key_from_certcCs6|�d|�}|�d�}||dd��d�}d�|�S)aopenssl x509 formats fingerprints as so:
        'SHA1 Fingerprint=07:3E:19:D1:4D:1C:79:92:24:C6:A0:FD:8D:DA:        B6:A8:BF:27:D4:73
'

        Azure control plane passes that fingerprint as so:
        '073E19D14D1C799224C6A0FD8DDAB6A8BF27D473'
        z-fingerprintr;r4���r�r,)r�r�r7r/)r�r�Zraw_fp�eqZoctetsr%r%r&�_get_fingerprint_from_certNs	
z)OpenSSLManager._get_fingerprint_from_certc	Csjt�|��d�}|j}ddddd|�d�g}t|j��*tjdjf|j	�d	d
�
|�d�\}}W5QRX|S)z�Decrypt the certificates XML document using the our private key;
        return the list of certs and private keys contained in the doc.
        z.//DatasMIME-Version: 1.0s<Content-Disposition: attachment; filename="Certificates.p7m"s?Content-Type: application/x-pkcs7-mime; name="Certificates.p7m"s!Content-Transfer-Encoding: base64�r�zuopenssl cms -decrypt -in /dev/stdin -inkey {private_key} -recip {certificate} | openssl pkcs12 -nodes -password pass:T�
)�shellrZ)rr�r�r�r�r�r�rrmr�r/)r�r��tagZcertificates_content�linesrGrHr%r%r&�_decrypt_certs_from_xml\s$���z&OpenSSLManager._decrypt_certs_from_xmlc	Csv|�|�}g}i}|��D]V}|�|�t�d|�r:g}qt�d|�rd�|�}|�|�}|�|�}|||<g}q|S)z�Given the Certificates XML document, return a dictionary of
        fingerprints and associated SSH keys derived from the certs.z[-]+END .*?KEY[-]+$z[-]+END .*?CERTIFICATE[-]+$�
)r��
splitlines�append�re�matchr/r�r�)	r�r�rGZcurrent�keysr�r�r��fingerprintr%r%r&�parse_certificatesus




z!OpenSSLManager.parse_certificatesN)r r�r�r�r�r��propertyr��setterr(r��staticmethodr�r�r�r�r�r%r%r%r&r�	s,�






r�c@s�eZdZe�d�Ze�d�ZdZdZdZ	dZ
eee
dd�d	d
�Zedd�dd
��Zee
dd�dd��Zde
e
e
e
ed�dd�Zeedd�dd��ZdS)�GoalStateHealthReportera�        <?xml version="1.0" encoding="utf-8"?>
        <Health xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <GoalStateIncarnation>{incarnation}</GoalStateIncarnation>
          <Container>
            <ContainerId>{container_id}</ContainerId>
            <RoleInstanceList>
              <Role>
                <InstanceId>{instance_id}</InstanceId>
                <Health>
                  <State>{health_status}</State>
                  {health_detail_subsection}
                </Health>
              </Role>
            </RoleInstanceList>
          </Container>
        </Health>
        z�        <Details>
          <SubStatus>{health_substatus}</SubStatus>
          <Description>{health_description}</Description>
        </Details>
        ZReadyZNotReadyZProvisioningFailediN)�
goal_stater��endpointrcCs||_||_||_dS)a?Creates instance that will report provisioning status to an endpoint

        @param goal_state: An instance of class GoalState that contains
            goal state info such as incarnation, container id, and instance id.
            These 3 values are needed when reporting the provisioning status
            to Azure
        @param azure_endpoint_client: Instance of class AzureEndpointHttpClient
        @param endpoint: Endpoint (string) where the provisioning status report
            will be sent to
        @return: Instance of class GoalStateHealthReporter
        N)�_goal_state�_azure_endpoint_client�	_endpoint)r�r�r�r�r%r%r&r��sz GoalStateHealthReporter.__init__r�c
Cs�|j|jj|jj|jj|jd�}t�d�z|j|d�Wn6t	k
rp}zt
d|tjd��W5d}~XYnXt�d�dS)N)r�r�r��statusz Reporting ready to Azure fabric.��documentz#exception while reporting ready: %srPzReported ready to Azure fabric.)
�build_reportr�r�r�r��PROVISIONING_SUCCESS_STATUSr>r?�_post_health_reportrrrW�errorrN)r�r�rFr%r%r&�send_ready_signal�s �
�z)GoalStateHealthReporter.send_ready_signal�rrc
Cs�|j|jj|jj|jj|j|j|d�}z|j|d�Wn:tk
rp}zd|}t	|t
jd��W5d}~XYnXt
�d�dS)N)r�r�r�r��	substatusrr�z%exception while reporting failure: %srPz!Reported failure to Azure fabric.)
r�r�r�r�r��PROVISIONING_NOT_READY_STATUS�PROVISIONING_FAILURE_SUBSTATUSr�rrrWr>r�rt)r�rr�rFrRr%r%r&�send_failure_signal�s�z+GoalStateHealthReporter.send_failure_signal)r�r�r�r�rc	Csbd}|dk	r.|jjt|�t|d|j��d�}|jjtt|��t|�t|�t|�|d�}|�d�S)Nr,)Zhealth_substatusZhealth_description)r�r�r�Z
health_statusZhealth_detail_subsectionr�)�%HEALTH_DETAIL_SUBSECTION_XML_TEMPLATErmr
�"HEALTH_REPORT_DESCRIPTION_TRIM_LEN�HEALTH_REPORT_XML_TEMPLATErqr�)	r�r�r�r�r�r�rZ
health_detailZ
health_reportr%r%r&r��s 	��
�z$GoalStateHealthReporter.build_report)r�rcCsHt�td�t�d�d�|j�}|jj||ddid�t�d�dS)Nrz&Sending health report to Azure fabric.zhttp://{}/machine?comp=healthzContent-Typeztext/xml; charset=utf-8)rZr�z/Successfully sent health report to Azure fabric)rxrr>r?rmr�r�r�)r�r�r�r%r%r&r�	s
�z+GoalStateHealthReporter._post_health_report)NN)r r�r�r-r�rr�r�r�r�r�r�r�rqr�r(r�r�r�r�r�r%r%r%r&r��s<��	���r�c@s�eZdZed�dd�Zdd�Zedd�dd	��Zedee	ed�d
d��Z
eedd�d
d��Zeee
d�dd��Zeed�dd��Zeeeefee
d�dd��Zee
eed�dd��Zeeeed�dd��ZdS)�WALinuxAgentShim�r�cCs||_d|_d|_dSr})r��openssl_managerr�)r�r�r%r%r&r�,szWALinuxAgentShim.__init__cCs|jdk	r|j��dSr})rr�r�r%r%r&r�1s
zWALinuxAgentShim.clean_upNr�c
CsVzt�d�t�d|g�Wn4tk
rP}ztd|tjd�W5d}~XYnXdS)NzEjecting the provisioning isoZejectz(Failed ejecting the provisioning iso: %srP)r>r?rrrrW)r��iso_devrFr%r%r&�	eject_iso5s
�zWALinuxAgentShim.eject_isocCs�d}|jdkr&|dk	r&t�|_|jj}|jdkr:t|�|_|j|dk	d�}d}|dk	rb|�||�}t||j|j�}|dk	r�|�	|�|�
�|S)a�Gets the VM's GoalState from Azure, uses the GoalState information
        to report ready/send the ready signal/provisioning complete signal to
        Azure, and then uses pubkey_info to filter and obtain the user's
        pubkeys from the GoalState.

        @param pubkey_info: List of pubkey values and fingerprints which are
            used to filter and obtain the user's pubkey values from the
            GoalState.
        @return: The list of user's authorized pubkey values.
        N�r�)rr�r�r�r��_fetch_goal_state_from_azure�_get_user_pubkeysr�r�rr�)r��pubkey_inforZhttp_client_certificater��ssh_keys�health_reporterr%r%r&�"register_with_azure_and_fetch_data@s.
���
z3WALinuxAgentShim.register_with_azure_and_fetch_datar�cCs@|jdkrtd�|_|jdd�}t||j|j�}|j|d�dS)z�Gets the VM's GoalState from Azure, uses the GoalState information
        to report failure/send provisioning failure signal to Azure.

        @param: user visible error description of provisioning failure.
        NFr�r)r�r�rr�r�r�)r�rr�rr%r%r&�&register_with_azure_and_report_failurefs

�z7WALinuxAgentShim.register_with_azure_and_report_failure)r�rcCs|��}|�||�S)aFetches the GoalState XML from the Azure endpoint, parses the XML,
        and returns a GoalState object.

        @param need_certificate: switch to know if certificates is needed.
        @return: GoalState object representing the GoalState XML
        )�"_get_raw_goal_state_xml_from_azure�_parse_raw_goal_state_xml)r�r��unparsed_goal_state_xmlr%r%r&rus

�z-WALinuxAgentShim._fetch_goal_state_from_azurec
Cs�t�d�d�|j�}z,tjddtd��|j�|�}W5QRXWn6t	k
rx}zt
d|tjd��W5d}~XYnXt�d	�|j
S)
z�Fetches the GoalState XML from the Azure endpoint and returns
        the XML as a string.

        @return: GoalState XML string
        zRegistering with Azure...z!http://{}/machine/?comp=goalstatezgoalstate-retrievalzretrieve goalstaterz9failed to register with Azure and fetch GoalState XML: %srPNz#Successfully fetched GoalState XML.)r>rNrmr�rrr!r�r�rrrWrtr?r�)r�r�r�rFr%r%r&r�s&
���
z3WALinuxAgentShim._get_raw_goal_state_xml_from_azure)rr�rc
Cs~zt||j|�}Wn6tk
rH}ztd|tjd��W5d}~XYnXd�d|jd|jd|j	g�}t|tj
d�|S)aParses a GoalState XML string and returns a GoalState object.

        @param unparsed_goal_state_xml: GoalState XML string
        @param need_certificate: switch to know if certificates is needed.
        @return: GoalState object representing the GoalState XML
        z"Error processing GoalState XML: %srPNz, zGoalState XML container id: %szGoalState XML instance id: %szGoalState XML incarnation: %s)r�r�rrrWr>rtr/r�r�r�r?)r�rr�r�rFrRr%r%r&r�s(����z*WALinuxAgentShim._parse_raw_goal_state_xml)r�r	rcCsHg}|jdk	rD|dk	rD|jdk	rDt�d�|j�|j�}|�||�}|S)a�Gets and filters the VM admin user's authorized pubkeys.

        The admin user in this case is the username specified as "admin"
        when deploying VMs on Azure.
        See https://docs.microsoft.com/en-us/cli/azure/vm#az-vm-create.
        cloud-init expects a straightforward array of keys to be dropped
        into the admin user's authorized_keys file. Azure control plane exposes
        multiple public keys to the VM via wireserver. Select just the
        admin user's key(s) and return them, ignoring any other certs.

        @param goal_state: GoalState object. The GoalState object contains
            a certificate XML, which contains both the VM user's authorized
            pubkeys and other non-user pubkeys, which are used for
            MSI and protected extension handling.
        @param pubkey_info: List of VM user pubkey dicts that were previously
            obtained from provisioning data.
            Each pubkey dict in this list can either have the format
            pubkey['value'] or pubkey['fingerprint'].
            Each pubkey['fingerprint'] in the list is used to filter
            and obtain the actual pubkey value from the GoalState
            certificates XML.
            Each pubkey['value'] requires no further processing and is
            immediately added to the return list.
        @return: A list of the VM user's authorized pubkey values.
        Nz/Certificate XML found; parsing out public keys.)r�rr>r?r��_filter_pubkeys)r�r�r	r
�keys_by_fingerprintr%r%r&r�s���
�z"WALinuxAgentShim._get_user_pubkeys)rr	rcCs|g}|D]n}d|kr,|dr,|�|d�qd|krj|drj|d}||kr\|�||�qvt�d|�qt�d|�q|S)a8Filter and return only the user's actual pubkeys.

        @param keys_by_fingerprint: pubkey fingerprint -> pubkey value dict
            that was obtained from GoalState Certificates XML. May contain
            non-user pubkeys.
        @param pubkey_info: List of VM user pubkeys. Pubkey values are added
            to the return list without further processing. Pubkey fingerprints
            are used to filter and obtain the actual pubkey values from
            keys_by_fingerprint.
        @return: A list of the VM user's authorized pubkey values.
        r�r�zIovf-env.xml specified PublicKey fingerprint %s not found in goalstate XMLzFovf-env.xml specified PublicKey with neither value nor fingerprint: %s)r�r>rt)rr	r�Zpubkeyr�r%r%r&r�s"
��z WALinuxAgentShim._filter_pubkeys)NN)r r�r�rqr�r�r(rr	rrrr�r�rr�rrr�listrr��dictrr%r%r%r&r+s<
�
�%�
�!�)r)r�r	rcCs,t|d�}z|j||d�W�S|��XdS)Nr)r	r)rr�r)r�r	r�shimr%r%r&�get_metadata_from_fabrics
�
rrcCs.t|d�}t}z|j|d�W5|��XdS)Nrr
)r�+DEFAULT_REPORT_FAILURE_USER_VISIBLE_MESSAGEr�r)r�rrr%r%r&�report_failure_to_fabrics

rcCs(td|tjd�td|tjd�dS)Nzdhclient output stream: %srPzdhclient error stream: %s)rWr>r?)rG�errr%r%r&�dhcp_log_cb)s��rc@seZdZdS)�BrokenAzureDataSourceN�r r�r�r%r%r%r&r2src@seZdZdS)�NonAzureDataSourceNrr%r%r%r&r6src@s&eZdZdZeedd�dd��ZdS)�ChassisAssetTagz 7783-7084-3265-9085-8269-3286-77r�cCs\t�d�}z||�}Wn(tk
r>td|tjd�YdSXtd||jftjd�|S)z�Check platform environment to report if this datasource may run.

        :returns: ChassisAssetTag if matching tag found, else None.
        zchassis-asset-tagzNon-Azure chassis asset tag: %rrPNz Azure chassis asset tag: %r (%s))rZ
read_dmi_datarArWr>r?r)�clsZ	asset_tagr�r%r%r&�query_system=s
��zChassisAssetTag.query_systemN)r r�r�ZAZURE_CLOUD�classmethodr	r!r%r%r%r&r:src@s�eZdZddd�Zddddddddd�eeeeeeeeeeeee	eeedd�	dd	�Z
ed
�dd�Zeedd
�dd��Z
deeed�dd�Zdeeeed�dd�Zdd�Zdd�Zdd�ZdS)�	OvfEnvXmlz)http://schemas.dmtf.org/ovf/environment/1z)http://schemas.microsoft.com/windowsazure)Zovf�waNF�r��passwordr��custom_data�disable_ssh_password_auth�public_keys�preprovisioned_vm�preprovisioned_vm_type)	r�r&r�r'r(r)r*r+rc	Cs8||_||_||_||_||_|p$g|_||_||_dSr}r%)	r�r�r&r�r'r(r)r*r+r%r%r&r�Zs
zOvfEnvXml.__init__r�cCs|j|jkSr})�__dict__)r��otherr%r%r&�__eq__oszOvfEnvXml.__eq__)�ovf_env_xmlrc
Cszzt�|�}Wn6tjk
rD}zd|}t|�|�W5d}~XYnX|�d|j�s\td��t�}|�|�|�	|�|S)z�Parser for ovf-env.xml data.

        :raises NonAzureDataSource: if XML is not in Azure's format.
        :raises BrokenAzureDataSource: if XML is unparseable or invalid.
        zInvalid ovf-env.xml: %sNz./wa:ProvisioningSectionz=Ignoring non-Azure ovf-env.xml: ProvisioningSection not found)
rr�r�rr��
NAMESPACESrr#�&_parse_linux_configuration_set_section� _parse_platform_settings_section)r r/r�rFZ	error_str�instancer%r%r&�
parse_textrs�

zOvfEnvXml.parse_textr$)r�required�	namespacecCsl|�d||ftj�}t|�dkrDd|}t�|�|r@t|��dSt|�dkrdtd|t|�f��|dS)Nz./%s:%sr�#No ovf-env.xml configuration for %rr4�:Multiple configuration matches in ovf-exml.xml for %r (%d))�findallr#r0r�r>r?r)r��noderr5r6�matchesrRr%r%r&�_find�s"
�

��zOvfEnvXml._find)rr5�
decode_base64�
parse_boolc
Cs�|�d|tj�}t|�dkr@d|}t�|�|r<t|��|St|�dkr`td|t|�f��|dj}	|	dkrv|}	|r�|	dk	r�t�	d�
|	����}	|r�t�
|	�}	|	S)Nz./wa:rr7r4r8r,)r9r#r0r�r>r?rr�r\Z	b64decoder/r7rZtranslate_bool)
r�r:rr5r=r>�defaultr;rRr�r%r%r&�_parse_property�s*	

��

zOvfEnvXml._parse_propertycCs�|j|ddd�}|j|ddd�}|j|dddd�|_|j|ddd�|_|j|d	dd�|_|j|d
dd�|_|j|dddd�|_|�|�dS)
NZProvisioningSectionT�r5Z!LinuxProvisioningConfigurationSetZ
CustomDataF)r=r5ZUserNameZUserPasswordZHostNameZ DisableSshPasswordAuthentication)r>r5)r<r@r'r�r&r�r(�_parse_ssh_section)r�r�Zprovisioning_section�
config_setr%r%r&r1�sL�������z0OvfEnvXml._parse_linux_configuration_set_sectioncCsL|j|ddd�}|j|ddd�}|j|ddddd�|_|j|ddd�|_dS)	NZPlatformSettingsSectionTrAZPlatformSettingsZPreprovisionedVmF)r>r?r5ZPreprovisionedVMType)r<r@r*r+)r�r�Zplatform_settings_sectionZplatform_settingsr%r%r&r2�s,����z*OvfEnvXml._parse_platform_settings_sectionc	Cs�g|_|j|ddd�}|dkr"dS|j|ddd�}|dkr>dS|�dtj�D]N}|j|ddd�}|j|ddd�}|j|dd	dd
�}|||d�}|j�|�qLdS)NZSSHFrAZ
PublicKeysz./wa:PublicKeyZFingerprint�PathZValuer,)r?r5)r�r�r�)r)r<r9r#r0r@r�)	r�rCZssh_sectionZpublic_keys_sectionZ
public_keyr�r�r�r�r%r%r&rB�s@�����zOvfEnvXml._parse_ssh_section)r$)FFN)r r�r�r0r	rqr�r�rrr�r.r"r4r<r@r1r2rBr%r%r%r&r#TsV��
�����$"r#)NN)Vr\�enumraZloggingrhr�r�r�r-r]�
contextlibrrr|rrr�typingrrr	r
rZ	xml.etreerZxml.sax.saxutilsr
Z	cloudinitrrrrrrrZcloudinit.reportingrZcloudinit.settingsrZ	getLoggerr r>ZDEFAULT_WIRESERVER_ENDPOINTrCrMrVr`rlrprr!rrr(r9rJrOrqrBrWrcrxrer�r�rr�rzr�r�r�r�rrr�r�r�r�rrrrrr�Enumrr#r%r%r%r&�<module>s�$
�� 
S
��(

	��7�"?"f�
�