Current File : //usr/lib/python3/dist-packages/cloudinit/sources/helpers/__pycache__/azure.cpython-312.pyc
�

x[h����R�ddlZddlZddlZddlZddlZddlZddlZddlmZddl	m	Z	m
Z
ddlmZmZddl
mZmZmZmZmZddlmZddlmZddlmZmZmZmZmZmZdd	lm Z dd
l!m"Z"ejFe$�Z%dZ&dZ'd
Z(dZ)dZ*e jVddd��Z,ed�Z-dede-fdede-ffd�Z.e.d��Z/e.d��Z0dd�de1de jdfd�Z3d�Z4e.d��Z5ed ��Z6e.dd!d"d#�d$e1d%e7d&ee8d'e9d(e9dejtfd)��Z;d*e1d+e1d,e1de8fd-�Z<Gd.�d/�Z=Gd0�d1e>�Z?Gd2�d3�Z@Gd4�d5�ZAGd6�d7�ZBGd8�d9�ZCe.		dGd:e1d;ej�d<eee1d=ee1fd>��ZEe.d:e1d?d@fdA��ZFdB�ZGGdC�dDe>�ZHGdE�dF�ZIy)H�N)�contextmanager)�datetime�timezone)�sleep�time)�Callable�List�Optional�TypeVar�Union)�ElementTree)�escape)�distros�subp�
temp_utils�
url_helper�util�version)�events)�errorsz
168.63.129.16�boot-telemetryzsystem-info�
diagnostic�
compressedzazure-dsz initialize reporter for azure dsT)�name�description�reporting_enabled�T�func.�returnc����fd�}|S)Nc���tj�j�jt��5�|i|��cddd�S#1swYyxYw)N�rr�parent)r�ReportEventStack�__name__�azure_ds_reporter)�args�kwargsrs  ��A/usr/lib/python3/dist-packages/cloudinit/sources/helpers/azure.py�implz)azure_ds_telemetry_reporter.<locals>.impl*sF���
�
$�
$�����
�
�$�
�	)�
��(��(�	)�	)�	)�s�A�A
�)rr*s` r)�azure_ds_telemetry_reporterr,)s���)��K�c
�,�tj�std��tj	d�	tt
��ttj��z
}	tjgd�d��\}}d}|rd|vr|jd�d	}|std
��|t|�dzz}	tjgd�d��\}}d}|rd|vr|jd�d	}|std��|t|�dzz}tjtddt!j"|t$j&�j)��dt!j"|t$j&�j)��dt!j"|t$j&�j)���tj*�}tj,|�|S#t$r}td�|�d}~wwxYw#tj$r}td|z�|�d}~wt$r}td
|z�|�d}~wwxYw#tj$r}td|z�|�d}~wt$r}td|z�|�d}~wwxYw)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 timestampN)�	systemctl�show�-p�UserspaceTimestampMonotonicT)�capture�=�z8Failed to parse UserspaceTimestampMonotonic from systemdi@Bz-Failed to get UserspaceTimestampMonotonic: %sz<Failed to parse UserspaceTimestampMonotonic from systemd: %s)r/r0zcloud-init-localr1�InactiveExitTimestampMonotonicz;Failed to parse InactiveExitTimestampMonotonic from systemdz0Failed to get InactiveExitTimestampMonotonic: %sz?Failed to parse InactiveExitTimestampMonotonic from systemd: %srz
kernel_start=z user_start=z cloudinit_activation=)r�uses_systemd�RuntimeError�LOG�debug�floatrr�uptime�
ValueErrorr�split�ProcessExecutionErrorr�ReportingEvent�BOOT_EVENT_TYPEr�
fromtimestampr�utc�	isoformat�DEFAULT_EVENT_ORIGIN�report_event)�kernel_start�e�out�_�tsm�
user_start�cloudinit_activation�evts        r)�get_boot_telemetryrO5s������!��N�O�O��I�I�)�*�P��T�V�}�u�T�[�[�]�';�;������F��
���Q����3�#�:��)�)�C�.��#�C���J��
�"�U�3�Z�'�%9�:�
�����
��	
���Q����3�#�:��)�)�C�.��#�C���M��
� ,�u�S�z�G�/C�D���
�
���
�"�"�<����>�H�H�J��"�"�:�x�|�|�<�F�F�H��"�"�$�h�l�l�
��i�k�
�		
�	�#�#��C�������J��S�P��G�H�a�O��P��$�%�%���;�a�?�
��	�����J�Q�N�
��	����2�%�%���>��B�
��	�����M��
�
��	���sa�1G/�(AH�?AI�/	H	�8H�H	�I�H.�.I�:I	�	I�J�$I3�3J�?J�Jc�0�tj�}tjtddtj��d|d�d|d�d|dd	�d
|dd�d|dd
�d|d��tj�}tj|�|S)z%Collect and report system informationzsystem informationzcloudinit_version=z, kernel_version=�releasez
, variant=�variantz, distro_name=�distrz, distro_version=r5z	, flavor=�z, python_version=�python)	r�system_inforr@�SYSTEMINFO_EVENT_TYPEr�version_stringrErF)�inforNs  r)�get_system_inforZ�s�������D�
�
�
���

�"�"�$���O���O���L��O���L��O���L��O���N�	
�	�#�#��C�"������Jr-��logger_func�msgc��t|�r||�tjtd|tj�}tj
|dh��|S)zReport a diagnostic eventzdiagnostic message�log��excluded_handler_types)�callablerr@�DIAGNOSTIC_EVENT_TYPErErF)r]r\rNs   r)�report_diagnostic_eventrd�sQ������C��
�
�
�����#�#�	�C�����U�G�<��Jr-c�*�tjtj|��}d|j	d�d�}tjt|tj|�t
j�}tj|hd���|S)zReport a compressed eventzgz+b64�ascii)�encoding�data>r_�print�webhookr`)�base64�encodebytes�zlib�compress�decoderr@�COMPRESSED_EVENT_TYPE�json�dumpsrErF)�
event_name�
event_content�compressed_data�
event_datarNs     r)�report_compressed_eventrw�s}���(�(����}�)E�F�O���&�&�w�/��J��
�
����
�
�:���#�#�	�C�����$?��
�Jr-c��tjd�	tjdgdd��\}}td|�y#t$r1}tdt
|�ztj��Yd}~yd}~wwxYw)	zReport dmesg to KVP.zDumping dmesg log to KVP�dmesgFT)ror3z$Exception when dumping dmesg log: %sr[N)r9r:rrw�	Exceptionrd�repr�warning)rIrJ�exs   r)�report_dmesg_to_kvpr~�sh���I�I�(�)�
����G�9�U�D�A���Q����-���
��2�T�"�X�=����	
�	
��
�s�(A�	A:�	'A5�5A:c#�K�tj�}tjtjj	|��	d��tj|�y#tj|�wxYw�w�N)�os�getcwd�chdir�path�
expanduser)�newdir�prevdirs  r)�cdr��sL�����i�i�k�G��H�H�R�W�W�
�
��
'�(��
�
�����������s�AA>�
A$�A>�$A;�;A>��)rh�retry_sleep�timeout_minutes�url�headersrhr�r�c	��|dzt�z}d}d}|s |dz
}	tj|||d��}	t	d
||fztj��|S#tj$r_}t	d||||j
|jfztj��t�|z|k\s
d	t|�vr�Yd}~nd}~wwxYwt|�|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.
    �<rNr5)r�r�)r�rh�timeoutzdFailed HTTP request with Azure endpoint %s during attempt %d with exception: %s (code=%r headers=%r)r[zNetwork is unreachablez@Successful HTTP request with Azure endpoint %s after %d attempts)rr�readurl�UrlErrorrd�coder�r9r:�strr)	r�r�rhr�r�r��attempt�responserHs	         r)�http_with_retriesr��s�����"�T�V�+�G��G��H���1���	�!�)�)��W�4���H�
�,�	��g��	'��I�I��
�O��5�"�"�	�#�E����A�F�F�A�I�I�6�7� �I�I�	
����$��/�+�s�1�v�5��6��	��&	�k��5�s�A�C�,AC�C�username�hostname�
disableSshPwdc�v�tjd�}|j|||��}|jd�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��utf-8)�textwrap�dedent�format�encode)r�r�r��OVF_ENV_TEMPLATE�rets     r)�build_minimal_ovfr�sG�� ���	���2�
!�
!��H�M�"��C��:�:�g��r-c�l�eZdZddd�Zd�Zd
dejfd�Z	ddee	dejfd	�Z
y)�AzureEndpointHttpClient�WALinuxAgentz
2012-11-30)zx-ms-agent-namezx-ms-versionc��d|d�|_y)N�DES_EDE3_CBC)zx-ms-cipher-namez!x-ms-guest-agent-public-x509-cert)�extra_secure_headers)�self�certificates  r)�__init__z AzureEndpointHttpClient.__init__Ds�� .�1<�%
��!r-rc��|j}|r5|jj�}|j|j�t	||��S)N)r�)r��copy�updater�r�)r�r��securer�s    r)�getzAzureEndpointHttpClient.getJs?���,�,����l�l�'�'�)�G��N�N�4�4�4�5� ��g�6�6r-Nrhc��|j}|�+|jj�}|j|�t|||��S)N)rhr�)r�r�r�r�)r�r�rh�
extra_headersr�s     r)�postzAzureEndpointHttpClient.postQs@���,�,���$��l�l�'�'�)�G��N�N�=�)� ��4��A�Ar-)F�NN)r%�
__module__�__qualname__r�r�r�UrlResponser�r
�bytesr�r+r-r)r�r�>sO��)�$��G�

�7�
�(>�(>�7�@D�B�!�%��B�	�	�	�Br-r�c��eZdZdZy)�InvalidGoalStateXMLExceptionz9Raised when GoalState XML is invalid or has missing data.N)r%r�r��__doc__r+r-r)r�r�[s��Cr-r�c	�8�eZdZ	ddeeefdededdfd�Zd�Z	y)	�	GoalState�unparsed_xml�azure_endpoint_client�need_certificaterNc���||_	tj|�|_|jd�|_	|jd�|_
|jd�|_dD]9}t||���d|z}t|tj��t|��d|_|jd	�}|�m|rjtj d
dt"��5|jj%|d
��j&|_|j�td��	ddd�yyy#tj$r$}td|ztj���d}~wwxYw#1swYyxYw)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: %sr[Nz./Container/ContainerIdz4./Container/RoleInstanceList/RoleInstance/InstanceIdz
./Incarnation)�container_id�instance_id�incarnationzMissing %s in GoalState XMLzD./Container/RoleInstanceList/RoleInstance/Configuration/Certificateszget-certificates-xmlzget certificates xmlr"T)r�z/Azure endpoint returned empty certificates xml.)r��ET�
fromstring�root�
ParseErrorrdr9r|�_text_from_xpathr�r�r��getattrr��certificates_xmlrr$r&r��contents)r�r�r�r�rH�attrr]r�s        r)r�zGoalState.__init__`s���&;��"�	��
�
�l�3�D�I�!�1�1�2K�L����0�0�B�
��� �0�0��A���B�	8�D��t�T�"�*�3�d�:��'�����E�2�3�7�7�		8�!%����#�#�
*�
���?�/��(�(�+�2�(��
�
)-�(B�(B�(F�(F���)G�)��(��%��(�(�0�6�I���1�
�
� 0�?��1�}�}�	�#�3�a�7��K�K�
�
��	��2
�
�s$�D+�AE%�+E"�>E�E"�%E.c�V�|jj|�}|�|jSyr�)r��find�text)r��xpath�elements   r)r�zGoalState._text_from_xpath�s'���)�)�.�.��'�����<�<��r-)T)
r%r�r�rr�r�r��boolr�r�r+r-r)r�r�_sA��
"&�	5��C��J�'�5� 7�5��	5�

�5�nr-r�c��eZdZddd�Zd�Zd�Zed��Zejd��Ze	d��Z
ee	d	���Ze	d
��Z
e	d��Ze	d��Ze	d
��Zy)�OpenSSLManagerzTransportPrivate.pemzTransportCert.pem)�private_keyr�c�d�tj�|_d|_|j	�yr�)r�mkdtemp�tmpdir�_certificate�generate_certificate�r�s r)r�zOpenSSLManager.__init__�s&�� �(�(�*��� ����!�!�#r-c�B�tj|j�yr�)r�del_dirr�r�s r)�clean_upzOpenSSLManager.clean_up�s�����T�[�[�!r-c��|jSr��r�r�s r)r�zOpenSSLManager.certificate�s��� � � r-c��||_yr�r�)r��values  r)r�zOpenSSLManager.certificate�s
��!��r-c��tjd�|j�tjd�yt|j�5tj
ddddddd	d
ddd
|jdd|jdg�d}tj|jd�j�D]}d|vs�||j�z
}�||_ddd�tjd�y#1swY�xYw)Nz7Generating certificate for communication with fabric...zCertificate already generated.�openssl�reqz-x509z-nodesz-subjz/CN=LinuxTransportz-days�32768z-newkeyzrsa:3072z-keyoutr�z-outr���CERTIFICATEzNew certificate generated.)r9r:r�r�r�r�certificate_namesr�load_text_file�
splitlines�rstrip)r�r��lines   r)r�z#OpenSSLManager.generate_certificate�s���	�	�K�L����'��I�I�6�7��
����_�	+��I�I������(�������*�*�=�9���*�*�=�9��
�$�K��+�+��&�&�}�5���j�l�
1��!��,��4�;�;�=�0�K�	
1�
 +�D��3	+�4	�	�	�.�/�5	+�	+�s�
A7C?�C?�?Dc�F�ddd|g}tj||��\}}|S)Nr��x509z-noout�rh)r)�action�cert�cmd�resultrJs     r)�_run_x509_actionzOpenSSLManager._run_x509_action�s+���&�(�F�3���I�I�c��-�	����
r-c�f�|jd|�}gd�}tj||��\}}|S)Nz-pubkey)z
ssh-keygenz-iz-m�PKCS8z-fz
/dev/stdinr�)r�r)r�r��pub_key�
keygen_cmd�ssh_keyrJs      r)�_get_ssh_key_from_certz%OpenSSLManager._get_ssh_key_from_cert�s2���'�'�	�;�?��L�
��Y�Y�z��8�
����r-c��|jd|�}|jd�}||dzdjd�}dj|�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\n'

        Azure control plane passes that fingerprint as so:
        '073E19D14D1C799224C6A0FD8DDAB6A8BF27D473'
        z-fingerprintr4r5����:r�)r�r�r>�join)r�r��raw_fp�eq�octetss     r)�_get_fingerprint_from_certz)OpenSSLManager._get_fingerprint_from_cert�sM���&�&�~�{�C��
�[�[��
����Q���$�*�*�3�/���w�w�v��r-c�r�tj|�jd�}|j}ddddd|j	d�g}t|j�5tjdjd
i|j��d	d
j|���\}}ddd�|S#1swYSxYw)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: base64r-r�zuopenssl cms -decrypt -in /dev/stdin -inkey {private_key} -recip {certificate} | openssl pkcs12 -nodes -password pass:T�
)�shellrhNr+)r�r�r�r�r�r�r�rr�r�r)r�r��tag�certificates_content�linesrIrJs       r)�_decrypt_certs_from_xmlz&OpenSSLManager._decrypt_certs_from_xml�s���
�m�m�,�-�2�2�9�=��"�x�x�� �K�N�0�� �'�'��0�

������_�	��Y�Y�*�#�#)�6�D�,0�,B�,B�D���Z�Z��&��F�C��	��
�	��
�s
�AB,�,B6c�P�|j|�}g}i}|j�D]}}|j|�tjd|�rg}�-tjd|�s�Ddj|�}|j
|�}|j|�}|||<g}�|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
r��append�re�matchrr�r)	r�r�rI�current�keysr�r�r��fingerprints	         r)�parse_certificatesz!OpenSSLManager.parse_certificatess����*�*�+;�<�������N�N�$�
	�D��N�N�4� ��x�x�.��5������8�$�?�"�i�i��0���5�5�k�B��"�=�=�k�J��$+��[�!���
	��r-N)r%r�r�r�r�r��propertyr��setterr,r��staticmethodr�r�rr
rr+r-r)r�r��s���-�*���
$�
"��!��!����"��"�!�0�!�0�B� ��!���
!��!��!��!��!��!��0!��!�r-r�c���eZdZejd�Zejd�ZdZdZdZ	dZ
deded	e
d
dfd�Zedd
��Zede
d
dfd��Z		dde
de
de
de
d
ef
d�Zeded
dfd��Zy)�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>
        �Ready�NotReady�ProvisioningFailedi�
goal_stater��endpointrNc�.�||_||_||_y)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�rr�r s    r)r�z GoalStateHealthReporter.__init__Fs��"&���&;��#�!��r-c��|j|jj|jj|jj|j
��}tjd�	|j|��tjd�y#t$r$}td|ztj���d}~wwxYw)N)r�r�r��statusz Reporting ready to Azure fabric.��documentz#exception while reporting ready: %sr[zReported ready to Azure fabric.)
�build_reportr"r�r�r��PROVISIONING_SUCCESS_STATUSr9r:�_post_health_reportrzrd�errorrY)r�r(rHs   r)�send_ready_signalz)GoalStateHealthReporter.send_ready_signal[s����$�$��(�(�4�4��)�)�6�6��(�(�4�4��3�3�	%�
��	�	�	�4�5�	��$�$�h�$�7�	���2�3���	�#�5��9��I�I�
�
��	�s�2B�	C�#C�Crc��|j|jj|jj|jj|j
|j|��}	|j|��tjd�y#t$r&}d|z}t|tj���d}~wwxYw)N)r�r�r�r&�	substatusrr'z%exception while reporting failure: %sr[z!Reported failure to Azure fabric.)
r)r"r�r�r��PROVISIONING_NOT_READY_STATUS�PROVISIONING_FAILURE_SUBSTATUSr+rzrdr9r,r|)r�rr(rHr]s     r)�send_failure_signalz+GoalStateHealthReporter.send_failure_signalos����$�$��(�(�4�4��)�)�6�6��(�(�4�4��5�5��9�9�#�
%�
��	��$�$�h�$�7�	���7�8���	�9�A�=�C�#�C�S�Y�Y�?���	�s�)B�	C�!B;�;Cr�r�r�r&c�>�d}|�<|jjt|�t|d|j���}|jjtt|��t|�t|�t|�|��}|j
d�S)Nr�)�health_substatus�health_description)r�r�r��
health_status�health_detail_subsectionr�)�%HEALTH_DETAIL_SUBSECTION_XML_TEMPLATEr�r�"HEALTH_REPORT_DESCRIPTION_TRIM_LEN�HEALTH_REPORT_XML_TEMPLATEr�r�)	r�r�r�r�r&r/r�
health_detail�
health_reports	         r)r)z$GoalStateHealthReporter.build_report�s����
�� � �F�F�M�M�!'�	�!2�#)�� I�$�"I�"I�J�$�N��M��7�7�>�>��s�;�/�0���-��{�+� ��.�%2�?�
�
��#�#�G�,�,r-r(c���td�tjd�dj|j�}|j
j
||ddi��tjd�y)Nrz&Sending health report to Azure fabric.zhttp://{}/machine?comp=healthzContent-Typeztext/xml; charset=utf-8)rhr�z/Successfully sent health report to Azure fabric)rr9r:r�r$r#r�)r�r(r�s   r)r+z+GoalStateHealthReporter._post_health_report�sc��(	�a���	�	�:�;�-�4�4�T�^�^�D���#�#�(�(���)�+D�E�	)�	
�
	�	�	�C�Dr-)rNr�)r%r�r�r�r�r:r8r*r0r1r9r�r�r�r�r,r-r2r�r)r+r+r-r)rr s��!0����	�"��,-<�H�O�O�	�-�)�#*��$.�!�%9�"�),�&�"��"� 7�"��	"�

�"�*!�4�!�4�&!�9�s�9�t�9�!�9�0��-��-��-��	-�
�-�
�-�8!�E�E�E�d�E�!�Er-rc�8�eZdZdefd�Zd�Zedejddfd��Z	e	ddejde
eefd��Zed	eddfd
��Z
ededefd��Zedefd
��Zedeeefdedefd��Zedededefd��Zedededefd��Zy)�WALinuxAgentShimr c�.�||_d|_d|_yr�)r �openssl_managerr�)r�r s  r)r�zWALinuxAgentShim.__init__�s�� ��
�9=���HL��"r-c�R�|j�|jj�yyr�)rAr�r�s r)r�zWALinuxAgentShim.clean_up�s%�����+�� � �)�)�+�,r-�distrorNc��tjd�	|j|�y#t$r(}t	d|ztj
��Yd}~yd}~wwxYw)NzEjecting the provisioning isoz(Failed ejecting the provisioning iso: %sr[)r9r:�eject_mediarzrdr,)r��iso_devrCrHs    r)�	eject_isozWALinuxAgentShim.eject_iso�sN���	�	�1�2�	����w�'���	�#�:�Q�>��I�I�
�
��	�s�)�	A�A�Ac��d}|j�'|�%t�|_|jj}|j�t	|�|_|j|du��}d}|�|j
||�}t||j|j�}|�|j||��|j�|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�)rC)rAr�r�r�r��_fetch_goal_state_from_azure�_get_user_pubkeysrr rGr-)r�rC�pubkey_inforF�http_client_certificater�ssh_keys�health_reporters        r)�"register_with_azure_and_fetch_dataz3WALinuxAgentShim.register_with_azure_and_fetch_data�s���#'�����'�K�,C�#1�#3�D� �&*�&:�&:�&F�&F�#��%�%�-�)@�'�*�D�&��6�6�4�D�@�7�
�
����"��-�-�j�+�F�H�1���2�2�D�M�M�
�����N�N�7�6�N�2��)�)�+��r-rc���|j�td�|_|jd��}t||j|j�}|j|��y)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.
        NFrI�r)r�r�rJrr r2)r�rrrOs    r)�&register_with_azure_and_report_failurez7WALinuxAgentShim.register_with_azure_and_report_failure�s^���%�%�-�)@��)F�D�&��6�6��6�N�
�1���2�2�D�M�M�
��	�+�+��+�Dr-r�c�F�|j�}|j||�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_xmls   r)rJz-WALinuxAgentShim._fetch_goal_state_from_azures,��#'�"I�"I�"K���-�-�#�%5�
�	
r-c��tjd�dj|j�}	t	j
ddt��5|jj|�}ddd�tjd	�jS#1swY�*xYw#t$r$}td|ztj���d}~wwxYw)
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 goalstater"Nz9failed to register with Azure and fetch GoalState XML: %sr[z#Successfully fetched GoalState XML.)r9rYr�r rr$r&r�r�rzrdr|r:r�)r�r�r�rHs    r)rUz3WALinuxAgentShim._get_raw_goal_state_xml_from_azures���	���,�-�1�8�8����G��
	��(�(�*�0�(��
?�
 �5�5�9�9�#�>��
?�	�	�	�7�8�� � � �
?�
?���	�#�K����K�K�
�

��
	�s/�B�B�*B�B�B�	C�(C�CrWc�B�	t||j|�}dj
d|jzd|jzd|jzg�}t|tj��|S#t$r$}td|ztj
���d}~wwxYw)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: %sr[Nz, zGoalState XML container id: %szGoalState XML instance id: %szGoalState XML incarnation: %s)r�r�rzrdr9r|rr�r�r�r:)r�rWr�rrHr]s      r)rVz*WALinuxAgentShim._parse_raw_goal_state_xml2s���	�"�'��*�*� ��J��i�i�0�:�3J�3J�J�/�*�2H�2H�H�/�*�2H�2H�H�
�
��	 �����;�����	�#�4�q�8��K�K�
�
��	�s�A1�1	B�:B�BrrLc���g}|j�Z|�X|j�Ltjd�|jj	|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.
        z/Certificate XML found; parsing out public keys.)r�rAr9r:r�_filter_pubkeys)r�rrLrN�keys_by_fingerprints     r)rKz"WALinuxAgentShim._get_user_pubkeysTsn��:���'�'�3��'��$�$�0��I�I�G�H�"&�"6�"6�"I�"I��+�+�#���+�+�,?��M�H��r-r\c��g}|D]t}d|vr|dr|j|d��!d|vr:|dr5|d}||vr|j||��Htjd|��_tjd|��v|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�rzIovf-env.xml specified PublicKey fingerprint %s not found in goalstate XMLzFovf-env.xml specified PublicKey with neither value nor fingerprint: %s)rr9r|)r\rLr�pubkeyrs     r)r[z WALinuxAgentShim._filter_pubkeys~s�����!�	�F��&� �V�G�_����F�7�O�,��&�(�V�M�-B�$�]�3���"5�5��K�K� 3�K� @�A��K�K�8�#�����0���	�(�r-r�)r%r�r�r�r�r�r,r�DistrorGr
r	rPrSr�r�rJr�rUrrV�listrKr�dictr[r+r-r)r?r?�se��M��M�
,�!������D��!��!�@D�#��n�n�#�	�$�s�)�	�#�!�#�J!�E�#�E�$�E�!�E�!�
� $�
�	�
�!�
�!�!�E�!�!�!�4!��!&�s�E�z�!2����
�	�!��B!�'�#�'�26�'�	
�'�!�'�R�!�T�!��!��!��!r-r?r rCrLrFc��t|��}	|j|||��|j�S#|j�wxYw)N�r )rCrLrF)r?rPr�)r rCrLrF�shims     r)�get_metadata_from_fabricre�sB���X�.�D���6�6��{�G�7�
�	
�
�
����
�
��s	�2�Ar,zerrors.ReportableErrorc��t|��}|j�}	|j|��|j�y#|j�wxYw)NrcrR)r?�as_encoded_reportrSr�)r r,rdrs    r)�report_failure_to_fabricrh�sC���X�.�D��)�)�+�K���3�3��3�L��
�
����
�
��s�A�Ac�|�td|ztj��td|ztj��y)Nzdhclient output stream: %sr[zdhclient error stream: %s)rdr9r:)rI�errs  r)�dhcp_log_cbrk�s0���$�s�*��	�	���#�c�)�s�y�y�r-c��eZdZy)�NonAzureDataSourceN)r%r�r�r+r-r)rmrm�s��r-rmc��eZdZddd�Zdddddddddd�	deedeed	eed
eedeedeee	d
edeededdfd�Z
defd�Zededdfd��Z
	ddededefd�Z			d dedededefd�Zd�Zd�Zd�Zy)!�	OvfEnvXmlz)http://schemas.dmtf.org/ovf/environment/1z)http://schemas.microsoft.com/windowsazure)�ovf�waNF�	r��passwordr��custom_data�disable_ssh_password_auth�public_keys�preprovisioned_vm�preprovisioned_vm_type�provision_guest_proxy_agentr�rsr�rtrurvrwrxryrc	��||_||_||_||_||_|xsg|_||_||_|	|_yr�rr)
r�r�rsr�rtrurvrwrxrys
          r)r�zOvfEnvXml.__init__�sN��!��
� ��
� ��
�&���)B��&�'2�'8�b���!2���&<��#�+F��(r-c�4�|j|jk(Sr�)�__dict__)r��others  r)�__eq__zOvfEnvXml.__eq__�s���}�}����.�.r-�ovf_env_xmlc�<�	tj|�}|jd|j��td��t�}|j|�|j|�|S#tj$r}tj|��|�d}~wwxYw)z�Parser for ovf-env.xml data.

        :raises NonAzureDataSource: if XML is not in Azure's format.
        :raises errors.ReportableErrorOvfParsingException: if XML is
                unparsable or invalid.
        )�	exceptionNz./wa:ProvisioningSectionz=Ignoring non-Azure ovf-env.xml: ProvisioningSection not found)r�r�r�r�"ReportableErrorOvfParsingExceptionr��
NAMESPACESrmro�&_parse_linux_configuration_set_section� _parse_platform_settings_section)�clsrr�rH�instances     r)�
parse_textzOvfEnvXml.parse_text�s���	P��=�=��-�D�
�9�9�/����@�H�$�O��
��;���7�7��=��1�1�$�7�����}�}�	P��;�;�a�H�a�O��	P�s�A,�,B�?B�Br�required�	namespacec�"�|jd|�d|��tj�}|s2d|z}tj	|�|rtj|��yt|�dkDr#tjd|t|�fz��|dS)Nz./r�missing configuration for %rr5�*multiple configuration matches for %r (%d)r)�findallror�r9r:r�!ReportableErrorOvfInvalidMetadata�len)r��noderr�r��matchesr]s       r)�_findzOvfEnvXml._finds����,�,�"�D�)�9�+?�+?�
���0�4�7�C��I�I�c�N���>�>�s�C�C��
��\�A�
��:�:�<���W��&�'��
�
�q�z�r-�
decode_base64�
parse_boolc���|jd|ztj�}|s3d|z}tj	|�|rtj|��|St|�dkDr#tjd|t|�fz��|dj}	|	�|}	|r4|	�2tjdj|	j���}	|rtj|	�}	|	S)Nz./wa:r�r5r�rr�)r�ror�r9r:rr�r�r�rk�	b64decoderr>r�translate_bool)
r�r�rr�r�r��defaultr�r]r�s
          r)�_parse_propertyzOvfEnvXml._parse_propertys����,�,�w��~�y�/C�/C�D���0�4�7�C��I�I�c�N���>�>�s�C�C��N��w�<�!���:�:�<���W��&�'��
�
��
�����=��E��U�.��$�$�R�W�W�U�[�[�]�%;�<�E���'�'��.�E��r-c�t�|j|dd��}|j|dd��}|j|ddd��|_|j|dd��|_|j|d	d��|_|j|d
d��|_|j|ddd��|_|j|�y)
N�ProvisioningSectionT�r��!LinuxProvisioningConfigurationSet�
CustomDataF)r�r��UserName�UserPassword�HostName� DisableSshPasswordAuthentication)r�r�)r�r�rtr�rsr�ru�_parse_ssh_section)r�r��provisioning_section�
config_sets    r)r�z0OvfEnvXml._parse_linux_configuration_set_section@s���#�z�z��'�$� *� 
���Z�Z� �/�� �
�
� �/�/�����	0�
����,�,��
�T�-�
��
��,�,����-�
��
��,�,��
�T�-�
��
�*.�)=�)=��.���	*>�*
��&�	
���
�+r-c���|j|dd��}|j|dd��}|j|dddd��|_|j|dd��|_|j|d	ddd��|_y)
N�PlatformSettingsSectionTr��PlatformSettings�PreprovisionedVmF)r�r�r��PreprovisionedVMType�ProvisionGuestProxyAgent)r�r�rwrxry)r�r��platform_settings_section�platform_settingss    r)r�z*OvfEnvXml._parse_platform_settings_sectionbs���$(�J�J��+�d�%/�%
�!�!�J�J�%�'9�D�'�
��"&�!5�!5������"6�"
���'+�&:�&:��"��';�'
��#�
,0�+?�+?��&����,@�,
��(r-c�t�g|_|j|dd��}|�y|j|dd��}|�y|jdtj�D]`}|j|dd��}|j|dd��}|j|dd	d�
�}|||d�}|jj
|��by)N�SSHFr��
PublicKeysz./wa:PublicKey�Fingerprint�Path�Valuer�)r�r�)rr�r�)rvr�r�ror�r�r)	r�r��ssh_section�public_keys_section�
public_keyrr�r�r�s	         r)r�zOvfEnvXml._parse_ssh_section~s�������j�j��U�U�j�C�����"�j�j����)�
���&��-�5�5��i�2�2�
�	-�J��.�.��M�E�/��K��'�'�
�F�U�'�K�D��(�(��G�R�%�)��E� +����G�

���#�#�G�,�	-r-)rq)FFN)r%r�r�r�r
r�r�r�r	rar�r~�classmethodr�r�r�r�r�r�r+r-r)roro�s`��:�9��J�#'�"&�"&�'+�48�,0�"'�04�,1�G��3�-�G��3�-�	G�
�3�-�G��e�_�
G�$,�D�>�G��d�4�j�)�G� �G�!)��
�G�&*�G�
�G�./�t�/���S��[����:�����	�
��:$� ��#��#��	#�
�#��
#�J ,�D
�8-r-ror�)Jrkrq�loggingr�rr�rm�
contextlibrrrrr�typingrr	r
rr�	xml.etreer
r��xml.sax.saxutilsr�	cloudinitrrrrrr�cloudinit.reportingr�cloudinit.sources.azurer�	getLoggerr%r9�DEFAULT_WIRESERVER_ENDPOINTrArWrcrpr$r&rr,rOrZr�r@rdrwr~r�rar��intr�r�r�r�rzr�r�r�rr?r_rerhrkrmror+r-r)�<module>r�s���
���	�	���%�'��;�;�'�#�J�J�&�*��g����!��.��"��%��$��$��+�F�+�+�	�2�����C�L��	�h�s�A�v�&6�	�8�C��F�;K�	��R��R�j����6"��	������$�*�

��

������
!���
3�	�3��3��5�/�	3�
�3��
3����3��3�l��� ��14��
��DB�B�:D�9�D�<�<�~��D[E�[E�|b�b�J�(,�!�	����N�N���$�s�)�$���c�]�	�����s��3K�����	��	�P-�P-r-