
    d93                        d dl Z d dlZd dlZd dlmc mZ d dlmc mZ d dlmc m	c m
Z
 d dlmZmZ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 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 Z. G d de-      Z/ G d de-      Z0 G d de-      Z1 G d de-      Z2 G d de-      Z3 G d de-      Z4 G d de-      Z5 G d  d!e      Z6y)"    N)MetricValueMetricsCategoryMetricsCounter)CGroupConfigurator)CGroupsTelemetry)
ErrorState)	add_eventWALAEventOperationreport_metric)ustr)ThreadHandlerInterface)
get_osutil)HealthService)get_imds_client)get_protocol_util)IOErrorCounter)hash_strings)
AGENT_NAMECURRENT_VERSION)PeriodicOperationc                      t               S N)MonitorHandler     </usr/lib/python3/dist-packages/azurelinuxagent/ga/monitor.pyget_monitor_handlerr   *   s    r   c                   (     e Zd ZdZ fdZd Z xZS )PollResourceUsagez
    Periodic operation to poll the tracked cgroups for resource usage data.

    It also checks whether there are processes in the agent's cgroup that should not be there.

    c                     t         t        |   t        j                                t        j
                         | _        i | _        y r   )superr   __init__confget_cgroup_check_periodget_cgroup_log_metrics_PollResourceUsage__log_metrics$_PollResourceUsage__periodic_metricsself	__class__s    r   r"   zPollResourceUsage.__init__5   s5    /0L0L0NO!88:"$r   c                 :   t        j                         }|D ]  }|j                  |j                  z   |j                  z   }|| j
                  vs<| j
                  |   |j                  z   t        j                  j                         k  sst        |j                  |j                  |j                  |j                  | j                         t        j                  j                         | j
                  |<    t        j                         j                  |       y N)	log_event)r   poll_all_trackedcategorycounterinstancer'   report_perioddatetimenowr   valuer&   r   get_instancecheck_cgroups)r)   tracked_metricsmetrickeys       r   
_operationzPollResourceUsage._operation:   s    *;;=% 	GF//FNN2V__DC$111d6M6Mc6RU[UiUi6invnn  oD  oD  oF  6Ffoov~~vPVP\P\hlhzhz{/7/@/@/D/D/F'',		G 	'')77Hr   __name__
__module____qualname____doc__r"   r;   __classcell__r*   s   @r   r   r   .   s    %
	Ir   r   c                   *     e Zd Z fdZd Zd Z xZS )PollSystemWideResourceUsagec                     t         t        |   t        j                  d             t        j                         | _        t               | _	        y )N   hours)
r!   rD   r"   r3   	timedeltar#   r%   )_PollSystemWideResourceUsage__log_metricsr   osutilr(   s    r   r"   z$PollSystemWideResourceUsage.__init__G   s9    )49(:L:LST:UV!88: lr   c                     | j                   j                         \  }}t        t        j                  t
        j                  d|      t        t        j                  t
        j                  d|      gS )N )rK   $get_used_and_available_system_memoryr   r   MEMORY_CATEGORYr   USED_MEMAVAILABLE_MEM)r)   used_memavailable_mems      r   poll_system_memory_metricsz6PollSystemWideResourceUsage.poll_system_memory_metricsL   s_    "&++"R"R"T-779P9PRT "779U9UWY%'
 	
r   c                     | j                         }|D ]D  }t        |j                  |j                  |j                  |j
                  | j                         F y r,   )rT   r   r/   r0   r1   r5   rJ   )r)   metricsr9   s      r   r;   z&PollSystemWideResourceUsage._operationU   sH    113 	xF&//6>>6??FLLdhdvdvw	xr   )r=   r>   r?   r"   rT   r;   rA   rB   s   @r   rD   rD   F   s    #

xr   rD   c                   (     e Zd ZdZ fdZd Z xZS )ResetPeriodicLogMessagesz
    Periodic operation to clean up the hash-tables maintained by the loggers. For reference, please check
    azurelinuxagent.common.logger.Logger and azurelinuxagent.common.event.EventLogger classes
    c                 T    t         t        |   t        j                  d             y )N   rG   )r!   rX   r"   r3   rI   r(   s    r   r"   z!ResetPeriodicLogMessages.__init__`   s    &6x7I7IPR7STr   c                 ,    t        j                          y r   )loggerreset_periodicr)   s    r   r;   z#ResetPeriodicLogMessages._operationc   s    r   r<   rB   s   @r   rX   rX   [   s    U r   rX   c                   $     e Zd Z fdZd Z xZS )ReportNetworkErrorsc                 T    t         t        |   t        j                  d             y )N   minutes)r!   r`   r"   r3   rI   r(   s    r   r"   zReportNetworkErrors.__init__h   s    !41(2D2DR2PQr   c                    t        j                         }|j                  d      }|j                  d      }|j                  d      }|dkD  s
|dkD  s|dkD  r/dj                  |||      }t	        t
        j                  |       y y )N
hostpluginprotocolotherr   z%hostplugin:{0};protocol:{1};other:{2})opmessage)r   get_and_resetgetformatr	   r
   
HttpErrors)r)   	io_errorshostplugin_errorsprotocol_errorsother_errorsmsgs         r   r;   zReportNetworkErrors._operationk   s    "002	%MM,7#--
3 }}W-q Oa$7<!;K9@@ARTceqrC+66D <Lr   )r=   r>   r?   r"   r;   rA   rB   s   @r   r`   r`   g   s    REr   r`   c                   .     e Zd ZdZ fdZd Zd Z xZS )!ReportNetworkConfigurationChangeszO
    Periodic operation to check and log changes in network configuration.
    c                     t         t        |   t        j                  d             t               | _        d| _        i | _        y )NrF   rc   r   )	r!   ru   r"   r3   rI   r   rK   last_route_table_hashlast_nic_stater(   s    r   r"   z*ReportNetworkConfigurationChanges.__init__z   s8    /?@R@R[\@]^ l%(" r   c           	      T   	 d}t         j                  j                  |      rg }t        |      5 }|D ]L  }|j	                  |       t        |      dk\  s#|j	                  dj                  t        |                    n d d d        t        j                  d|dj                  |             | j                  j                  d      }|dk7  rt        j                  d|       y y # 1 sw Y   hxY w# t        $ r)}t        j                  d	t        |             Y d }~y d }~ww xY w)
Nz/proc/net/routed   z<TRUNCATED TO {0} LINESzRouting table from {0}:
{1}rM   T)	as_stringzNetwork interfaces:
{0}z-Error fetching the network configuration: {0})ospathexistsopenappendlenrm   r\   infojoinrK   get_nic_state	Exceptionwarnr   )r)   
route_filelinesfile_objectlinenetwork_interfaces	exceptions          r   log_network_configurationz;ReportNetworkConfigurationChanges.log_network_configuration   s   	Z*Jww~~j)*% " + "T*u:,!LL)B)I)I#e*)UV!	"" :JPUW!%!:!:T!:!J!R'68JK (" "  	ZKKGiYY	Zs5   .C5 %C),C)A%C5 )C2.C5 5	D'>D""D'c                    | j                   j                         }t        |      }|| j                  k7  rw|| _        | j                   j	                  |      }t        j                  dj                  dj                  t        t        j                  j                  |                         | j                   j                         }|| j                  k7  rk| j                  i k(  rdnd}t        j                  dj                  |dj                  t        t        |j!                                                  || _        y y )NzRoute table: [{0}],InitialUpdatedz{0} NIC state: [{1}]z, )rK   read_route_tabler   rw   get_list_of_routesr\   r   rm   r   mapnetworkutil
RouteEntryto_jsonr   rx   strvalues)r)   raw_route_listdigest
route_list	nic_statedescriptions         r   r;   z,ReportNetworkConfigurationChanges._operation   s    557n-T///)/D&77GJKK,33CHHSAWAWA_A_ak=l4mnoKK--/	+++'+':':b'@)iKKK.55k499SQTV_VfVfVhMiCjkl"+D ,r   )r=   r>   r?   r@   r"   r   r;   rA   rB   s   @r   ru   ru   v   s    !Z$,r   ru   c                   t     e Zd ZdZ fdZ ej                  d      Z ej                  d      Zd Z	 xZ
S )SendHostPluginHeartbeatz
    Periodic operation for reporting the HostGAPlugin's health. The signal is 'Healthy' when we have been able to communicate with
    plugin at least once in the last _HOST_PLUGIN_HEALTH_PERIOD.
    c                     t         t        |   t        j                         || _        || _        t        t        j                        | _        y N)min_timedelta)	r!   r   r"   _HOST_PLUGIN_HEARTBEAT_PERIODrg   health_servicer   _HOST_PLUGIN_HEALTH_PERIODhost_plugin_error_state)r)   rg   r   r*   s      r   r"   z SendHostPluginHeartbeat.__init__   s=    %t56M6k6kl ,'1@W@r@r's$r   rF   rc      c           	      
   	 | j                   j                  j                         }|j                          | j                   j	                          |j                         }|r| j                  j                          n| j                  j                          | j                  j                         du }t        j                  d|       | j                  j                  |       |sKt        t        t         t"        j$                  ddj'                  | j                  j(                        d       y y # t*        $ rG}dj'                  t-        |            }t        t        t         t"        j.                  d|d        d }~ww xY w)NFzHostGAPlugin health: {0}z{0} since successful heartbeatnameversionri   
is_successrj   r-   z,Exception sending host plugin heartbeat: {0})rg   clientget_host_pluginensure_initialized"update_host_plugin_from_goal_state
get_healthr   resetincris_triggeredr\   verboser   report_host_plugin_heartbeatr	   r   r   r
   HostPluginHeartbeatExtendedrm   	fail_timer   r   HostPluginHeartbeat)r)   host_pluginis_currently_healthy
is_healthyers   s         r   r;   z"SendHostPluginHeartbeat._operation   s7   #	--..>>@K**,MM<<>#.#9#9#; #,,224,,11355BBDMJNN5zB<<ZH#+)EE$<CCDD`D`DjDjk#%   		@GGQPC'%99 ! 		s   D.D2 2	F;AE==F)r=   r>   r?   r@   r"   r3   rI   r   r   r;   rA   rB   s   @r   r   r      s;    t %7H$6$6q$A!!3!3!3A!>$r   r   c                   t     e Zd ZdZ fdZ ej                  d      Z ej                  d      Zd Z	 xZ
S )SendImdsHeartbeatz
    Periodic operation to report the IDMS's health. The signal is 'Healthy' when we have successfully called and validated
    a response in the last _IMDS_HEALTH_PERIOD.
    c                     t         t        |   t        j                         || _        t        |j                               | _        t        t        j                        | _
        y r   )r!   r   r"   _IMDS_HEARTBEAT_PERIODr   r   get_wireserver_endpointimds_clientr   _IMDS_HEALTH_PERIODimds_error_state)r)   protocol_utilr   r*   s      r   r"   zSendImdsHeartbeat.__init__   sL    /0A0X0XY,*=+P+P+RS *9J9^9^ _r   rF   rc      c           	         	 | j                   j                         \  }}|r| j                  j                          n| j                  j	                          | j                  j                         du }t        j                  d||       | j                  j                  ||       y # t        $ rG}dj                  t        |            }t        t        t        t         j"                  d|d        d }~ww xY w)NFzIMDS health: {0} [{1}]z%Exception sending imds heartbeat: {0}r   )r   validater   r   r   r   r\   r   r   report_imds_statusr   rm   r   r	   r   r   r
   ImdsHeartbeat)r)   r   responser   r   rs   s         r   r;   zSendImdsHeartbeat._operation   s    	-1-=-=-F-F-H* (#%%++-%%**,..;;=FJNN3ZJ22:xH 		9@@aIC'%33 ! 		s   B#B& &	C6/AC11C6)r=   r>   r?   r@   r"   r3   rI   r   r   r;   rA   rB   s   @r   r   r      s;    ` 0X//:,(,,Q7r   r   c                   P    e Zd Zd Zed        Zd Zd Zd Zd Z	d Z
d Zd Zd	 Zy
)r   c                  "    t         j                  S r   )r   _THREAD_NAMEr   r   r   get_thread_namezMonitorHandler.get_thread_name  s    ***r   c                      d | _         d| _        y )NT)monitor_thread
should_runr^   s    r   r"   zMonitorHandler.__init__  s    "r   c                 $    | j                          y r   )startr^   s    r   runzMonitorHandler.run	  s    

r   c                 T    d| _         | j                         r| j                          y y )NF)r   is_aliver   r^   s    r   stopzMonitorHandler.stop  s     ==?IIK r   c                 8    | j                   j                          y r   )r   r   r^   s    r   r   zMonitorHandler.join  s      "r   c                     | j                    S r   )r   r^   s    r   stoppedzMonitorHandler.stopped  s    ??""r   c                 V    | j                   d uxr | j                   j                         S r   )r   r   r^   s    r   r   zMonitorHandler.is_alive  s'    ""$.Q43F3F3O3O3QQr   c                 
   t        j                  | j                        | _        | j                  j	                  d       | j                  j                  | j                                | j                  j                          y )N)targetT)	threadingThreaddaemonr   	setDaemonsetNamer   r   r^   s    r   r   zMonitorHandler.start  s\    '..dkkB%%d+##D$8$8$:;!!#r   c           	         	 t               }|j                         }t        |j                               }t	               t               t               t               t        ||      t        ||      g}t               }t        j                         r|j                  |       n%t        j                  d       |j!                          | j#                         s@	 |D ]  }|j%                           	 t'        j(                  |       | j#                         s?y y # t'        j(                  |       w xY w# t*        $ r)}t        j,                  dt/        |             Y d }~y d }~ww xY w)Nz0Monitor.NetworkConfigurationChanges is disabled.zBAn error occurred in the monitor thread; will exit the thread.
{0})r   get_protocolr   get_endpointrX   r`   r   rD   r   r   ru   r#   )get_monitor_network_configuration_changesr   r\   r   r   r   r   r   sleep_until_next_operationr   errorr   )r)   r   rg   r   periodic_operations$report_network_configuration_changesri   r   s           r   r   zMonitorHandler.daemon   s'   	i ./M$113H*8+@+@+BCN(*#%!#+-'.A!-@# 4U3V0==?#**+OPNO4NNPllnV1 !! &@@ATU lln
 &@@ATU 	iLL^`def`ghh	is0   CD1 D /%D1 D..D1 1	E#:EE#N)r=   r>   r?   r   staticmethodr   r"   r   r   r   r   r   r   r   r   r   r   r   r      sC    #L+ +
##R$ir   r   )7r3   r|   r   azurelinuxagent.common.confcommonr#   azurelinuxagent.common.loggerr\   (azurelinuxagent.common.utils.networkutilutilsr   azurelinuxagent.common.cgroupr   r   r   )azurelinuxagent.common.cgroupconfiguratorr   'azurelinuxagent.common.cgroupstelemetryr   !azurelinuxagent.common.errorstater   azurelinuxagent.common.eventr	   r
   r   azurelinuxagent.common.futurer   !azurelinuxagent.common.interfacesr   azurelinuxagent.common.osutilr   -azurelinuxagent.common.protocol.healthservicer   $azurelinuxagent.common.protocol.imdsr   $azurelinuxagent.common.protocol.utilr   %azurelinuxagent.common.utils.restutilr   %azurelinuxagent.common.utils.textutilr   azurelinuxagent.common.versionr   r   %azurelinuxagent.ga.periodic_operationr   r   r   rD   rX   r`   ru   r   r   r   r   r   r   <module>r     s   $  	  * * . . > > V V H D 8 U U . D 4 G @ B @ > F CI) I0x"3 x*	 0 	 E+ E(,(9 (,V2/ 2j%) %P@i+ @ir   