U
    0hR                     @   s  d dl Z d dlZ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
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 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 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* d dl+m,Z,m-Z-m.Z.m/Z/ e0Z1dZ2dZ3e,e-e.dZ4ddddd Z5e6e7Z8d\d"d#Z9d]d$d%Z:d&d' Z;e<d(e8j=fe
e0gdf d)d*d+Z>d,d- Z?e$d.d/d0Z@d1d2 ZAd^d4d5ZBd_e	eCe0f d7d8d9ZDd:d; ZEd<d= ZFeee0eGf  e	eHe1f d>d?d@ZIeejJ e	eHe1f dAdBdCZKdDdE ZLdFdG ZMdHdI ZNdJdK ZOdLdM ZPejQdNdOdPZRdQdR ZSdSdT ZTd`dUdVZUdWdX ZVdYdZ ZWe7d[kreXeUejY dS )a    N)OptionalTupleCallableUnion)featuresnetinfo)signal_handler)sources)socket)stages)
url_helper)util)performance)version)warnings)	reporting)atomic_helper)	lifecycle)handlers)log_utilloggers)read_cfg_paths)cc_set_hostname)Modules)validate_cloudconfig_schema)log_with_downgradable_level)events)PER_INSTANCE
PER_ALWAYSPER_ONCECLOUD_CONFIGzOCloud-init v. {version} running '{action}' at {timestamp}. Up {uptime} seconds.zcloud_%s_modules)instancealwaysoncezLocal StagezNetwork StagezConfig StagezFinal Stage)
init-localinitmodules-configmodules-final c                 C   sV   | rt jd|   t jd t jd tjt jd t jd t jd d S )N%s
z<------------------------------------------------------------
)file)sysstderrwrite	traceback	print_excmsg r3   4/usr/lib/python3/dist-packages/cloudinit/cmd/main.pyr0   T   s    r0   c                 C   s&   |st | }tjd| ddtd |S )Nr)   FT)Zconsoler-   log)welcome_formatr   Z	multi_logLOG)actionr2   r3   r3   r4   welcome^   s    r9   c                 C   s   t jt t t | dS )N)r   uptimeZ	timestampr8   )WELCOME_MSG_TPLformatr   version_stringr   r:   Ztime_rfc2822r8   r3   r3   r4   r6   e   s    r6   Closing stdin)loggerc              	   C   sR   t tj sF| d tt j}t | tj  W 5 Q R X n| d dS )zj
    reopen stdin as /dev/null to ensure no side effects

    logger: a function for logging messages
    r?   z"Not closing stdin, stdin is a tty.N)osisattyr,   stdinfilenoopendevnulldup2)r@   fpr3   r3   r4   close_stdinn   s
    "rI   c                 C   sT   g }| j r*| j D ]}|tj|j q| jrP| jD ]}|tj|j q6|S N)
main_filesappendrA   pathrealpathnamefiles)argsZfn_cfgsZfhr3   r3   r4   extract_fns}   s    

rR   )modsc                 C   sv   t | }| |\}}t|t| }|dkrXd||f }tjd|  t| g S tdt|t| |S d S )Nr   z)No '%s' modules to run under section '%s'r)   zRan %s modules with %s failures)MOD_SECTION_TPLZrun_sectionlenr,   r-   r.   r7   debug)rS   action_nameZsectionZfull_section_name	which_ranfailuresZtotal_attemptedr2   r3   r3   r4   run_module_section   s"    
  rZ   c                 C   s   |  drt|  d d S )Nr   )getr   Zupdate_configuration)cfgr3   r3   r4   apply_reporting_cfg   s    
r]   cloud-config-urlurlc                 C   s@   t | }|D ]}||kr||| f  S qtd| |f d S )Nz!No keys (%s) found in string '%s')r   Zkeyval_str_to_dictKeyError)cmdlinenamesdatakeyr3   r3   r4   parse_cmdline_url   s
    
rf   T)returnc              
   C   s4  |dkrt  }zt|\}}W n tk
r>   tjdf Y S X |d}|rtj	| r|r|d| |f }tj
}|rtj}nd| |f }tj}||fS |dddd	}|s|rtj}d
|d< ntj}d|d< d}	d}
z tjf |}d}| rd}t|tjrHz|t|jt|
d7 }W n tk
r4   Y nX ||
sZd}n|j|
sZd}|r|dkrtjdddddW S n2|dkrtj}ntj
}|d| dt|
 fW S n|d||jf fW S ||j }	W n: tjk
r } z|d||f f W Y S d}~X Y nX t j| |	dd tj
d||| f fS )a  Write data from url referenced in command line to path.

    path: a file to write content to if downloaded.
    network: should network access be assumed.
    cmdline: the cmdline to parse for cloud-config-url.

    This is used in MAAS datasource, in "ephemeral" (read-only root)
    environment where the instance netboots to iscsi ro root.
    and the entity that controls the pxe config has to configure
    the maas datasource.

    An attempt is made on network urls even in local datasource
    for case of network set up in initramfs.

    Return value is a tuple of a logger function (logging.DEBUG)
    and a message indicating what happened.
    Nz!No kernel command line url found.)zfile:///z_file '%s' existed, possibly from local stage download of command line url '%s'. Not re-writing.zafile '%s' existed, possibly from previous boot download of command line url '%s'. Not re-writing.
      T)r`   ZtimeoutZretriesstream   Zsec_betweeng?s   #cloud-config    )Z
chunk_sizeFr`   z!The kernel command line key `url`z22.3zD Please use `cloud-config-url` kernel command line parameter instead
deprecateddeprecated_versionextra_messageZskip_logr_   zcontents of 'z' did not start with z$url '%s' returned code %s. Ignoring.zretrieving url '%s' failed: %si  )modez*wrote cloud-config data from %s='%s' to %s)r   Zget_cmdlinerf   ra   loggingDEBUG
startswithrA   rM   existsINFOWARNr   Zread_file_or_urlok
isinstanceZUrlResponsenextZiter_contentrU   StopIterationcontentsr   	deprecatestrcodeZUrlError
write_file)rM   networkrb   Zcmdline_namer`   Zpath_is_localmlevelkwargsrd   headerZrespZsniffed_contentZis_cloud_cfger3   r3   r4   attempt_cmdline_url   s    






&r   c                 C   s   dt jjt jjf }tj| jdd}tj	|rjt
|}||krtd | d t
|| n*tj	| jdrtd t
|| dS )	zPurge the cache if python version changed on us.

    There could be changes not represented in our cache (obj.pkl) after we
    upgrade to a new version of python, so at that point clear the cache
    z%d.%drd   zpython-versionz-Python version change detected. Purging cacheTZobj_pklzMWriting python-version file. Cache compatibility status is currently unknown.N)r,   version_infomajorminorrA   rM   joinpaths	get_cpathrv   r   load_text_filer7   rV   purge_cacher   get_ipath_curinfo)r%   Zcurrent_python_versionZpython_version_pathZcached_python_versionr3   r3   r4   $purge_cache_on_python_version_change  s&    
 


r   c                 C   s   t | jdrdS |j S )NZdisable_network_activationF)r   get_cfg_option_boolr\   local)r%   rQ   r3   r3   r4   _should_bring_up_interfaces:  s    r   )
raw_configrg   c              
   C   s  | sdS t |  dd dkr&dS zt| }W n> tk
rr } z ttdtj	d|fd W Y d	S d}~X Y nX t
|tsd
S d|kr|d D ]2}|dpi }|dd}|r|ds dS qdS |drdS |di drdS |d rdS dS )a  Determine if our cloud-config requires us to wait

    User data requires us to wait during cloud-init network phase if:
    - We have user data that is anything other than cloud-config
      - This can likely be further optimized in the future to include
        other user data types
    - cloud-config contains:
      - bootcmd
      - random_seed command
      - mounts
      - write_files with source
    )Fzno configuration foundN*   ztext/cloud-config)Tz non-cloud-config user data foundz24.4z'Unexpected failure parsing userdata: %s)r@   r   Zrequested_levelr2   rQ   )Tz!failed to parse user data as yaml)Tz(parsed config not in cloud-config formatZwrite_filessourceZurir(   )rh   zfile:)Tz!write_files with source uri found)Fz$write_files without source uri foundZbootcmd)Tzbootcmd foundZrandom_seedZcommand)Tzrandom_seed command foundZmounts)Tzmounts found)Fz8cloud-config does not contain network requiring elements)r   Ztype_from_starts_withstripyaml	safe_load	Exceptionr   r7   rs   WARNINGrz   dictr[   ru   )r   Zparsed_yamlr   itemZsource_dictZ
source_urir3   r3   r4   _should_wait_via_user_data@  sD    

r   )
datasourcerg   c                 C   s   | sdS t |  \}}|r*d| dfS t |  \}}|rLd| dfS t |  \}}|rnd| dfS dd| d| d	| fS )
zDetermine if we should wait on network connectivity for cloud-init.

    We need to wait during the cloud-init network phase if:
    - We have no datasource
    - We have user data that may require network access
    )Tzno datasource foundTz in user dataz in vendor dataz in vendor data2Fzuser data: z, vendor data: z, vendor data2: )r   Zget_userdata_rawZget_vendordata_rawZget_vendordata2_raw)r   Zuser_should_waitZuser_reasonZvendor_should_waitZvendor_reasonZvendor2_should_waitZvendor2_reasonr3   r3   r4   _should_wait_on_network|  s(    	r   c                    s  t jt jg}|jrt jg}ttjdt d|j dg |jrDdnd}t	|}t
j||jd}|t| d }d }z@|jst fdd t|j| \}}nt|j| \}}W n< tk
r   d	}tt| t|  tj|f Y nX |jrtd
 t  |js,t|j t |j t!| |d t"dt# |  D ]\}	}t$|	| qNz|%  W n" tk
r   ttd Y nX |j&}
t'| |jrt j(nt j)}|t j)krt*j+rtj,|j&-dstd |j./  d}t0j12dt34   nZd}t5|jdd}|r:td d}n(|
6d}tj,|rbtd| d}|7  t8||}zD|j9|d |t j)kr|j:j;|krtd||j: d g fW S W n t j<k
rH   |t j(krtd nttd |j=s8|j>|d td| |t j(kr(d g f Y S d dgf Y S ntd| Y nX t?| |@ }td || ||A  |t j(krtB|d!d"d# |j>|d |t j(kr$t*j+rtC|j:\}}|rtd$| n td%| tD|j&-dd& |j:j;|krtd'||j: |j:g fS td(||j: |E  |F  tB|d)d*d# z2|G jHd+|jItJgtJd,\}}|sr|ItK W n. tk
r   ttd- |j:d-gf Y S X |j&6d.}tj,|rtL|jMd/krtNtOPtQ|ddd0d1 n
td2 t |j tR|t||jd3}zR|}|}t|j| \}}||ksF||krftSd4|| t|j| \}}W n" tk
r   ttd5 Y nX t|j |T  tU|j:|jd6 |j:tV|| | fS )7Nz%s.dz91_kernel_cmdline_url.cfg)rM   r   r$   r%   Zds_depsreporterc                    s     tj| fS rJ   )rL   rs   rt   r1   Z
early_logsr3   r4   <lambda>  rm   zmain_init.<locals>.<lambda>#Failed to setup output redirection!@Logging being reset, this logger may no longer be active shortlyr1   !PID [%s] started cloud-init '%s'.z0Failed to initialize, likely bad things to come!z.skip-networkz4Will wait for network connectivity before continuingtrustr)   ZcheckZmanual_cache_cleanFz"manual cache clean set from configZmanual_clean_markerz(manual cache clean found from marker: %sexistingz)[%s] Exiting. datasource %s in local modezNo local datasource foundz8No instance datasource found! Likely bad things to come!)Zbring_upz[%s] Exiting without datasourcezNo instance datasource found.z2[%s] barreling on in force mode without datasourcez5[%s] %s will now be targeting instance id: %s. new=%sr   r   )stageretry_stagezTNetwork connectivity determined necessary for cloud-init's network stage. Reason: %szVNetwork connectivity determined unnecessary for cloud-init's network stage. Reason: %sr(   z.[%s] Exiting. datasource %s not in local mode.z6[%s] %s is in local mode, will apply init modules now.zinit-netzmodules:configconsume_data)rQ   ZfreqzConsuming user data failed!Zcloud_configr   T)configstrictZlog_detailsZlog_deprecationsz2Skipping user-data validation. No user-data found.r   z#Stdout, stderr changing to (%s, %s)z'Failed to re-adjust output redirection!)r   r\   )Wr	   ZDEP_FILESYSTEMZDEP_NETWORKr   r   rA   rM   r   r    r6   r   Initr   read_cfgrR   skip_log_setuprI   r   fixup_outputr\   Zget_output_cfgr   logexcr7   r0   rL   rs   rx   rV   r   reset_loggingsetup_loggingr]   r9   r   getppidr5   Z
initializer   r   ZDSMODE_LOCALZDSMODE_NETWORKr   ZMANUAL_NETWORK_WAITrv   get_runpathZdistroZwait_for_networkr,   r-   r.   r   Z
debug_infor   r   r   r   fetchr   ZdsmodeDataSourceNotFoundExceptionforceZapply_network_config_maybe_persist_instance_dataZ
instancifyZis_new_instance_maybe_set_hostnamer   r   Zsetup_datasourceupdatecloudifyrunr   r   r   statst_sizer   r   r   r   r   warningZactivate_datasourcedi_report_warnrZ   )rO   rQ   Zdepsbootstage_namew_msgr%   ZoutfmtZerrfmtr2   ZlvlZpath_helperrr   r   ZmcfgZmfileZbring_up_interfacesZiidZshould_waitreasonZranZ_resultsZcloud_cfg_pathrS   Zoutfmt_origZerrfmt_origr3   r   r4   	main_init  sN    






  


 

r   c                 C   s   d|krt d d S |d }|d kr4t d d S t|tsNt d| d S |d}|d krnt d d S t|tst d| d S | jdd	 }|	t
jr|tt
jd  }nt d
| | ||krt d| || d S tjd||t|d d S )NZ	di_reportzno di_report found in config.zdi_report was None.z%di_report config not a dictionary: %sZdatasource_listz(no 'datasource_list' found in di_report.z(di_report/datasource_list not a list: %s.rj   z1Datasource '%s' came from unexpected module '%s'.z:used datasource '%s' from '%s' was in di_report's list: %sZdsid_missing_source)r   dslist)r7   rV   rz   r   r   r[   list
__module__
rpartitionru   r	   Z	DS_PREFIXrU   r   Zshow_warningr   )r   r\   Zdicfgr   modnamer3   r3   r4   r     sN    





   r   c                 C   sd  |j }d| |f }t|}tjg |jd}|t| z|jdd W nB tj	k
r   d| }t
t| t| |js|g Y S Y nX t| t|t||jd}z|jst  t
|j| W n  tk
r   t
td Y nX |jrtd t  |js t|j t|j t||d	 td
t | |dkrXtj dddd t!|||S )Nz%s:%sr   r   r   zGCan not apply stage %s, no datasource found! Likely bad things to come!r   r   r   r1   r   r%   z`--mode init`24.1Use `cloud-init init` instead.)ro   rp   rq   )"rr   r6   r   r   r   r   rR   r   r	   r   r   r   r7   r0   r   r   r   r   rI   r   r\   r   rV   r   r   r   r]   r9   r   rA   r   r   r~   rZ   )rW   rQ   rO   r   r   r%   r2   rS   r3   r3   r4   main_modules  sR    

r   c           
      C   s  |j }t| }tjg |jd}|t| z|jdd W n6 tj	k
rr   t
td td |jsnY dS Y nX t| t|t||jd}|j}|rtd| |j}|rtd| t|}zt  t
|jd  W n  tk
r   t
td	 Y nX |jrtd
 t  t|j t|j t| |d ||||\}}	|	rdt d| dS |szt d| dS dS d S )Nr   r   r   z;Failed to fetch your datasource, likely bad things to come!rl   r   zUsing passed in arguments %szUsing passed in frequency %sr   r   r1   zRan %s but it failed!zDid not run %s, does it exist?r   )!rO   r6   r   r   r   r   rR   r   r	   r   r   r   r7   r0   r   r   r   module_argsrV   Z	frequencyFREQ_SHORT_NAMESr[   rI   r   r\   r   r   r   r   r]   r9   Z
run_singler   )
rO   rQ   mod_namer   r%   rS   Zmod_argsZmod_freqrX   rY   r3   r3   r4   main_single  s\    	 

r   c                 C   s:  t  }|d}tj|j}tj|d}tj|d}tj|d}tj|d}t }	t	
||f |j\}
}| dkr|jrd}qd}n | dkrd|j }ntd|  |tkrtd	|g i d d d
}dd | | | | di}|dkr"||||fD ]}t	| qn,ztt	|}W n tk
rL   Y nX ||d krl| |d |< |d }||d< || d r|| d stdt|  tt	 || d< ttdd |	j}| }t || t	j!tj"|||dd zzX|| |}|dkr8|\}}|d k	r<t'||d< n|}|| d (dd |D  W n tk
r } z2t)d| t*d|  || d +t'| W 5 d }~X Y nd t,k
r } zD|j-rt)d| t*d|  || d +dt'|j- d W 5 d }~X Y nX W 5 tt	 || d< d |d< | }|#  |$ D ]J}||kr|t%t&|| ||  || d |< n|| || d |< qHt || X |dkr*g }|$ D ]<}t.|| t/r|| 0dr|(|| 0dg  qt |d|d |d i t	j!tj"|||dd t1|| d S )!Nrd   zstatus.jsonzresult.jsonr%   r$   modules
modules-%szunknown name: %sz'Invalid cloud init mode specified '{0}')errorsrecoverable_errorsstartfinishedv1)r   r%   r$   r&   r'   r   r   r   z=Unexpected start time found for %s. Was this stage restarted?c                 S   s   t | tjS rJ   )rz   r   ZLogExporter)hr3   r3   r4   r     rm   z status_wrapper.<locals>.<lambda>T)r   r   )r%   r$   r   r   c                 S   s   g | ]}t |qS r3   )r   ).0r   r3   r3   r4   
<listcomp>  s     z"status_wrapper.<locals>.<listcomp>zfailed stage %szfailed run of stage %sz	sys.exit(z) calledr'   )r   r   )2r   r   rA   rM   normpathZrun_dirr   rs   	getLoggerr   Zensure_dirsr8   r   rr   
ValueError
STAGE_NAMEr<   copyZdel_filejsonloadsr   r   r7   r   floatr:   r{   filterr   Zexport_logsr   Z
write_jsonZsym_linkrelpathZ
clean_logskeysr   setr   extendZ	exceptionr0   rL   
SystemExitr   rz   r   r[   rU   )rO   rQ   r   Zdata_dZlink_dZstatus_pathZstatus_linkZresult_pathZresult_linkZroot_logger_namefunctorrr   Z
nullstatusstatusfr   ZhandlerZpreexisting_recoverable_errorsZnew_recoverable_errorsre   Zretr   r   r   r   r3   r3   r4   status_wrapperR  s    

	
   


 &6

   r   )r%   c                 C   s6   | j r2| jr2| jd}tj|s2| j jdd dS )zCWrite instance-data.json file if absent and datasource is restored.Zinstance_dataF)Zwrite_cacheN)r   Zds_restoredr   r   rA   rM   rv   Zpersist_instance_data)r%   Zinstance_data_filer3   r3   r4   r     s    r   c              
   C   sx   |   }tj| j|dd\}}}|rtztd| j|d W n8 tjk
rr } ztd||t	| W 5 d}~X Y nX dS )zCall set_hostname if metadata, vendordata or userdata provides it.

    @param stage: String representing current stage in which we are running.
    @param retry_stage: String represented logs upon error setting hostname.
    T)Zmetadata_onlyZset_hostnameNzGFailed setting hostname in %s stage. Will retry in %s stage. Error: %s.)
r   r   Zget_hostname_fqdnr\   r   ZhandleZSetHostnameErrorr7   rV   r   )r%   r   r   ZcloudZhostnameZ_fqdn_r   r3   r3   r4   r     s       r   c                 C   s    t jdttjd  d S )Nr*   )r,   stdoutr.   r   sortedr   ZFEATURES)rO   rQ   r3   r3   r4   main_features  s    r   c              	   C   s  t   | stj} tj| dd}|jddddt	  dd |jd	d
dddd |jdddddt
dd |jdddddd |jdddddd |jd d |jdd d!}|jd"d#d$}|jd%d&dd'dd |jdddd(d)t
dd |jd"tfd* |jd+d,d$}tjd-d.d/d0d1j}|jd2d3d4d5| d6d7d8 |jdddd(d)t
dd |jd+tfd* |jd9d:d$}|jd;d<d4d=d0d> |jd?d4d@dtt dA |jdBddCdd> |jdDdEdFdGdH |jdddd(d)t
dd |jd9tfd* |jdIdJd$}|jdKdLd$}|jdKtfd* |jdMdNd$}	|jdOdPd$}
|jdQdRd$}|jdSdTd$}|jdUdVd$}|jdWdXd$}| rtdYdZ | D d }|dMkrdd[lm} ||	 q|dOkrdd[lm} ||
 q|dQkrdd\lm}m} ||d] |jdQ|fd* n|dSkr@dd^lm}m} || |jdS|fd* n|dIkrtdd_l m}m!} || |jd`|fd* nf|dWkrddal"m}m#} || |jdW|fd* n2|dUkrddbl$m}m%} || |jdU|fd* n
|&dc |j'| dd}t(|ded |j)st*|S t)|S )fNr   )progz	--versionz-vr   z	%(prog)s z'Show program's version number and exit.)r8   r   helpz--debugz-d
store_truez:Show additional pre-action logging (default: %(default)s).F)r8   r   defaultz--filez-frL   rK   zPUse additional yaml configuration files for subcommands: init, modules or singlerb)r8   destr   typez--forcezDForce running even if no datasource is found (use at your own risk).r   )r8   r   r   r   z--all-stages
all_stageszsRun cloud-init's stages under a single process using a syncronization protocol. This is not intended for CLI usage.)r   r8   r   r   r   ZSubcommands
subcommand)titler   r%   z2Initialize cloud-init and perform initial modules.)r   --localz-lz+Start in local mode (default: %(default)s).rP   z(Use additional yaml configuration files.r>   r   z1Activate modules using a given configuration key.z`init`r   r   Trn   z--modez-mZstorez9Module configuration name to use (default: %(default)s). r   )r%   r   final)r8   r   r   choicessinglezRun a single module.z--namez-nzModule name to run.)r8   r   requiredz--frequencyzModule frequency for this run.)r8   r   r	  r  z--reportzEnable reporting.r   *Zargumentz0Any additional arguments to pass to this module.)nargsmetavarr   Zqueryz;Query standardized instance metadata from the command line.r   zList defined features.Zanalyzez-Devel tool: Analyze cloud-init logs and data.ZdevelzRun development tools.zcollect-logsz*Collect and tar all cloud-init debug info.Zcleanz3Remove logs and artifacts so cloud-init can re-run.r   z/Report cloud-init status or wait on completion.Zschemaz-Validate cloud-config files using jsonschema.c                 s   s   | ]}| d s|V  qdS )-N)ru   )r   Zposargr3   r3   r4   	<genexpr>  s     
 zmain.<locals>.<genexpr>)
get_parser)r  handle_collect_logs_args)parser)r  handle_clean_args)r  handle_argsZrender)r  handle_schema_args)r  handle_status_argsza subcommand is requiredrQ   r   )+r   Zconfigure_root_loggerr,   argvargparseArgumentParserpopadd_argumentr   r=   ZFileTypeZset_defaultsZadd_subparsersZ
add_parserr   r   r~   messager   r   r   r   r   r   r{   Zcloudinit.analyzer  Zcloudinit.cmd.devel.parserZcloudinit.cmd.devel.logsr  Zcloudinit.cmd.cleanr  Zcloudinit.cmd.queryr  cloudinit.config.schemar  Zcloudinit.cmd.statusr  error
parse_argssetattrr  sub_main)Z	sysv_argsr  Z
subparsersZparser_initZ
parser_modZ
extra_helpZparser_singleZparser_queryZparser_featuresZparser_analyzeZparser_develZparser_collect_logsZparser_cleanZparser_statusZparser_schemar  Zanalyze_parserZdevel_parserZlogs_parserr  Zclean_parserr  Zquery_parserZhandle_query_argsZschema_parserr  Zstatus_parserr  rQ   r3   r3   r4   main  s   
 
  
       








r"  c              	   C   sJ  t d tdddd}td |d& | jddgd	}d
|_t||_W 5 Q R X |d$ | jdgd	}d|_t||_W 5 Q R X |d& | jddgd	}d|_t||_W 5 Q R X |d& | jddgd	}d|_t||_W 5 Q R X |j	r2d}|j
rd|j
 }td| d td dS td td dS )z>Run all stages in a single process using an ordering protocol.z*Running cloud-init in single process mode.r   r   r   r  zREADY=1r%   r  r  FTr   z--mode=configz--mode=finalz%a stage of cloud-init exited non-zerozfirst exception received: zSTATUS=Completed with failure, z2. Run 'cloud-init status --long' for more details.z
STOPPING=1rl   zSTATUS=CompletedN)r7   r   r
   Z
SocketSyncZ	sd_notifyr  r   r!  Zsystemd_exit_codeZexperienced_any_errorZfirst_exception)r  syncrQ   r  r3   r3   r4   r    s<    








r  c              
   C   sV  | j \}}|dkr,t| jr"tjntj n| jr:t  t  d|ks\d|kr`d| j	kr`t
}d }d}|dkr| jrd\}}qd\}}nV|dkrd| j	 d| j	  }}n6|d	krd
| j d| j  }}| j}n|}d| }d}tj|||d| _| j. td| d ||| }W 5 Q R X W 5 Q R X t  d|krRd| j	krRt|}|S )N)r%   r   r%   r   T)r$   zsearching for local datasources)zinit-networkz!searching for network datasourcesr   zrunning modules for %sr  z	single/%szrunning single module %szrunning 'cloud-init %s'F)Zreporting_enabledzcloud-init stage: '')r8   r   Zsetup_basic_loggingrV   rs   rt   r   r   Zattach_handlersrr   r   r   rO   reportr   ZReportEventStackr   r   ZTimedr   Zflush_eventsrU   )rQ   rO   r   ZrnameZ	report_onZrdescZretvalr3   r3   r4   r!  H  sP    


  r!  __main__)r(   )N)r^   )TN)N)Zr  r   rA   r,   r/   rs   r   typingr   r   r   r   Z	cloudinitr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   Zcloudinit.logr   r   Zcloudinit.cmd.develr   Zcloudinit.configr   Zcloudinit.config.modulesr   r  r   Zcloudinit.lifecycler   Zcloudinit.reportingr   Zcloudinit.settingsr   r   r   r    r   ZReasonr;   rT   r   r   r   __name__r7   r0   r9   r6   ZtimedrV   rI   rR   rZ   r]   rf   intr   r   r   bytesboolr   Z
DataSourcer   r   r   r   r   r   r   r   r   r   r"  r  r!  exitr  r3   r3   r3   r4   <module>   s   



	 
m
=
% y2AF 
 ~;E
