
    d                     r   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Zd dlZd dl	m	Z	 d dl
mc mZ d dlmc mZ d dlmZ d dl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mZmZmZm Z m!Z! d d	l"m#Z#m$Z$ d d
l%m&Z&m'Z'm(Z(m)Z)m*Z* d dl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 d dl3m4Z4 dZ5da6dZ7dZ8dZ9dZ:dZ;dZ<dZ=dZ> ej~                  d      Z@d ZA G d d      ZBdZCeBj                  eBj                  eBj                  eBj                  gZH G d deI      ZJ eJ       ZKeBj                  gZMd ZNd ZOd  ZPd! ZQd" ZRd9d$ZS G d% d&eI      ZT G d' d(eI      ZU eU       ZVd) ZWd* ZXd:d,ZYd;d-ZZdeVfd.Z[eVfd/Z\e.eBj                  d#d  e^e,      d+d#eVfd0Z_deVfd1Z`eBj                  d#d  e^e,      d+d#deVfd2Zad3 Zbd4 Zcd5 Zdd6 Zed7 Zfd8 Zgy)<    N)datetime)AgentGlobals)
EventErrorOSUtilError)ustr)get_propertiesset_properties)
get_osutil)TelemetryEventParamTelemetryEventCommonTelemetryEventSchemaGuestAgentGenericLogsSchemaGuestAgentExtensionEventsSchema!GuestAgentPerfCounterEventsSchema)fileutiltextutil)	parse_docfindallfind	getattribstr_to_encoded_ustr)CURRENT_VERSIONCURRENT_AGENT
AGENT_NAMEDISTRO_NAMEDISTRO_VERSIONDISTRO_CODE_NAMEAGENT_EXECUTION_MODE)get_imds_clienteventsz2Event: name={0}, op={1}, message={2}, duration={3}z$69B669B9-4AF8-4C50-BDC4-6006FA76E975      z$FFF0196F-EE4C-4EAF-9AA5-776F622DEB4F   F  z.waagent.tldz!(?P<agent_event>\.waagent)?\.tld$c                      t         S N)SEND_LOGS_TO_TELEMETRY     >/usr/lib/python3/dist-packages/azurelinuxagent/common/event.pysend_logs_to_telemetryr+   @   s    !!r)   c                       e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&d%Z'd&Z(d'Z)d(Z*d)Z+d*Z,d+Z-d,Z.d-Z/d.Z0d/Z1d0Z2d1Z3d2Z4d3Z5d4Z6d5Z7d6Z8d7Z9d8Z:d9Z;d:Z<d;Z=d<Z>d=Z?y>)?WALAEventOperationActivateResourceDiskAgentBlacklistedAgentEnabledAgentMemoryAgentUpgradeArtifactsProfileBlobCGroupsCleanUpCGroupsDisabledCGroupsInfoCollectEventErrorsCollectEventUnicodeErrorsConfigurationChange
CustomDataDefaultChannelChangeDeployDisable	DowngradeDownloadEnableExtensionProcessing!ExtensionTelemetryEventProcessingFetchGoalStateFirewall	GoalStateGoalStateUnsupportedFeaturesHealthCheckHealthObservation	HeartBeat
HostPluginHostPluginHeartbeatHostPluginHeartbeatExtended
HttpErrorsHttpGetImdsHeartbeatInstallInitializeHostPluginLogLogCollectionOSInfo	PartitionPersistFirewallRulesPluginSettingsVersionMismatchInvalidExtensionConfig	ProvisionProvisionGuestAgentRemoteAccessHandlingReportEventErrorsReportEventUnicodeErrorsReportStatusReportStatusExtendedRestartSequenceNumberMismatchSetCGroupsLimits
SkipUpdateStatusProcessingUnhandledError	UnInstallUnknownUpdate
VmSettingsVmSettingsSummaryN)@__name__
__module____qualname__r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   r(   r)   r*   r-   r-   D   sM   1)!LK!L1%N'OK- ;/J1FGIHF/(K%%NHI#A K+IJ/"?JG#MG1
C#MFI1$C!5I/1+9!L1G5)J)%NIGFJ+r)   r-   P   c                   h    e Zd ZdZd Zd Zd Zd Z ej                         fdZ
d Zd Zd	 Zd
 Zy)EventStatuszevent_status.jsonc                      d | _         i | _        y r&   )_path_statusselfs    r*   __init__zEventStatus.__init__   s    
r)   c                 2    i | _         | j                          y r&   )rs   _savert   s    r*   clearzEventStatus.clear   s    

r)   c                 @    | j                  |||      | j                  v S r&   _event_namers   ru   nameversionops       r*   event_markedzEventStatus.event_marked   s     gr2dllBBr)   c                 h    | j                  |||      }|| j                  vry| j                  |   du S NTr{   )ru   r~   r   r   events        r*   event_succeededzEventStatus.event_succeeded   s9      w3$||E"d**r)   c                     t         j                  j                  |t        j                        | _        | j                          y r&   )ospathjoinrp   EVENT_STATUS_FILErr   _load)ru   
status_dirs     r*   
initializezEventStatus.initialize   s'    WW\\*k.K.KL


r)   c                 l    | j                  |||      }|du | j                  |<   | j                          y r   )r|   rs   rx   )ru   r~   r   r   statusr   s         r*   mark_event_statuszEventStatus.mark_event_status   s1      w3%~U

r)   c                 (    dj                  |||      S )Nz{0}-{1}-{2})formatr}   s       r*   r|   zEventStatus._event_name   s    ##D'266r)   c                 t   	 i | _         t        j                  j                  | j                        r:t        | j                  d      5 }t        j                  |      | _         d d d        y y # 1 sw Y   y xY w# t        $ r5}t        j                  dj                  |             i | _         Y d }~y d }~ww xY w)Nrz,Exception occurred loading event status: {0})rs   r   r   isfilerr   openjsonload	Exceptionloggerwarnr   ru   fes      r*   r   zEventStatus._load   s    	DLww~~djj)$**c* 0a#'99Q<DL0 0 *0 0 	KKFMMaPQDLL	s6   AA9 A-#A9 -A62A9 6A9 9	B7+B22B7c                    	 t        | j                  d      5 }t        j                  | j                  |       d d d        y # 1 sw Y   y xY w# t
        $ r.}t        j                  dj                  |             Y d }~y d }~ww xY w)Nwz+Exception occurred saving event status: {0})	r   rr   r   dumprs   r   r   r   r   r   s      r*   rx   zEventStatus._save   sk    	Qdjj#& +!		$,,*+ + + 	QKKELLQOPP	Qs3   A !AA AA A 	B$B  BN)rk   rl   rm   r   rv   ry   r   r   confget_lib_dirr   r   r|   r   rx   r(   r)   r*   rp   rp      sG    +C+ %5D$4$4$6 
7Qr)   rp   c                 l    t        j                  |       }t               }t        d||       d|_        |S )Nr   r   )r   loadsr   r	   	file_type)data_strdatar   s      r*   parse_json_eventr      s1    ::hDE#UD1EOLr)   c                     	 	 t        |       S # t        $ r t        |       cY S w xY w# t        $ r(}t	        dj                  t        |                  d }~ww xY w)NzError parsing event: {0})r   
ValueErrorparse_xml_eventr   r   r   r   )r   r   s     r*   parse_eventr      s^    E	-#H-- 	-"8,,	- E3::47CDDEs$   
 %( %( 	A#AAc                     t        | d      }t        | d      }t        | d      }|}|dk(  rt        |      }n!|dk(  rt        |      }n|dk(  rt        |      }t	        ||      S )NNameValueTz	mt:uint64zmt:boolz
mt:float64)r   intboolfloatr   )
param_noder~   	value_str	attr_typevalues        r*   parse_xml_paramr      sl    Z(D*g.I*c*IEKI	i	Y	l	"i tU++r)   c                 T   	 t        |       }t        t        |d      d      }t        t        |d      d      }t        ||      }t	        |d      }|D ]&  }|j
                  j                  t        |             ( d|_        |S # t        $ r}t        t        |            d }~ww xY w)NEventidProviderParamxml)r   r   r   r   r   
parametersappendr   r   r   r   r   )r   xml_docevent_idprovider_idr   param_nodesr   r   s           r*   r   r      s    "H%T'73T:Wj 94@x5gw/% 	AJ##OJ$?@	A "a!!"s   BB 	B'B""B'c                     t        |      dk(  r|S | t        vr|S 	 t        j                  |      S # t        $ r Y yw xY w)a  
    Gzip and base64 encode a message based on the operation.

    The intent of this message is to make the logs human readable and include the
    stdout/stderr from extension operations.  Extension operations tend to generate
    a lot of noise, which makes it difficult to parse the line-oriented waagent.log.
    The compromise is to encode the stdout/stderr so we preserve the data and do
    not destroy the line oriented nature.

    The data can be recovered using the following command:

      $ echo '<encoded data>' | base64 -d | pigz -zd

    You may need to install the pigz command.

    :param op: Operation, e.g. Enable or Install
    :param message: Message to encode
    :return: gzip'ed and base64 encoded message, or the original message
    r   z<>)lenSHOULD_ENCODE_MESSAGE_OPr   compressr   )r   messages     r*   _encode_messager      sM    * 7|q	))  ))  s   1 	==Tc                 ~    |st        j                  t        | |||       y t        j                  t        | |||       y r&   )r   error
_EVENT_MSGinfo)r~   r   r   duration
is_successs        r*   
_log_eventr     s/     Zr7H=Jb'8<r)   c                   H    e Zd ZdZdZdZdZefdZd Ze	d        Z
d Zd	 Zy
)CollectOrReportEventDebugInfoa,  
    This class is used for capturing and reporting debug info that is captured during event collection and
    reporting to wireserver.
    It captures the count of unicode errors and any unexpected errors and also a subset of errors with stacks to help
    with debugging any potential issues.
       ReportCollectc                 D   d| _         t               | _        d| _        t               | _        || j
                  k(  r+t        j                  | _        t        j                  | _
        y || j                  k(  r+t        j                  | _        t        j                  | _
        y y )Nr   )3_CollectOrReportEventDebugInfo__unicode_error_countset._CollectOrReportEventDebugInfo__unicode_errors._CollectOrReportEventDebugInfo__op_error_count)_CollectOrReportEventDebugInfo__op_errors	OP_REPORTr-   r]   3_CollectOrReportEventDebugInfo__unicode_error_eventr\   /_CollectOrReportEventDebugInfo__op_errors_event
OP_COLLECTr8   r7   )ru   	operations     r*   rv   z&CollectOrReportEventDebugInfo.__init__+  s{    %&" # !5&);)T)TD&%7%I%ID"$//));)U)UD&%7%J%JD" *r)   c                     d } || j                   | j                  | j                          || j                  | j                  | j
                         y )Nc           
          d}| dkD  r=t        ||j                  | t        j                  dj	                  |            d       y y )Nz7DroppedEventsCount: {0}
Reasons (first {1} errors): {2}r   z, F)r   r   r   )	add_eventr   r   4_CollectOrReportEventDebugInfo__MAX_ERRORS_TO_REPORTr   )counterrorsoperation_nameerr_msg_formats       r*   report_dropped_events_errorzTCollectOrReportEventDebugInfo.report_debug_info.<locals>.report_dropped_events_error:  sQ    WNqy^"0"7"7?\?s?suyu~u~  @F  vG  #H%*, r)   )r   r   r   r   r   r   )ru   r   s     r*   report_debug_infoz/CollectOrReportEventDebugInfo.report_debug_info8  sF    	, 	$D$9$94;K;KTMcMcd#D$>$>@U@UW[WqWqrr)   c                     | dz  } t        |      t        j                  k  r<|j                  dj	                  t        |      t        j                                      | S )Nr!   z{0}: {1})r   r   r   addr   r   	traceback
format_exc)error_countr   r   s      r*   _update_errors_and_get_countz:CollectOrReportEventDebugInfo._update_errors_and_get_countD  sK    qv;6MMMJJz((ei6J6J6LMNr)   c                 \    | j                  | j                  | j                  |      | _        y r&   )r   r   r   )ru   unicode_errs     r*   update_unicode_errorz2CollectOrReportEventDebugInfo.update_unicode_errorK  s*    %)%F%FtGaGacgcxcxGR&T"r)   c                 \    | j                  | j                  | j                  |      | _        y r&   )r   r   r   )ru   op_errs     r*   update_op_errorz-CollectOrReportEventDebugInfo.update_op_errorO  s'     $ A A$BWBWY]YiYikq rr)   N)rk   rl   rm   __doc__r   r   r   rv   r   staticmethodr   r   r   r(   r)   r*   r   r      sH     IJ!* K
s  Tsr)   r   c                       e Zd Zd Zed        Zed        Zed        Zd Zd Z	d Z
d Zej                  d	d
 ee      dd	dfdZej                  d	d
 ee      dd	fdZd ZddZed        Zd Zy)EventLoggerc           
         d | _         i | _        g | _        t               }| j                  j	                  t        t        j                  t        j                                      | j                  j	                  t        t        j                  t                     | j                  j	                  t        t        j                  t        t        j                  |                         | j                  j	                  t        t        j                  t        t        j!                  |                         | j                  j	                  t        t        j"                  d             | j                  j	                  t        t        j$                  d             | j                  j	                  t        t        j&                  d             | j                  j	                  t        t        j(                  d             | j                  j	                  t        t        j*                  d             | j                  j	                  t        t        j,                  d             | j                  j	                  t        t        j.                  d             | j                  j	                  t        t        j0                  d             y )	NTenantName_UNINITIALIZEDRoleName_UNINITIALIZEDRoleInstanceName_UNINITIALIZEDLocation_UNINITIALIZEDSubscriptionId_UNINITIALIZEDResourceGroupName_UNINITIALIZEDVMId_UNINITIALIZEDr   )	event_dirperiodic_events_common_parametersr
   r   r   r   	OSVersionr   _get_os_versionExecutionModer   RAMr   _get_ram
Processors_get_processors
TenantNameRoleNameRoleInstanceNameLocationSubscriptionIdResourceGroupNameVMIdImageOrigin)ru   osutils     r*   rv   zEventLogger.__init__T  s@   !* #% &&':;U;_;_ala|a|a~'  	A&&':;U;c;cey'z{&&':;U;Y;Y[^_j_s_stz_{[|'}~&&':;U;`;`befq  gB  gB  CI  gJ  cK  (L  	M 	&&':;U;`;`b|'}~&&':;U;^;^`x'yz&&':;U;f;f  iI  (J  	K 	&&':;U;^;^`x'yz&&':;U;d;d  gE  (F  	G&&':;U;g;g  jK  (L  	M&&':;U;Z;Z\p'qr&&':;U;a;acd'efr)   c                      dj                  t        j                         t        t        t
        t        j                               S )Nz{0}:{1}-{2}-{3}:{4})r   platformsystemr   r   r   releaser(   r)   r*   r	  zEventLogger._get_os_version  s7    $++HOO,={N\lnvn~n~  oA  B  	Br)   c                     	 | j                         S # t        $ r)}t        j                  dt	        |             Y d }~yd }~ww xY w)Nz;Failed to get RAM info; will be missing from telemetry: {0}r   )get_total_memr   r   r   r   r  r   s     r*   r  zEventLogger._get_ram  sE    	`'')) 	`KKUW[\]W^__	`    	A?Ac                     	 | j                         S # t        $ r)}t        j                  dt	        |             Y d }~yd }~ww xY w)NzBFailed to get Processors info; will be missing from telemetry: {0}r   )get_processor_coresr   r   r   r   r  s     r*   r  zEventLogger._get_processors  sE    	g--// 	gKK\^bcd^eff	gr  c                    i }| j                   D ]  }|||j                  <    	 |j                         }|j                  |t        j
                     _        |j                  |t        j                     _        |j                  |t        j                     _        	 t        |j!                               }|j#                         }|j$                  |t        j&                     _        |j(                  |t        j*                     _        |j,                  |t        j.                     _        |j0                  |t        j2                     _        t5        |j6                        |t        j8                     _        y# t        $ r*}t        j                  dt        |             Y d}~d}~ww xY w# t        $ r)}t        j                  dt        |             Y d}~yd}~ww xY w)zZ
        Initializes the common parameters that come from the goal state and IMDS
        zJFailed to get VM info from goal state; will be missing from telemetry: {0}Nz<Failed to get IMDS info; will be missing from telemetry: {0})r  r~   
get_vminfo
tenantNamer   r  r   roleNamer  roleInstanceNamer  r   r   r   r   r   get_endpointget_computelocationr  subscriptionIdr  resourceGroupNamer  vmIdr  r   image_originr  )ru   protocolr   pvminfor   imds_client	imds_infos           r*   #initialize_vminfo_common_parametersz/EventLogger.initialize_vminfo_common_parameters  s   
 
(( 	#A!"Jqvv	#	o((*FFLFWFWJ1<<=CDJOOJ1::;ALRLcLcJ1BBCI		a)(*?*?*ABK#//1IDMDVDVJ1::;AJSJbJbJ1@@AGMVMhMhJ1CCDJ@IJ1667=GJ9KaKaGbJ1==>D  	oKKdfjklfmnn	o  	aKKVX\]^X_``	as1   A6E8 CF. 8	F+F&&F+.	G 7GG c           	         | j                   t        j                  d       y 	 t        j                  | j                   d       	 t        j                  | j                         }t        |      t        k\  rt        j                  t        j                  dj                  | j                   t        |                   |j!                          |d d }|D ]?  }t        j"                  t        j$                  j'                  | j                   |             A t        j$                  j'                  | j                   t        t)        t+        j*                         dz                    }	 t-        |d	z   d
      5 }|j/                  |j1                  d             d d d        t        j2                  |d	z   |t4        z          y # t
        t        f$ r5}dj                  | j                   t        |            }t        |      d }~ww xY w# t
        t        f$ r5}dj                  | j                   t        |            }t        |      d }~ww xY w# 1 sw Y   xY w# t
        t        f$ r!}dj                  |      }t        |      d }~ww xY w)Nz7Cannot save event -- Event reporter is not initialized.i  )modez.Failed to create events folder {0}. Error: {1}zV[PERIODIC] Too many files under: {0}, current count:  {1}, removing oldest event filesiz>Failed to remove old events from events folder {0}. Error: {1}i@B z.tmpzwb+zutf-8z#Failed to write events to file: {0})r  r   r   r   mkdirIOErrorOSErrorr   r   r   r   listdirr   MAX_NUMBER_OF_EVENTSperiodic_warnEVERY_MINUTEsortremover   r   r   timer   writeencoderenameAGENT_EVENT_FILE_EXTENSION)	ru   r   r   msgexisting_eventsoldest_files
event_filefilenamehfiles	            r*   
save_eventzEventLogger.save_event  s   >>!KKQR	"NN4>>6
	" jj8O?#';;$$V%8%8 ;XX^X^_c_m_m_bcr_sYuv  $$&.u5". HJIIbggll4>>:FGH 77<< $Sw)>%? @B	"h'/ 25DKK012IIh'4N)NO/ ! 	"BII$..Z^_`ZabCS/!	" ! 	"RYYZ^ZhZhjnopjqrCS/!	"2 2 ! 	"7>>qACS/!	"s`   !G CH	 )I 8!I(I H0HH	I0IIII J+JJc                     i | _         y r&   )r  rt   s    r*   reset_periodiczEventLogger.reset_periodic  s
    !r)   c                 p    || j                   vxs' | j                   |   |z   t        j                         k  S r&   )r  r   now)ru   deltahs      r*   is_period_elapsedzEventLogger.is_period_elapsed  s:    ,,, @!!!$u,?	@r)   Tr    Fc
           	          t        ||z   t        |      z   |z         }
|	s| j                  ||
      r:| j                  |||||||       t	        j
                         | j                  |
<   y y )Nr   r   r   r   r   	log_event)hashr   rQ  r   r   rN  r  )ru   rO  r~   r   r   r   r   r   rU  forcerP  s              r*   add_periodiczEventLogger.add_periodic  sm    T*--78D**5!4NN4B:#*Gy  R&.llnD  # 5r)   c           	      p   |s|rt        |||||       t        t        t              }|j                  j                  t        t        j                  t        |                   |j                  j                  t        t        j                  t        |                   |j                  j                  t        t        j                  t        |                   |j                  j                  t        t        j                  t        |                   |j                  j                  t        t        j                  t        |                   |j                  j                  t        t        j                  t!        |                   | j#                  |t%        j&                                t)        |      }		 | j+                  t-        j.                  |	             y # t0        $ rF}
t3        j4                  t2        j6                  dj9                  t;        |
                   Y d }
~
y d }
~
ww xY w)Nr   [PERIODIC] {0})r   r   TELEMETRY_EVENT_EVENT_IDTELEMETRY_EVENT_PROVIDER_IDr   r   r   r   r   r   Version	OperationOperationSuccessr   MessageDurationr   add_common_event_parametersr   utcnowr   rJ  r   dumpsr   r   periodic_errorEVERY_FIFTEEN_MINUTESr   r   )ru   r~   r   r   r   r   r   rU  r   r   r   s              r*   r   zEventLogger.add_event  s    	tR(zJ79TU 34S4X4XZmnrZs tu 34S4[4[]pqx]y z{ 34S4]4]_rsu_v wx 34S4d4dfjkufv wx 34S4[4[]pqx]y z{ 34S4\4\^abj^k lm((0ABe$	bOODJJt,- 	b!!&">">@P@W@WX\]^X_@`aa	bs   $G& &	H5/<H00H5c           
         t        t        t              }|j                  j	                  t        t        j                  t        j                               |j                  j	                  t        t        j                  t        j                  j                  |                |j                  j	                  t        t        j                  t        | j!                  |                         |j                  j	                  t        t        j"                  t%        j&                         j)                  t        j*                  j,                                     |j                  j	                  t        t        j.                  d             | j1                  |t%        j&                                t3        |      }	 | j5                  t7        j8                  |             y # t:        $ r Y y w xY w)NrR  )r   TELEMETRY_LOG_EVENT_IDTELEMETRY_LOG_PROVIDER_IDr   r   r   r   	EventNamer-   rR   CapabilityUsedr   LogLevelSTRINGSContext1r   _clean_up_messageContext2r   rd  strftimeLoggerLogTimeFormatInUTCContext3rc  r   rJ  r   re  r   )ru   levelr   r   r   s        r*   add_log_eventzEventLogger.add_log_event  s   57PQ 34O4Y4Y[m[q[q rs 34O4^4^`f`o`o`w`wx}`~   	A 34O4X4XZmnr  oE  oE  FM  oN  [O  !P  	Q 34O4X4XZbZiZiZkZtZtu{  vC  vC  vV  vV  [W  !X  	Y 34O4X4XZ\ ]^((0ABe$	OODJJt,- 		s   >$G# #	G/.G/c           	         |r&dj                  ||||      }t        t        d|d       t        t        t
              }|j                  j                  t        t        j                  t        |                   |j                  j                  t        t        j                  t        |                   |j                  j                  t        t        j                  t        |                   |j                  j                  t        t        j                  t        |                   | j!                  |t#        j$                                t'        |      }	 | j)                  t+        j,                  |             y# t.        $ rF}	t1        j2                  t0        j4                  dj                  t7        |	                   Y d}	~	yd}	~	ww xY w)a  
        Create and save an event which contains a telemetry event.

        :param str category: The category of metric (e.g. "cpu", "memory")
        :param str counter: The specific metric within the category (e.g. "%idle")
        :param str instance: For instanced metrics, the instance identifier (filesystem name, cpu core#, etc.)
        :param value: Value of the metric
        :param bool log_event: If true, log the collected metric in the agent log
        Metric {0}/{1} [{2}] = {3}METRICr   r[  N)r   r   r   r   TELEMETRY_METRICS_EVENT_IDr]  r   r   r   r   Categoryr   CounterInstancer   r   rc  r   rd  r   rJ  r   re  r   r   rf  rg  r   )
ru   categorycounterinstancer   rU  r   r   r   r   s
             r*   
add_metriczEventLogger.add_metric  s\    299(GXW\]Gz8Wa89;VW 34U4^4^`st|`} ~ 34U4]4]_rsz_{ |} 34U4^4^`st|`} ~ 34U4[4[]bch]i jk((0ABe$	bOODJJt,- 	b!!&">">@P@W@WX\]^X_@`aa	bs   $F 	G<GGc                     | s| S t        j                  d      }t        j                  d      }|j                  |       }|r|j                  d      S |j                  |       }|r|j                  d      S | S )Nz'^.*(INFO|WARNING|ERROR|VERBOSE)\s*(.*)$z^[0-9:/\-TZ\s.]*\s(.*)$   r!   )recompilesearchgroup)r   log_level_format_parserlog_format_parserextract_level_messageextract_messages        r*   rp  zEventLogger._clean_up_message#  s    ( N
 #%**-W"XJJ'AB !8 > >w G (..q11 066w?O&,,Q//r)   c           
         t        t        j                  t              t        t        j                  t        j                               t        t        j                  |j                  t        j                  j                              t        t        j                  t        j                         j                        t        t        j                   t#        j$                               t        t        j&                  t        j                         j)                               t        t        j*                  d      g}|j,                  t.        k(  r`|j0                  t2        k(  rM|j5                  t        t6        j8                  |j:                        t        t6        j<                  d      g       |j>                  j5                  |       |j>                  j5                  | j@                         y)z
        This method is called for all events and ensures all telemetry fields are added before the event is sent out.
        Note that the event timestamp is saved in the OpcodeName field.
        rR  FN)!r   r   	GAVersionr   ContainerIdr   get_container_id
OpcodeNamerr  r   rs  rt  EventTid	threadingcurrent_threadidentEventPidr   getpidTaskNamegetNameKeywordNameeventIdr\  
providerIdr]  extendr   ExtensionTyper   
IsInternalr   r  )ru   r   event_timestampcommon_paramss       r*   rc  z'EventLogger.add_common_event_parametersL  sr   
 --G-Q-QS`a,-G-S-SUaUrUrUtu,-G-R-RTcTlTlmsmzmz  nN  nN  UO  P,-G-P-PR[RjRjRlRrRrs,-G-P-PRTR[R[R]^,-G-P-PR[RjRjRlRtRtRvw,-G-S-SUWXZ ==449I9IMh9h   "56U6c6cejetet"u,-L-W-WY^_"a b 	. 7 78r)   N)F)rk   rl   rm   rv   r   r	  r  r  r3  rJ  rL  rQ  r-   rg   strr   rX  r   rw  r  rp  rc  r(   r)   r*   r   r   S  s    *gX B B    a8!"F"@ ,>+E+ERVab 12UZ5 "4!;!;WXbefubvb,b6 & &P9r)   r   c                      t         S r&   )__event_logger__r(   r)   r*   get_event_loggerr  e  s    r)   c                     t        j                         }|| k  ry|| z
  }t        |j                  dz  dz  dz  |j                  z   dz  |j
                  dz  z         S )Nr      <   r$   g     @@)r   rd  r   dayssecondsmicroseconds)	utc_startrN  ds      r*   elapsed_millisecondsr  i  sa    
//
C
YiA"r!B&2d:^^f,. / /r)   rR  c                 H    t        t        t        t              ||| |       y )N)r   r   r   r   rU  )r   r   r  r   )r   r   r   rU  s       r*   report_eventr  s  s     j/*#!#r)   c                 H    t        | t        t        t              |||       y )N)r   r   r   r   )rX  r   r  r   )rO  r   r   r   s       r*   report_periodicr  |  s    
_-& 	r)   c           
      \   |j                   <t        j                  d       dj                  | |||      }t	        t
        d|d       y	 |j                  | ||t        |      |       y# t        $ r9 t        j                  t        j                  dj                  | |||             Y yw xY w)a)  
    Send a telemetry event reporting a single instance of a performance counter.
    :param str category: The category of the metric (cpu, memory, etc)
    :param str counter: The name of the metric ("%idle", etc)
    :param str instance: For instanced metrics, the identifier of the instance. E.g. a disk drive name, a cpu core#
    :param     value: The value of the metric
    :param bool log_event: If True, log the metric in the agent log as well
    :param EventLogger reporter: The EventLogger instance to which metric events should be sent
    Nz@Cannot report metric event -- Event reporter is not initialized.ry  rz  r   zT[PERIODIC] Cannot cast the metric value. Details of the Metric - {0}/{1} [{2}] = {3})r  r   r   r   r   r   r  r   r   r;  EVERY_HALF_HOUR)r  r  r  r   rU  reporterr   s          r*   report_metricr    s     !VW.55hSXY:x!4wHgxuyQ wV33 6KKQ6RZ\cemotKu	wws   
A) )?B+*B+c                 &    |j                  |        y r&   )r3  )r.  r  s     r*   0initialize_event_logger_vminfo_common_parametersr    s    00:r)   c           	          |j                   &t        j                  d       t        | ||||       y t	        | |||      r0t        | |||       |j                  | |||t        |      ||       y y )Nz6Cannot add event -- Event reporter is not initialized.rZ  rT  )r  r   r   r   should_emit_eventr   r   r  )r~   r   r   r   r   r   rU  r  s           r*   r   r     sy    !LM4Wh:FwJ7$Z84B:Z]^eZf#*%. 	 	0 8r)   c                     |j                   y|st               sy| t        j                  j                  k\  r|j                  | |       yy)a!  
    :param level: LoggerLevel of the log event
    :param message: Message
    :param forced: Force write the event even if send_logs_to_telemetry() is disabled
        (NOTE: Remove this flag once send_logs_to_telemetry() is enabled for all events)
    :param reporter:
    :return:
    N)r  r+   r   rm  WARNINGrw  )rv  r   forcedr  s       r*   rw  rw    sF     !,.'''ug. (r)   c
                     |	j                   &t        j                  d       t        |||||       y |	j	                  | ||||t        |      |||	       y )Nz?Cannot add periodic event -- Event reporter is not initialized.rZ  )r   r   r   r   r   rU  rW  )r  r   r   r   rX  r  )
rO  r~   r   r   r   r   r   rU  rW  r  s
             r*   rX  rX    s\    !UV4Wh:F%"h`cdk`l")Ye  Mr)   c                 F    |t         v rt        j                  | |||       y y r&   )__event_status_operations____event_status__r   r~   r   r   r   s       r*   r   r     s$    	((**4"fE )r)   c                     |t         vxs> t        d u xs4 t        j                  | ||       xs t        j                  | ||      |k7  S r&   )r  r  r   r   r  s       r*   r  r    sY    
-- 	FD 	F))$<<	F 	((w;vE	Fr)   c                     | t         _        y r&   )r  r  )r  s    r*   init_event_loggerr    s    !*r)   c                 .    t         j                  |        y r&   )r  r   )r   s    r*   init_event_statusr    s    
+r)   c                 T   t        t        d      rt        t        d      rt        t        d      rvt        t        d      }t        t        d      }t        t        d      }t        j                  |||      }dj                  |      }t        | d|t        j                         y y y y )N	last_type
last_valuelast_tracebackrR  F)r   r   r   )	hasattrsysgetattrr   format_exceptionr   r   r-   re   )r~   r  r  r  r   r   s         r*   dump_unhandled_errr    s    sK WS,%?C)*C-	S,/
 &67**9j+9;''%.$5''66	8 + &@ r)   c                 8    t        j                  t        |        y r&   )atexitregisterr  )r~   s    r*   enable_unhandled_err_dumpr    s    
OO&-r)   )T)TrR  T)TrR  )hr  r   r   r  r  r  r  r?  r   r   azurelinuxagent.common.confcommonr   azurelinuxagent.common.loggerr   #azurelinuxagent.common.AgentGlobalsr    azurelinuxagent.common.exceptionr   r   azurelinuxagent.common.futurer   #azurelinuxagent.common.datacontractr   r	   azurelinuxagent.common.osutilr
   %azurelinuxagent.common.telemetryeventr   r   r   r   r   r   azurelinuxagent.common.utilsr   r   %azurelinuxagent.common.utils.textutilr   r   r   r   r   azurelinuxagent.common.versionr   r   r   r   r   r   r   $azurelinuxagent.common.protocol.imdsr   EVENTS_DIRECTORYr   r]  r\  r{  rj  ri  r'   r:  rC  r  EVENT_FILE_REGEXr+   r-   SHOULD_ENCODE_MESSAGE_LENr=   r@   rP   rf   r   objectrp   r  r^   r  r   r   r   r   r   r   r   r   r  r  r  r  r  r  r  rg   r  r   rw  rX  r   r  r  r  r  r  r(   r)   r*   <module>r     s  $   	  	 
     * * . . < D . N 4d d ; j j [  [  [ @ A
D   B     + 2::BC "=, =,@    	 /Q& /Qd = '' 
E," F=0sF 0sfM9& M9` = /# AFP` w, IY ; "4"<"<XYcfgvcwD3C0 */9I /& "4!;!;WXbefubvt5CSMF
F+,
8.r)   