
    x[h                     ^   S SK r S SKrS SKrS SKrS SKrS SKrS SKrS SKJr  S SK	J	r	J
r
  S SKJrJr  S SKJrJrJrJrJr  S SKJr  S SKJr  S SKJrJrJrJrJrJr  S S	KJ r   S S
K!J"r"  \RF                  " \$5      r%Sr&Sr'Sr(Sr)Sr*\ RV                  " SSSS9r,\" S5      r-S\S\-4   S\S\-4   4S jr.\.S 5       r/\.S 5       r0SS.S\1S\ Rd                  4S jjr3S r4\.S 5       r5\S  5       r6\.SS!S"S#.S$\1S%\7S&\\8   S'\9S(\9S\Rt                  4S) jj5       r;S*\1S+\1S,\1S\84S- jr< " S. S/5      r= " S0 S1\>5      r? " S2 S35      r@ " S4 S55      rA " S6 S75      rB " S8 S95      rC\.  SGS:\1S;\R                  S<\\\1      S=\\1   4S> jj5       rE\.S:\1S?S@4SA j5       rFSB rG " SC SD\>5      rH " SE SF5      rIg)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-telemetryzsystem-info
diagnostic
compressedzazure-dsz initialize reporter for azure dsT)namedescriptionreporting_enabledTfunc.returnc                    ^  U 4S jnU$ )Nc                     > [         R                  " TR                  TR                  [        S9   T" U 0 UD6sS S S 5        $ ! , (       d  f       g = f)Nr   r   parent)r   ReportEventStack__name__azure_ds_reporter)argskwargsr   s     A/usr/lib/python3/dist-packages/cloudinit/sources/helpers/azure.pyimpl)azure_ds_telemetry_reporter.<locals>.impl*   sA    $$$

 ((
 
 
s   A
A )r   r*   s   ` r)   azure_ds_telemetry_reporterr-   )   s    ) K    c                  x   [         R                  " 5       (       d  [        S5      e[        R	                  S5         [        [        5       5      [        [        R                  " 5       5      -
  n  [        R                  " / SQSS9u  p#SnU(       a  SU;   a  UR                  S5      S	   nU(       d  [        S
5      eU [        U5      S-  -   n [        R                  " / SQSS9u  p#SnU(       a  SU;   a  UR                  S5      S	   nU(       d  [        S5      eU [        U5      S-  -   n[        R                  " [        SS[         R"                  " U [$        R&                  5      R)                  5       < S[         R"                  " U[$        R&                  5      R)                  5       < S[         R"                  " U[$        R&                  5      R)                  5       < 3[        R*                  5      n[        R,                  " U5        U$ ! [         a  n[        S5      UeSnAff = f! [        R                   a  n[        SU-  5      UeSnAf[         a  n[        SU-  5      UeSnAff = f! [        R                   a  n[        SU-  5      UeSnAf[         a  n[        SU-  5      UeSnAff = f)zWReport timestamps related to kernel initialization and systemd
activation of cloud-initz1distro not using systemd, skipping boot telemetryzCollecting boot telemetryz*Failed to determine kernel start timestampN)	systemctlshow-pUserspaceTimestampMonotonicT)capture=   z8Failed to parse UserspaceTimestampMonotonic from systemdi@B z-Failed to get UserspaceTimestampMonotonic: %sz<Failed to parse UserspaceTimestampMonotonic from systemd: %s)r0   r1   zcloud-init-localr2   InactiveExitTimestampMonotonicz;Failed to parse InactiveExitTimestampMonotonic from systemdz0Failed to get InactiveExitTimestampMonotonic: %sz?Failed to parse InactiveExitTimestampMonotonic from systemd: %sr   zkernel_start=z user_start=z cloudinit_activation=)r   uses_systemdRuntimeErrorLOGdebugfloatr   r   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_telemetryrP   5   s    !!NOOII)*PTV}uT[[]';;F
 3#:))C.#CJ  "U3Z'%9:
 	
 3#:))C.#CM   ,uSzG/CD 

 ""<>HHJ"":x||<FFH""$hllik		
 	##C  JS  PGHaOP$ %% ;a?
	  JQN
	2 %% >B
	  M
 	sa   2H /AH. AI5 
H+H&&H+.I2II2I--I25J9	JJ9%J44J9c                  F   [         R                  " 5       n [        R                  " [        SS[
        R                  " 5       < SU S   < SU S   < SU S   S	   < S
U S   S   < SU S   S   < SU S   < 3[        R                  5      n[        R                  " U5        U$ )z%Collect and report system informationzsystem informationzcloudinit_version=z, kernel_version=releasez
, variant=variantz, distro_name=distr   z, distro_version=r6   z	, flavor=   z, python_version=python)	r   system_infor   rA   SYSTEMINFO_EVENT_TYPEr   version_stringrF   rG   )inforO   s     r)   get_system_infor[      s     D



 ""$OOLOLOLON	
 	##C"  Jr.   logger_funcmsgc                    [        U5      (       a  U" U 5        [        R                  " [        SU [        R                  5      n[        R
                  " US1S9  U$ )zReport a diagnostic eventzdiagnostic messagelogexcluded_handler_types)callabler   rA   DIAGNOSTIC_EVENT_TYPErF   rG   )r^   r]   rO   s      r)   report_diagnostic_eventre      sT     C


##	C UG< Jr.   c                 .   [         R                  " [        R                  " U5      5      nSUR	                  S5      S.n[
        R                  " [        U [        R                  " U5      [
        R                  5      n[
        R                  " U1 SkS9  U$ )zReport a compressed eventzgz+b64ascii)encodingdata>   r`   printwebhookra   )base64encodebyteszlibcompressdecoder   rA   COMPRESSED_EVENT_TYPEjsondumpsrF   rG   )
event_nameevent_contentcompressed_data
event_datarO   s        r)   report_compressed_eventrx      s}    ((})EFO&&w/J 



:##	C $?
 Jr.   c                      [         R                  S5         [        R                  " S/SSS9u  p[        SU 5        g! [         a.  n[        S[        U5      -  [         R                  S9   SnAgSnAff = f)	zReport dmesg to KVP.zDumping dmesg log to KVPdmesgFT)rp   r4   z$Exception when dumping dmesg log: %sr\   N)r:   r;   r   rx   	Exceptionre   reprwarning)rJ   rK   exs      r)   report_dmesg_to_kvpr      sa     II()
G9UDA- 
2T"X=	

s   %= 
A5$A00A5c              #     #    [         R                  " 5       n[         R                  " [         R                  R	                  U 5      5         S v   [         R                  " U5        g ! [         R                  " U5        f = f7fN)osgetcwdchdirpath
expanduser)newdirprevdirs     r)   cdr      sK     iikGHHRWW'(
s   A	BA' B'A??B      )ri   retry_sleeptimeout_minutesurlheadersri   r   r   c          	         US-  [        5       -   nSnSnU(       d  US-  n [        R                  " XUSS9n [	        S
X4-  [        R                  S9  U$ ! [        R                   a]  n[	        SXXR
                  UR                  4-  [        R                  S9  [        5       U-   U:  d  S	[        U5      ;   a  e  SnAOSnAff = f[        U5        U(       d  M  N)zReadurl 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.
<   r   Nr6   )r   r   )r   ri   timeoutzdFailed HTTP request with Azure endpoint %s during attempt %d with exception: %s (code=%r headers=%r)r\   zNetwork is unreachablez@Successful HTTP request with Azure endpoint %s after %d attempts)r   r   readurlUrlErrorre   coder   r:   r;   strr   )	r   r   ri   r   r   r   attemptresponserI   s	            r)   http_with_retriesr      s     "TV+GGH1	!))4H , 		'II
 O5 "" 	#EFFAII67  II	 $/+s1v5 6	& 	k5 hs   A C+ACCusernamehostnamedisableSshPwdc                 p    [         R                  " S5      nUR                  XUS9nUR                  S5      $ )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     sE      	2 
!
!M " C ::gr.   c                   |    \ rS rSrSSS.rS rSS\R                  4S jjr SS	\	\
   S\R                  4S
 jjrSrg)AzureEndpointHttpClienti>  WALinuxAgentz
2012-11-30)zx-ms-agent-namezx-ms-versionc                     SUS.U l         g )NDES_EDE3_CBC)zx-ms-cipher-namez!x-ms-guest-agent-public-x509-certextra_secure_headers)selfcertificates     r)   __init__ AzureEndpointHttpClient.__init__D  s     .1<%
!r.   r   c                     U R                   nU(       a5  U R                   R                  5       nUR                  U R                  5        [	        XS9$ )N)r   )r   copyupdater   r   )r   r   securer   s       r)   getAzureEndpointHttpClient.getJ  s=    ,,ll'')GNN4445 66r.   Nri   c                     U R                   nUb+  U R                   R                  5       nUR                  U5        [        XUS9$ )N)ri   r   )r   r   r   r   )r   r   ri   extra_headersr   s        r)   postAzureEndpointHttpClient.postQ  s>     ,,$ll'')GNN=) AAr.   r   )FNN)r%   
__module____qualname____firstlineno__r   r   r   UrlResponser   r
   bytesr   __static_attributes__r,   r.   r)   r   r   >  sU    )$G

7
(>(> 7 @DB!%B			B Br.   r   c                       \ rS rSrSrSrg)InvalidGoalStateXMLExceptioni[  z9Raised when GoalState XML is invalid or has missing data.r,   N)r%   r   r   r   __doc__r   r,   r.   r)   r   r   [  s    Cr.   r   c            	       D    \ rS rSr S
S\\\4   S\S\SS4S jjr	S r
S	rg)	GoalStatei_  unparsed_xmlazure_endpoint_clientneed_certificater   Nc                    X l          [        R                  " U5      U l        U R                  S5      U l	        U R                  S5      U l
        U R                  S5      U l        S H7  n[        X5      b  M  SU-  n[        U[        R                  S9  [        U5      e   SU l        U R                  S	5      nUbn  U(       af  [        R                   " S
S["        S9   U R                   R%                  USS9R&                  U l        U R                  c  [        S5      e SSS5        ggg! [        R                   a!  n[        SU-  [        R                  S9  e SnAff = f! , (       d  f       g= f)a@  Parses 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incarnationzMissing %s in GoalState XMLzD./Container/RoleInstanceList/RoleInstance/Configuration/Certificateszget-certificates-xmlzget certificates xmlr"   T)r   z/Azure endpoint returned empty certificates xml.)r   ET
fromstringroot
ParseErrorre   r:   r}   _text_from_xpathr   r   r   getattrr   certificates_xmlr   r$   r&   r   contents)r   r   r   r   rI   attrr^   r   s           r)   r   GoalState.__init__`  sx    &;"	l3DI !112KL00B
  00ABDt"*3d:'E2377	 C !%##*
 ?/((+2(
 )-(B(B(F(F )G )( % ((06I  1   0?1 }} 	#3a7KK 	2 s$   D, AE$,E! EE!$
E2c                 X    U R                   R                  U5      nUb  UR                  $ g r   )r   findtext)r   xpathelements      r)   r   GoalState._text_from_xpath  s'    ))..'<<r.   )r   r   r   r   r   r   )T)r%   r   r   r   r   r   r   r   boolr   r   r   r,   r.   r)   r   r   _  sA    
 "&	5CJ'5  75 	5
 
5nr.   r   c                       \ rS rSrSSS.rS rS r\S 5       r\R                  S 5       r\
S	 5       r\\
S
 5       5       r\
S 5       r\
S 5       r\
S 5       r\
S 5       rSrg)OpenSSLManageri  zTransportPrivate.pemzTransportCert.pem)private_keyr   c                 f    [         R                  " 5       U l        S U l        U R	                  5         g r   )r   mkdtemptmpdir_certificategenerate_certificater   s    r)   r   OpenSSLManager.__init__  s&     ((* !!#r.   c                 D    [         R                  " U R                  5        g r   )r   del_dirr   r   s    r)   clean_upOpenSSLManager.clean_up  s    T[[!r.   c                     U R                   $ r   r   r   s    r)   r   OpenSSLManager.certificate  s       r.   c                     Xl         g r   r   )r   values     r)   r   r     s    !r.   c                 ,   [         R                  S5        U R                  b  [         R                  S5        g [        U R                  5         [
        R
                  " SSSSSSS	S
SSSU R                  S   SU R                  S   /5        Sn[        R                  " U R                  S   5      R                  5        H  nSU;  d  M  XR                  5       -  nM     Xl        S S S 5        [         R                  S5        g ! , (       d  f       N$= f)Nz7Generating certificate for communication with fabric...zCertificate already generated.opensslreqz-x509z-nodesz-subjz/CN=LinuxTransportz-days32768z-newkeyzrsa:3072z-keyoutr   z-outr    CERTIFICATEzNew certificate generated.)r:   r;   r   r   r   r   certificate_namesr   load_text_file
splitlinesrstrip)r   r   lines      r)   r   #OpenSSLManager.generate_certificate  s    		KL'II67_II(**=9**=9$ K++&&}5jl !,;;=0K	
  +3 4 			./5 _s   A9DD
Dc                 >    SSSU /n[         R                   " X!S9u  p4U$ )Nr   x509z-nooutri   )r   )actioncertcmdresultrK   s        r)   _run_x509_actionOpenSSLManager._run_x509_action  s'     &(F3IIc-	r.   c                 ^    U R                  SU5      n/ SQn[        R                  " X2S9u  pEU$ )Nz-pubkey)z
ssh-keygenz-iz-mPKCS8z-fz
/dev/stdinr   )r  r   )r   r   pub_key
keygen_cmdssh_keyrK   s         r)   _get_ssh_key_from_cert%OpenSSLManager._get_ssh_key_from_cert  s.    ''	;?L
YYz8
r.   c                     U R                  SU5      nUR                  S5      nX#S-   S R                  S5      nSR                  U5      $ )zopenssl 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-fingerprintr5   r6   :r   )r  r   r?   join)r   r   raw_fpeqoctetss        r)   _get_fingerprint_from_cert)OpenSSLManager._get_fingerprint_from_cert  sK     &&~{C[[Q$**3/wwvr.   c                 x   [         R                  " U5      R                  S5      nUR                  nSSSSSUR	                  S5      /n[        U R                  5         [        R                  " SR                  " S0 U R                  D6S	S
R                  U5      S9u  pVSSS5        U$ ! , (       d  f       W$ = f)zDecrypt the certificates XML document using the our private key;
return the list of certs and private keys contained in the doc.
z.//Datas   MIME-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   
)shellri   Nr,   )r   r   r   r   r   r   r   r   r   r   r  )r   r   tagcertificates_contentlinesrJ   rK   s          r)   _decrypt_certs_from_xml&OpenSSLManager._decrypt_certs_from_xml  s    
 mm,-229="xx KN0 ''0
 _YY##)6* D,0,B,BD ZZ&FC  
 _ 
s   AB**
B9c                 n   U R                  U5      n/ n0 nUR                  5        H  nUR                  U5        [        R                  " SU5      (       a  / nM4  [        R                  " SU5      (       d  MR  SR                  U5      nU R                  U5      nU R                  U5      nXtU'   / nM     U$ )zxGiven 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matchr  r  r  )	r   r   rJ   currentkeysr   r   r  fingerprints	            r)   parse_certificates!OpenSSLManager.parse_certificates  s     **+;<NN$DNN4 xx.558$??"ii055kB"==kJ$+[! % r.   )r   r   r   N)r%   r   r   r   r   r   r   propertyr   setterr-   r   staticmethodr  r  r  r  r'  r   r,   r.   r)   r   r     s    -*
$
" ! ! " " !0 !0B   ! 
 ! ! ! ! ! !0 ! !r.   r   c                       \ rS rSr\R
                  " S5      r\R
                  " S5      rSrSr	Sr
SrS\S	\S
\SS4S jr\SS j5       r\S\SS4S j5       r  SS\S\S\S\S\4
S jjr\S\SS4S j5       rSrg)GoalStateHealthReporteri   a          <?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   endpointr   Nc                 (    Xl         X l        X0l        g)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   r1  r   r2  s       r)   r    GoalStateHealthReporter.__init__F  s    " &&;#!r.   c                    U R                  U R                  R                  U R                  R                  U R                  R                  U R
                  S9n[        R                  S5         U R                  US9  [        R                  S5        g ! [         a!  n[        SU-  [        R                  S9  e S nAff = f)N)r   r   r   statusz Reporting ready to Azure fabric.documentz#exception while reporting ready: %sr\   zReported ready to Azure fabric.)build_reportr4  r   r   r   PROVISIONING_SUCCESS_STATUSr:   r;   _post_health_reportr{   re   errorrZ   )r   r;  rI   s      r)   send_ready_signal)GoalStateHealthReporter.send_ready_signal[  s    $$((44))66((4433	 % 
 			45	$$h$7 	23  	#59II 	s   /B 
B?B::B?r   c           	      v   U R                  U R                  R                  U R                  R                  U R                  R                  U R
                  U R                  US9n U R                  US9  [        R                  S5        g ! [         a#  nSU-  n[        U[        R                  S9  e S nAff = f)N)r   r   r   r9  	substatusr   r:  z%exception while reporting failure: %sr\   z!Reported failure to Azure fabric.)r<  r4  r   r   r   PROVISIONING_NOT_READY_STATUSPROVISIONING_FAILURE_SUBSTATUSr>  r{   re   r:   r?  r}   )r   r   r;  rI   r^   s        r)   send_failure_signal+GoalStateHealthReporter.send_failure_signalo  s    $$((44))66((445599# % 
	$$h$7 	78  	9A=C#CSYY?	s   &B 
B8B33B8r   r   r   r9  c                 4   SnUb9  U R                   R                  [        U5      [        US U R                   5      S9nU R                  R                  [        [        U5      5      [        U5      [        U5      [        U5      US9nUR                  S5      $ )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   r9  rC  r   health_detailhealth_reports	            r)   r<  $GoalStateHealthReporter.build_report  s       FFMM!'	!2#) I$"I"IJ$ N M 77>>s;/0-{+ .%2 ? 
 ##G,,r.   r;  c                     [        S5        [        R                  S5        SR                  U R                  5      nU R
                  R                  UUSS0S9  [        R                  S5        g )Nr   z&Sending health report to Azure fabric.zhttp://{}/machine?comp=healthzContent-Typeztext/xml; charset=utf-8)ri   r   z/Successfully sent health report to Azure fabric)r   r:   r;   r   r6  r5  r   )r   r;  r   s      r)   r>  +GoalStateHealthReporter._post_health_report  sc    ( 	a		:;-44T^^D##(()+DE 	) 	

 			CDr.   )r5  r6  r4  )r   Nr   )r%   r   r   r   r   r   rO  rM  r=  rD  rE  rN  r   r   r   r   r-   r@  rF  r   r<  r>  r   r,   r.   r)   r-  r-     s
   !)	", -5OO	-) #*$.!%9"),&""  7" 	"
 
"* !4 !4& !9s 9t 9 !90 -- - 	-
 - 
-8 !EE Ed E !Er.   r-  c                   T   \ rS rSrS\4S jrS r\S\R                  SS4S j5       r
\ SS\R                  S\\\      4S	 jj5       r\S
\SS4S j5       r\S\S\4S j5       r\S\4S j5       r\S\\\4   S\S\4S j5       r\S\S\S\4S j5       r\S\S\S\4S j5       rSrg)WALinuxAgentShimi  r2  c                 ,    Xl         S U l        S U l        g r   )r2  openssl_managerr   )r   r2  s     r)   r   WALinuxAgentShim.__init__  s     9=HL"r.   c                 T    U R                   b  U R                   R                  5         g g r   )rX  r   r   s    r)   r   WALinuxAgentShim.clean_up  s%    +  ))+ ,r.   distror   Nc                     [         R                  S5         UR                  U5        g ! [         a%  n[	        SU-  [         R
                  S9   S nAg S nAff = f)NzEjecting the provisioning isoz(Failed ejecting the provisioning iso: %sr\   )r:   r;   eject_mediar{   re   r?  )r   iso_devr\  rI   s       r)   	eject_isoWALinuxAgentShim.eject_iso  sI    		12	w' 	#:Q>II	s   ) 
AAAc                    SnU R                   c(  Ub%  [        5       U l         U R                   R                  nU R                  c  [	        U5      U l        U R                  USLS9nSnUb  U R                  XR5      n[        XPR                  U R                  5      nUb  U R                  X1S9  UR                  5         U$ )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   )r\  )rX  r   r   r   r   _fetch_goal_state_from_azure_get_user_pubkeysr-  r2  r`  r@  )r   r\  pubkey_infor_  http_client_certificater1  ssh_keyshealth_reporters           r)   "register_with_azure_and_fetch_data3WALinuxAgentShim.register_with_azure_and_fetch_data  s     #''K,C#1#3D &*&:&:&F&F#%%-)@'*D& 664D@ 7 

 "--jFH122DMM
 NN7N2))+r.   r   c                     U R                   c  [        S5      U l         U R                  SS9n[        X R                   U R                  5      nUR                  US9  g)zGets 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.
NFrc  r   )r   r   rd  r-  r2  rF  )r   r   r1  ri  s       r)   &register_with_azure_and_report_failure7WALinuxAgentShim.register_with_azure_and_report_failure  s\     %%-)@)FD&666N
122DMM
 	+++Dr.   r   c                 D    U R                  5       nU R                  X!5      $ )zFetches 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)   rd  -WALinuxAgentShim._fetch_goal_state_from_azure  s)     #'"I"I"K--#
 	
r.   c                    [         R                  S5        SR                  U R                  5      n [        R
                  " SS[        S9   U R                  R                  U5      nSSS5        [         R                  S	5        WR                  $ ! , (       d  f       N/= f! [         a!  n[        SU-  [         R                  S9  e SnAff = f)
zrFetches the GoalState XML from the Azure endpoint and returns
the XML as a string.

@return: GoalState XML string
zRegistering with Azure...z!http://{}/machine/?comp=goalstatezgoalstate-retrievalzretrieve goalstater"   Nz9failed to register with Azure and fetch GoalState XML: %sr\   z#Successfully fetched GoalState XML.)r:   rZ   r   r2  r   r$   r&   r   r   r{   re   r}   r;   r   )r   r   r   rI   s       r)   rq  3WALinuxAgentShim._get_raw_goal_state_xml_from_azure  s     	,-188G	((*0(
  5599#> 			78      	#KKK
 	s5   B" B(B" 
BB" B" "
C,CCrs  c                 8    [        UU R                  U5      nSR                  SUR                  -  SUR                  -  SUR                  -  /5      n[        U[        R                  S9  U$ ! [         a!  n[        SU-  [        R
                  S9  e SnAff = f)zParses 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, zGoalState XML container id: %szGoalState XML instance id: %szGoalState XML incarnation: %s)r   r   r{   re   r:   r}   r  r   r   r   r;   )r   rs  r   r1  rI   r^   s         r)   rr  *WALinuxAgentShim._parse_raw_goal_state_xml2  s    	"'** J ii0:3J3JJ/*2H2HH/*2H2HH
 	 ;  	#4q8KK 	s   A. .
B8BBr1  rf  c                     / nUR                   b[  UbX  U R                  bK  [        R                  S5        U R                  R	                  UR                   5      nU R                  XB5      nU$ )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   rX  r:   r;   r'  _filter_pubkeys)r   r1  rf  rh  keys_by_fingerprints        r)   re  "WALinuxAgentShim._get_user_pubkeysT  sl    : ''3'$$0IIGH"&"6"6"I"I++# ++,?MHr.   r{  c                 "   / nU H  nSU;   a   US   (       a  UR                  US   5        M)  SU;   aA  US   (       a7  US   nX@;   a  UR                  X   5        MX  [        R                  SU5        Mp  [        R                  SU5        M     U$ )a  Filter 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:   r}   )r{  rf  r%  pubkeyr&  s        r)   rz   WALinuxAgentShim._filter_pubkeys~  s     !F& VG_F7O,&(VM-B$]35KK 3 @AKK8# 0 "( r.   )r   r2  rX  r   )r%   r   r   r   r   r   r   r-   r   Distror`  r
   r	   rj  rn  r   r   rd  r   rq  r   rr  listre  r+  dictrz  r   r,   r.   r)   rV  rV    se   M M
, ! D  ! !@D#nn#	$s)	# !#J !E# E$ E !E !
 $
	
 !
 !!E ! !!4 !!&sEz!2  
	 !B !'#'26'	' !'R !T ! ! ! !r.   rV  r2  r\  rf  r_  c                     [        U S9n UR                  XUS9UR                  5         $ ! UR                  5         f = f)Nr2  )r\  rf  r_  )rV  rj  r   )r2  r\  rf  r_  shims        r)   get_metadata_from_fabricr    s@     X.D66G 7 
 	s   + =r?  zerrors.ReportableErrorc                     [        U S9nUR                  5       n UR                  US9  UR                  5         g ! UR                  5         f = f)Nr  rm  )rV  as_encoded_reportrn  r   )r2  r?  r  r   s       r)   report_failure_to_fabricr    sC    X.D))+K333Ls	   ; Ac                 p    [        SU -  [        R                  S9  [        SU-  [        R                  S9  g )Nzdhclient output stream: %sr\   zdhclient error stream: %s)re   r:   r;   )rJ   errs     r)   dhcp_log_cbr    s0    $s*		 #c)syyr.   c                       \ rS rSrSrg)NonAzureDataSourcei  r,   N)r%   r   r   r   r   r,   r.   r)   r  r    s    r.   r  c                      \ rS rSrSSS.rSSSSSSSSSS.	S\\   S	\\   S
\\   S\\   S\\   S\\	\
      S\S\\   S\SS4S jjrS\4S jr\S\SS 4S j5       r S!S\S\S\4S jjr   S"S\S\S\S\4S jjrS rS rS rS rg)#	OvfEnvXmli  z)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   r  r   r  r  r  r  r  r  r   c       	             Xl         X l        X0l        X@l        XPl        U=(       d    / U l        Xpl        Xl        Xl        g r   r  )
r   r   r  r   r  r  r  r  r  r  s
             r)   r   OvfEnvXml.__init__  s>     !  &)B&'2'8b!2&<#+F(r.   c                 4    U R                   UR                   :H  $ r   )__dict__)r   others     r)   __eq__OvfEnvXml.__eq__  s    }}..r.   ovf_env_xmlc                 >    [         R                  " U5      nUR                  SU R                  5      c  [        S5      e[        5       nUR                  U5        UR                  U5        U$ ! [         R                   a  n[        R                  " US9UeSnAff = f)zParser 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   
NAMESPACESr  r  &_parse_linux_configuration_set_section _parse_platform_settings_section)clsr  r   rI   instances        r)   
parse_textOvfEnvXml.parse_text  s    	P==-D
 99/@H$O  ;77=11$7 }} 	P;;aHaO	Ps   A. .BBBr   required	namespacec                 @   UR                  SU< SU< 3[        R                  5      nU(       d8  SU-  n[        R	                  U5        U(       a  [
        R                  " U5      eg [        U5      S:  a$  [
        R                  " SU[        U5      4-  5      eUS   $ )Nz./r  missing configuration for %rr6   *multiple configuration matches for %r (%d)r   )findallr  r  r:   r;   r   !ReportableErrorOvfInvalidMetadatalen)r   noder   r  r  matchesr^   s          r)   _findOvfEnvXml._find  s     ,,"D)9+?+?
 047CIIcN>>sCC\A::<W&' 
 qzr.   decode_base64
parse_boolc                    UR                  SU-   [        R                  5      nU(       d9  SU-  n[        R	                  U5        U(       a  [
        R                  " U5      eU$ [        U5      S:  a$  [
        R                  " SU[        U5      4-  5      eUS   R                  n	U	c  Un	U(       a6  U	b3  [        R                  " SR                  U	R                  5       5      5      n	U(       a  [        R                  " U	5      n	U	$ )Nz./wa:r  r6   r  r   r   )r  r  r  r:   r;   r   r  r  r   rl   	b64decoder  r?   r   translate_bool)
r   r  r   r  r  r  defaultr  r^   r   s
             r)   _parse_propertyOvfEnvXml._parse_property  s     ,,w~y/C/CD047CIIcN>>sCCNw<!::<W&' 
 
 =EU.$$RWWU[[]%;<E''.Er.   c                 J   U R                  USSS9nU R                  USSS9nU R                  USSSS9U l        U R                  USSS9U l        U R                  US	SS9U l        U R                  US
SS9U l        U R                  USSSS9U l        U R                  U5        g )NProvisioningSectionTr  !LinuxProvisioningConfigurationSet
CustomDataF)r  r  UserNameUserPasswordHostName DisableSshPasswordAuthentication)r  r  )r  r  r  r   r  r   r  _parse_ssh_section)r   r   provisioning_section
config_sets       r)   r  0OvfEnvXml._parse_linux_configuration_set_section@  s    #zz'$  *  
 ZZ /   

  //	 0 
 ,,
T - 
 ,, - 
 ,,
T - 
 *.)=)=.	 *> *
& 	
+r.   c                     U R                  USSS9nU R                  USSS9nU R                  USSSSS9U l        U R                  USSS9U l        U R                  US	SSSS9U l        g )
NPlatformSettingsSectionTr  PlatformSettingsPreprovisionedVmF)r  r  r  PreprovisionedVMTypeProvisionGuestProxyAgent)r  r  r  r  r  )r   r   platform_settings_sectionplatform_settingss       r)   r  *OvfEnvXml._parse_platform_settings_sectionb  s    $(JJ+d %/ %
! !JJ%'9D ' 
 "&!5!5 "6 "
 '+&:&:" '; '
#
 ,0+?+?& ,@ ,
(r.   c                 ^   / U l         U R                  USSS9nUc  g U R                  USSS9nUc  g UR                  S[        R                  5       HX  nU R                  USSS9nU R                  USSS9nU R                  USS	SS
9nUUUS.nU R                   R                  U5        MZ     g )NSSHFr  
PublicKeysz./wa:PublicKeyFingerprintPathValuer   )r  r  )r&  r   r   )r  r  r  r  r  r  r!  )	r   r  ssh_sectionpublic_keys_section
public_keyr&  r   r   r  s	            r)   r  OvfEnvXml._parse_ssh_section~  s    jjUUjC"jj ) 
 &-55i22
J ..ME / K ''
FU'KD((GR% ) E  +G
 ##G,
r.   )	r  r  r   r  r  r  r  r  r   )r  )FFN)r%   r   r   r   r  r
   r   r   r   r	   r  r   r  classmethodr  r  r  r  r  r  r   r,   r.   r)   r  r    s`   :9J #'"&"&'+48,0"'04,1G 3-G 3-	G
 3-G e_G $,D>G d4j)G  G !)G &*G 
G./t / S [  :   	
 : $ # # 	#
 # #J ,D
8-r.   r  r   )Jrl   rr   loggingr   r"  r   rn   
contextlibr   r   r   r   r   typingr   r	   r
   r   r   	xml.etreer   r   xml.sax.saxutilsr   	cloudinitr   r   r   r   r   r   cloudinit.reportingr   cloudinit.sources.azurer   	getLoggerr%   r:   DEFAULT_WIRESERVER_ENDPOINTrB   rX   rd   rq   r$   r&   r   r-   rP   r[   r   rA   re   rx   r   r   r  r   intr   r   r   r   r{   r   r   r   r-  rV  r  r  r  r  r  r  r,   r.   r)   <module>r     s  
    	 	   % '  ; ; ' # J J & *! . "% $ $ ++	2  CL	hsAv&6 	8CF;K 	 R Rj  6 "	$* 

 

   
 !3	3 3 5/	3
 3 3 3 3l 14
DB B:D9 D< <~ D[E [E|b bJ  (,!	NN $s)$ c]	  s 3K  	 	P- P-r.   