
    x[hO                        d dl Z d dlZd dlZd dlZd dlZd dlmZmZmZ ddl	m
Z
 ddlmZmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ  e j4                  e      ZdZdZdZdZ dZ!dZ"d Z#d3dZ$d Z%d Z&d Z'd Z(d Z)d Z*d Z+d Z,	 d4dZ-d Z.d Z/d Z0d  Z1d! Z2	 d5d"Z3d# Z4d$ Z5d% Z6d& Z7d' Z8d( Z9d) Z:d* Z;d+ Z<d, Z=d- Z>d. Z?d/ Z@d0 ZAd1 ZBd2 ZCy)6    N)performancesubputil   )Config)PostCustomScriptPreCustomScript)
ConfigFile)NicConfigurator)PasswordConfigurator)GuestCustErrorEnum)GuestCustEventEnum)GuestCustStateEnumz/var/log/cloud-init.logqueryNicsSupported	connected/var/run/vmware-imc	deployPkgzenable-custom-scriptsc                 *   | sy d}d}	 t         j                  d|        t        j                  d| gdg      \  }}|r|j                         }||fS # t        $ r7}t         j                  d       t         j                  |       Y d }~||fS d }~ww xY w)N zError sending the RPC commandzSending RPC command: %szvmware-rpctoolr   )rcszFailed to send RPC command)loggerdebugr   rstrip	Exception	exception)rpcouterres       U/usr/lib/python3/dist-packages/cloudinit/sources/helpers/vmware/imc/guestcust_util.pysend_rpcr!   ,   s    
C
)C.4YY 0#6QC@
c**,C
 :	  12:	s   AA 	B*BBc                 d    d}|rt         dz   |z   }nt         }d| ||fz  }t        |      \  }}||fS )Nr   @zdeployPkg.update.state %d %d %s)CLOUDINIT_LOG_FILEr!   )	custstate	custerrorerrormessagemessager   r   r   s          r    set_customization_statusr)   B   sF    G$s*\9$
+y)W.M
MC#JS#:    c                    | syd}t         j                  j                  |       syt        j                  d|        5  t        | d      5 }|j                  |      }ddd       ddd       S # 1 sw Y   xY w# 1 sw Y   S xY w)zReads the NICS from the specified file path and returns the content

    @param nicsfilepath: Absolute file path to the NICS.txt file.
    Ni   zReading r)ospathexistsr   Timedopenread)nicsfilepath	NICS_SIZEfpnicss       r    get_nics_to_enabler7   O   s     I77>>,'			Xl^4	5 "tc8 "	wwy!" "
 K" " "
 Ks#   A;A/A;/A8	4A;;Bc                 p   | st         j                  d       y d}d}d}t        |      D ]  }t         j                  d|       t	        t
        j                  t        j                  |       \  }}|st        j                  ||z         `|t        k7  rt         j                  d        y t        |      D ]g  }t	        t
        j                  t        j                  |       \  }}|r"|t        k(  rt         j                  d|         y t        j                  |       i  t         j                  d|       y )NzNo Nics found   r   z(Trying to connect interfaces, attempt %dz-NICS connection status query is not supportedzNICS are connected on %d secondz2Can't connect network interfaces after %d attempts)r   warningranger   r)   r   GUESTCUST_STATE_RUNNINGr   GUESTCUST_EVENT_ENABLE_NICStimesleepQUERY_NICS_SUPPORTEDGUESTCUST_EVENT_QUERY_NICSNICS_STATUS_CONNECTEDinfo)r6   enableNicsWaitRetriesenableNicsWaitCountenableNicsWaitSecondsattemptr   _errcounts           r    enable_nicsrJ   f   s   './ .?I.66::
d
 JJ*-BBC&&NNJK./ 
	.E2"::"==KS$
 s33=uEJJ,-
	..6 NN<r*   c                    t        j                  d      st        j                  d       |S ddd| |g}	 t        j                   |      }|}t        j                  d
|j                        }|r9|j                  d      j                         }t        j                  d| ||       |S t        j                  d| ||       |S # t         j                  $ rx}|j
                  dk(  r't        j                  ddj                  |      |       n6t        j                  d||j
                         t        j                  |       |cY d	}~S d	}~ww xY w)a$  Return the value of [section] key from VMTools configuration.

    @param section: String of section to read from VMTools config
    @returns: String value from key in [section] or defaultVal if
              [section] is not present or vmware-toolbox-cmd is
              not installed.
    zvmware-toolbox-cmdz9vmware-toolbox-cmd not installed, returning default valueconfiggetE   zRvmware-toolbox-cmd returned 69 (unavailable) for cmd: %s. Return default value: %s zFailed running %s[%s]Nz([^=]+)=(.*)   zGet tools config: [%s] %s = %sz<Tools config: [%s] %s is not found, return default value: %s)r   whichr   r   ProcessExecutionError	exit_codejoinerrorr   rematchstdoutgroupstrip)sectionkey
defaultValcmdr   r   retValuems           r    get_tools_configra      s'    ::*+G	
 5'3
?Ciin H
#**-A771:##%5wXN O 	J		
 O5 %% ;;"LL,	 LL0#q{{CQs   C EA-EEEc                 @    | r| j                   rd|z  }t        |      S y )Nzinfo-set guestinfo.gc.status %s)post_gc_statusr!   )rL   gcMsgr   s      r    set_gc_statusre      s$    &''/%7}r*   c                      t         S N)IMC_DIR_PATH r*   r    get_imc_dir_pathrj      s    r*   c                    i d d i f\  }}}}t        |d       t        |      \  }}t        | |      }	|	rt        ||||      syt	        | |      sy	 t
        j                  d       t        |dd|j                        |d<   t        |       t        t         j"                  t$        j&                         t        |d       ||||fS # t        $ r/}
t        dt        |
      t        j                  |       Y d }
~
yd }
~
ww xY w)NStarted)NNNNz#Preparing the Network configurationTnetworkz%Error preparing Network Configuration
Successful)re   )get_non_network_data_from_vmware_cust_cfgcheck_markersdo_special_customizationrecheck_markersr   r   %get_network_data_from_vmware_cust_cfgosfamilyr   set_cust_error_statusstrr   $GUESTCUST_EVENT_NETWORK_SETUP_FAILEDconnect_nicsr)   r   GUESTCUST_STATE_DONEr   GUESTCUST_ERROR_SUCCESS)	cloud_dirscripts_cpathcust_cfgcust_cfg_dirdistromdudvdcfgis_special_customizationr   s              r    get_data_from_imc_cust_cfgr      s    $b(OBB(I&9(CIR,YA'8\6
 ,9h/'(:;=dD&//
9 //22 (L)B  (3FCC		
 ((s   0C 	C>%C99C>c                    t        | d       d\  }}}| j                  }|rCt        j                  j	                  t               |      }t        j                  j                  |      s t        dd|z  t        j                  |        y	 t        j                  |      }	 t        j                  d       t!        j"                  |      }| j*                  }|rt        j                  j	                  t               |      }t        j                  j                  |      s t        dd	|z  t        j                  |        y	 t        j                  |      j-                  d
d      }t/        t0        j2                  t&        j4                         t        | d       |||fS # t        $ r/}t        dt        |      t        j                  |        Y d }~yd }~ww xY w# t         j$                  $ r0}t        dt        |      t&        j(                  |        Y d }~Md }~ww xY w# t        $ r/}t        dt        |      t        j                  |        Y d }~yd }~ww xY w)Nrl   )NNNz,Error locating the cloud-init meta data filezMeta data file is not found: %sz'Error loading cloud-init meta data filez'Validating if meta data is valid or notz&Error parsing the cloud-init meta dataz+Error locating the cloud-init userdata filezUserdata file is not found: %sr   z&Error loading cloud-init userdata filern   )re   meta_data_namer-   r.   rT   rj   r/   ru   r    GUESTCUST_EVENT_CUSTOMIZE_FAILEDr   load_text_filer   rv   r   r   yaml	safe_load	YAMLErrorr   !GUESTCUST_ERROR_WRONG_META_FORMATuser_data_namereplacer)   r   ry   rz   )	r}   r   r   r   md_filemd_pathr   ud_fileud_paths	            r    #get_data_from_imc_raw_data_cust_cfgr      s   (I&!JBB%%G'',,/17;ww~~g&!>1G;"CC	 &		&$$W-B		LLBC#B ))ggll#3#5w?G77>>'*%A4w>&GG	 *	*((199$C //22 (L)B<_  	&!9A"CC	 &	& ~~ 	!8A"DD	 	*  *%<F&GG	 **sH   
F  *G  %H 	G'%GGH,%HH	I(%IIc                    i i }}| j                   r;| j                  r | j                   dz   | j                  z   |d<   n| j                   |d<   | j                  r| j                  |d<   | j                  r| j                  |d<   ||fS )N.zlocal-hostnametimezonezinstance-id)	host_namedomain_namer   instance_id)r}   r   r   s      r    ro   ro   7  s    "B""S(8+?+??   $,#5#5B "++J$00=9r*   c                     t        | j                  | j                  | j                  |      }|j	                  ||      }t        |      S rg   )r   r6   name_serversdns_suffixesgenerategen_v2_network_config)r}   use_system_devices	configurert   nicConfiguratorethernets_dicts         r    rs   rs   G  sI     &	O %--iBN 00r*   c                     d| dS )NrP   )version	ethernetsri   )r   s    r    r   r   U  s    ~66r*   c                     t         j                  j                  | d      }t         j                  j                  |      r+t        j                  d|       t        t        |             y y )Nznics.txtz%s file found, to connect nics)r-   r.   rT   r/   r   r   rJ   r7   )r~   	nics_files     r    rx   rx   Y  sH    \:6I	ww~~i 5yA&y12 !r*   c                 2    t        j                  | dd       S )Ndisable_vmware_customizationTr   get_cfg_option_bool)sys_cfgs    r    is_vmware_cust_enabledr   `  s"    ''/  r*   c                 0    t        j                  | dd      S )Nallow_raw_dataTr   )ds_cfgs    r    is_raw_data_cust_enabledr   f  s    ##F,<dCCr*   c                     t        |       }t        j                  d      5  t        d|      }d d d        rt        j                  d|       |S t        j                  d       y # 1 sw Y   9xY w)N3Waiting for VMware customization configuration filezcust.cfgz3Found VMware customization configuration file at %sz0No VMware customization configuration file found)get_max_wait_from_cfgr   r0   wait_for_cust_cfg_filer   r   )r   max_waitcust_cfg_file_paths      r    get_cust_cfg_filer   j  sv     %V,H			=
 J 4JIJ A	
 "!GHJ Js   A&&A/c                    d}||k  rd}||k  rvt         j                  j                  ||       }t         j                  j                  |      r|S t        j                  d       t        j                  |       ||z  }||k  rvy )Nr   r   r   )r-   r.   rT   isfiler   r   r>   r?   )filenamemaxwaitnaplendirpathwaitedfileFullPaths         r    r   r     sz     F&
7
ww||GX677>>,'JK

6& 7
 r*   c                     d}d}|}| s|S 	 t        | j                  ||            }|dk  rt        j	                  d|||       |}|S # t        $ r t        j	                  d||       Y Cw xY w)N   vmware_cust_file_max_waitzFailed to get '%s', using %sr   z/Invalid value '%s' for '%s', using '%s' instead)intrM   
ValueErrorr   r:   )r   default_max_waitmax_wait_cfg_optionr   s       r    r   r     s    5H
vzz"57GHI !|=		
 $O  
*	

s   A  A+*A+c                 |    |j                   }t        |t        j                  j	                  | d            }|xr | S )Ndata)	marker_idcheck_marker_existsr-   r.   rT   )r{   r}   product_markerhas_marker_files       r    rp   rp     s;    ''N)Y7O 1/11r*   c                     | syt         j                  j                  |d| z   dz         }t         j                  j                  |      ryy)ag  
    Check the existence of a marker file.
    Presence of marker file determines whether a certain code path is to be
    executed. It is needed for partial guest customization in VMware.
    @param markerid: is an unique string representing a particular product
                     marker.
    @param: marker_dir: The directory in which markers exist.
    F.markerfile-.txtT)r-   r.   rT   r/   )markerid
marker_dir
markerfiles      r    r   r     s>     j.8*Cf*LMJ	ww~~j!r*   c                 :    |j                   }|rt        | |      syy)NFT)r   create_marker_file)r{   r}   r   s      r    rr   rr     s     ''N!)X6r*   c                     	 t        |j                  t        j                  j	                  | d             y# t
        $ r/}t        dt        |      t        j                  |       Y d }~yd }~ww xY w)Nr   zError creating marker filesFT)
setup_marker_filesr   r-   r.   rT   r   ru   rv   r   r   )r{   r}   r   s      r    r   r     s`    	8--rww||Iv/NO   )F??		
 s   47 	A/ %A**A/c                 l   t         j                  d       t        j                  j	                  |d| z   dz         }t        j
                  |      D ]G  }|j                  d      st        j                  t        j                  j	                  ||             I t        |d      j                          y)a#  
    Create a new marker file.
    Marker files are unique to a full customization workflow in VMware
    environment.
    @param marker_id: is an unique string representing a particular product
                      marker.
    @param: marker_dir: The directory in which markers exist.
    zHandle marker creationr   r   z.markerfilewN)r   r   r-   r.   rT   listdir
startswithr   del_filer1   close)r   r   marker_filefnames       r    r   r     s     LL)*'',,z>I+E+NOKJ' ;M*MM"'',,z59:; 	c  "r*   c                     d}d}d}d}|j                   }|rt        |      }|rt        |||      }t        ||      }|r0|r.t        j
                  j                  | d      }	t        ||||	      }|r
|xr |xr |S |S )NFzper-instance)custom_script_namecheck_custom_script_enablementdo_pre_custom_scriptdo_password_customizationr-   r.   rT   do_post_custom_script)
r|   r}   r~   r   is_pre_custom_successfulis_password_custom_successfulis_post_custom_successfulis_custom_script_enabledcustom_scriptccScriptsDirs
             r    rq   rq     s    $$)! %$//M#A(#K #';-($ %>h$O!1ww||M>B$9m\<%
! $ *-*)	

 )(r*   c                     	 t        ||      }|j                          y# t        $ r/}t        dt	        |      t
        j                  |        Y d }~yd }~ww xY w)Nz(Error executing pre-customization scriptFT)r	   executer   ru   rv   r   r   )r}   r   r~   precustr   s        r    r   r     sW    
!->   6F??		
 s    	A%AAc                     	 t        |||      }|j                          y# t        $ r/}t        dt	        |      t
        j                  |        Y d }~yd }~ww xY w)Nz)Error executing post-customization scriptFT)r   r   r   ru   rv   r   r   )r}   r   r~   r   postcustr   s         r    r   r     s[    
#M<N   7F??		
 s     	A%AAc                     d}d}| j                   rt        j                  d       d}t        t        t
        |      }|j                         dk7  rt        ddt        j                  |        |S d}|S )NFfalsez=Set default value to true due to customization configuration.truez-Custom script is disabled by VM Administratorz'Error checking custom script enablementT)
default_run_post_scriptr   r   ra   IMC_TOOLS_CONF_GROUPNAME"IMC_TOOLS_CONF_ENABLE_CUST_SCRIPTSlowerru   r   GUESTCUST_ERROR_SCRIPT_DISABLED)r}   r   default_valuecustom_script_enablements       r    r   r   $  s    $M''K	
 / * 
  %%'61;5>>		
 $# $( ##r*   c                 F   t         j                  d       t               }| j                  }	 | j                  }|s|r|j                  |||       yt         j                  d       	 y# t        $ r/}t        dt        |      t        j                  |        Y d }~yd }~ww xY w)NzApplying password customizationzChanging password is not neededz%Error applying password configurationFT)r   r   r   admin_passwordreset_passwordr   r   ru   rv   r   r   )r}   r   pwdConfigurator	admin_pwd	reset_pwdr   s         r    r   r   =  s    
LL23*,O''I++		%%iFC  LL:;   3F??		
 s   #A( A( (	B 1%BB c                 *    t        t        |             S rg   )r   r
   )cfg_files    r    parse_cust_cfgr  R  s    *X&''r*   c                     d\  }}| j                   rd}t        j                  d       ||fS d}t        j                  d       ||fS )N)FFTz!raw cloudinit data cust cfg foundzvmware cust cfg found)r   r   r   )r}   is_vmware_cust_cfgis_raw_data_cust_cfgs      r    get_cust_cfg_typer	  V  sY    /;,,#89  455 ",- 455r*   c                  f    d} d}| D ](  }t        ||      }|st        j                  d|        y y)N)z/usr/lib/vmware-toolsz/usr/lib64/vmware-toolsz/usr/lib/open-vm-toolsz/usr/lib64/open-vm-toolsz'/usr/lib/x86_64-linux-gnu/open-vm-toolsz(/usr/lib/aarch64-linux-gnu/open-vm-toolsz%/usr/lib/i386-linux-gnu/open-vm-toolszlibdeployPkgPlugin.soz$Found the customization plugin at %sTF)search_filer   r   )search_pathscust_pluginr.   cust_plugin_paths       r    is_cust_plugin_availabler  a  sK    L *K &t[9LL68H  r*   c                     | r|sy t        j                  |       D ],  \  }}}||v st         j                  j                  ||      c S  y rg   )r-   walkr.   rT   )r   r   root_dirsfiless        r    r  r  v  sK    ( ggg. 0eUu77<<h//0 r*   c                     t        j                  t        d| |       t        t        j
                  |       t        ||        y)zS
    Set customization status to the underlying VMware Virtualization Platform
    z%s: %sN)r   logexcr   r)   r   r<   re   )prefixrU   eventr}   s       r    ru   ru     s1     	KK&%0/GGO(F#r*   rg   )TFN)   r9   r   )Dloggingr-   rV   r>   r   	cloudinitr   r   r   rL   r   config_custom_scriptr   r	   config_filer
   
config_nicr   config_passwdr   guestcust_errorr   guestcust_eventr   guestcust_stater   	getLogger__name__r   r$   r@   rB   rh   r   r   r!   r)   r7   rJ   ra   re   rj   r   r   ro   rs   r   rx   r   r   r   r   r   rp   r   rr   r   r   rq   r   r   r   r   r  r	  r  r  ru   ri   r*   r    <module>r%     s"    	 	   - -  C # ' / / / /			8	$ / + # $& %< "
,
.'T-d%P?D" BF173D0 .C"22"#")6$2*(6*$r*   