o
    x[h<  ã                   @   sR  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	Z	d dl
m
Z
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 e e¡ZG dd„ deƒZG d	d
„ d
e jd�ZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZeeeeeef Z eƒ Z!e! "de¡ e! "de¡ e! "de¡ e! "de¡ dS )é    N)ÚdatetimeÚtimezone)ÚEvent)ÚUnion)ÚperformanceÚ
url_helperÚutil)ÚDictRegistryc                   @   s   e Zd ZdS )ÚReportExceptionN)Ú__name__Ú
__module__Ú__qualname__© r   r   ú>/usr/lib/python3/dist-packages/cloudinit/reporting/handlers.pyr
      s    r
   c                   @   s&   e Zd ZdZejdd„ ƒZdd„ ZdS )ÚReportingHandlerzƒBase class for report handlers.

    Implement :meth:`~publish_event` for controlling what
    the handler does with an event.
    c                 C   ó   dS )zPublish an event.Nr   ©ÚselfÚeventr   r   r   Úpublish_event"   ó    zReportingHandler.publish_eventc                 C   r   )z0Ensure ReportingHandler has published all eventsNr   ©r   r   r   r   Úflush&   r   zReportingHandler.flushN)r   r   r   Ú__doc__ÚabcÚabstractmethodr   r   r   r   r   r   r      s
    
r   )Ú	metaclassc                       s*   e Zd ZdZd‡ fdd„	Zdd„ Z‡  ZS )Ú
LogHandlerzBPublishes events to the cloud-init log at the ``DEBUG`` log level.ÚDEBUGc                    s`   t t| ƒ ¡  t|tƒrn|}z	tt| ¡ ƒ}W n ty*   t	 
d|¡ tj}Y nw || _d S )Nzinvalid level '%s', using WARN)Úsuperr   Ú__init__Ú
isinstanceÚintÚgetattrÚloggingÚupperÚ	ExceptionÚLOGÚwarningÚWARNÚlevel)r   r*   Úinput_level©Ú	__class__r   r   r    -   s   

þ
zLogHandler.__init__c                 C   s2   t  d dd|j|jg¡¡}| | j| ¡ ¡ d S )NÚ.Ú	cloudinitÚ	reporting)r$   Ú	getLoggerÚjoinÚ
event_typeÚnameÚlogr*   Ú	as_string)r   r   Úloggerr   r   r   r   :   s   ÿzLogHandler.publish_event)r   )r   r   r   r   r    r   Ú__classcell__r   r   r,   r   r   *   s    r   c                   @   s   e Zd ZdZdd„ ZdS )ÚPrintHandlerzPrint the event as a string.c                 C   s   t | ¡ ƒ d S ©N)Úprintr6   r   r   r   r   r   D   s   zPrintHandler.publish_eventN)r   r   r   r   r   r   r   r   r   r9   A   s    r9   c                       sB   e Zd Z						d
‡ fdd„	Zdd„ Zdd„ Zdd	„ Z‡  ZS )ÚWebHookHandlerNc           	         s–   t t| ƒ ¡  t||||gƒrtj||||d�}|j| _ntj| _|| _|| _|| _	t
 ¡ | _tƒ | _t ¡ | _tj| jd�| _d| j_| j ¡  d S )N)Úconsumer_keyÚ	token_keyÚtoken_secretÚconsumer_secret©ÚtargetT)r   r<   r    Úanyr   ÚOauthUrlHelperÚreadurlÚendpointÚtimeoutÚretriesr   Úfetch_ssl_detailsÚssl_detailsr   Úflush_requestedÚqueueÚQueueÚ	threadingÚThreadÚprocess_requestsÚevent_processorÚdaemonÚstart)	r   rF   r=   r>   r?   r@   rG   rH   Úoauth_helperr,   r   r   r    I   s&   
ü


zWebHookHandler.__init__c              
   C   sì   d}	 | j  ¡ r'|dkr't d¡ | j ¡ s%| j ¡  | j ¡  | j ¡ rd}| jjdd�}z@z| j	|d |d |d |d |d d	d
� d}W n t
yg } zt d|d |¡ |d7 }W Y d }~nd }~ww W | j ¡  n| j ¡  w q)Nr   Té   zNMultiple consecutive failures in WebHookHandler. Cancelling all queued events.©Úblocké   é   é   F)ÚdatarG   rH   rJ   Úlog_req_respz0Failed posting event: %s. This was caused by: %s)rK   Úis_setr'   r(   rL   ÚemptyÚ
get_nowaitÚ	task_doneÚgetrE   r&   )r   Úconsecutive_failedÚargsÚer   r   r   rP   j   sD   ÿ



þúý€ú€ÞzWebHookHandler.process_requestsc                 C   s@   |  ¡ }t d| j|¡ | j | jt |¡| j| j	| j
f¡ d S )NzQueuing POST to %s, data: %s)Úas_dictr'   ÚdebugrF   rL   ÚputÚjsonÚdumpsrG   rH   rJ   )r   r   Ú
event_datar   r   r   r   �   s   ýûÿzWebHookHandler.publish_eventc                 C   s,   | j  ¡  t d¡ | j ¡  | j  ¡  d S )Nz(WebHookHandler flushing remaining events)rK   Úsetr'   rf   rL   r2   Úclearr   r   r   r   r   ¡   s   


zWebHookHandler.flush)NNNNNN)r   r   r   r    rP   r   r   r8   r   r   r,   r   r<   H   s    ø!&r<   c                       sÐ   e Zd ZdZdZdZdZee ZdZdZ	dZ
dZd	Zd
ZdZedf‡ fdd„	Zedd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zded ed!dfd"d#„Zd$d%„ Zd&d'„ Zd(d)„ Zd*d+„ Z‡  ZS ),ÚHyperVKvpReportingHandlera,  
    Reports events to a Hyper-V host using Key-Value-Pair exchange protocol
    and can be used to obtain high level diagnostic information from the host.

    To use this facility, the KVP user-space daemon (hv_kvp_daemon) has to be
    running. It reads the kvp_file when the host requests the guest to
    enumerate the KVP's.

    This reporter collates all events for a module (origin|name) in a single
    json string in the dictionary.

    For more information, see
    https://technet.microsoft.com/en-us/library/dn798287.aspx#Linux%20guests
    i   i   i   Ú
CLOUD_INITÚmsgÚresultÚmsg_i)ú,ú:z/var/lib/hyperv/.kvp_pool_1FNc                    sr   t t| ƒ ¡  || _t | j¡ || _t ¡ | _|  	¡ | _
d | j| j
¡| _tj| jd�| _d| j_| j ¡  d S )Nz{0}|{1}rA   T)r   rm   r    Ú_kvp_file_pathÚ_truncate_guest_pool_fileÚ_event_typesrL   rM   ÚqÚ_get_incarnation_noÚincarnation_noÚformatÚEVENT_PREFIXÚevent_key_prefixrN   rO   Ú_publish_event_routineÚpublish_threadrR   rS   )r   Úkvp_file_pathÚevent_typesr,   r   r   r    Ç   s    ÿ

ÿÿz"HyperVKvpReportingHandler.__init__c              
   C   s´   | j rdS t ¡ tt ¡ ƒ }zFztj |¡|k r.t|dƒ� W d  ƒ n1 s)w   Y  W n t	t
fyI } zt d|¡ W Y d}~nd}~ww W d| _ dS W d| _ dS d| _ w )a  
        Truncate the pool file if it has not been truncated since boot.
        This should be done exactly once for the file indicated by
        KVP_POOL_FILE_GUEST constant above. This method takes a filename
        so that we can use an arbitrary file during unit testing.
        Since KVP is a best-effort telemetry channel we only attempt to
        truncate the file once and only if the file has not been modified
        since boot. Additional truncation can lead to loss of existing
        KVPs.
        NÚwz$failed to truncate kvp pool file, %sT)Ú_already_truncated_pool_fileÚtimeÚfloatr   ÚuptimeÚosÚpathÚgetmtimeÚopenÚOSErrorÚIOErrorr'   r(   )ÚclsÚkvp_fileÚ	boot_timerd   r   r   r   ru   Ú   s"   ÿ€€ÿ€
þz3HyperVKvpReportingHandler._truncate_guest_pool_filec                 C   s@   t  ¡ }ztt ¡ t|ƒ ƒW S  ty   t d|¡ Y dS w )zÀ
        use the time passed as the incarnation number.
        the incarnation number is the number which are used to
        distinguish the old data stored in kvp and the new data.
        z"uptime '%s' not in correct format.r   )r   r…   r"   rƒ   r„   Ú
ValueErrorr'   r(   )r   Ú
uptime_strr   r   r   rx   ò   s   þz-HyperVKvpReportingHandler._get_incarnation_noc                 c   sž   � t | jdƒ�>}t |tj¡ | |¡ | | j¡}t|ƒ| jkr6|  	|¡}|V  | | j¡}t|ƒ| jks!t |tj
¡ W d  ƒ dS 1 sHw   Y  dS )z-iterate the kvp file from the current offset.ÚrbN)r‰   rt   ÚfcntlÚflockÚLOCK_EXÚseekÚreadÚHV_KVP_RECORD_SIZEÚlenÚ_decode_kvp_itemÚLOCK_UN)r   ÚoffsetÚfÚrecord_dataÚkvp_itemr   r   r   Ú_iterate_kvpsÿ   s   €

ý"øz'HyperVKvpReportingHandler._iterate_kvpsc                 C   s   d  | j|j|jt ¡ ¡S )z�
        the event key format is:
        CLOUD_INIT|<incarnation number>|<event_type>|<event_name>|<uuid>
        [|subevent_index]
        z{0}|{1}|{2}|{3})rz   r|   r3   r4   ÚuuidÚuuid4r   r   r   r   Ú
_event_key  s   ÿz$HyperVKvpReportingHandler._event_keyc                 C   s*   t  d| j| jf | d¡| d¡¡}|S )Nz%ds%dsúutf-8)ÚstructÚpackÚHV_KVP_EXCHANGE_MAX_KEY_SIZEÚHV_KVP_EXCHANGE_MAX_VALUE_SIZEÚencode©r   ÚkeyÚvaluer[   r   r   r   Ú_encode_kvp_item  s   þÿù	z*HyperVKvpReportingHandler._encode_kvp_itemc                 C   sd   t |ƒ}|| jkrtd || j¡ƒ‚|d| j…  d¡ d¡}|| j| j…  d¡ d¡}||dœS )Nz$record_data len not correct {0} {1}.r   r£   ú )rª   r«   )r˜   r—   r
   rz   r¦   ÚdecodeÚstrip)r   r�   Úrecord_data_lenÚkÚvr   r   r   r™   !  s$   
ÿÿý
ÿû
z*HyperVKvpReportingHandler._decode_kvp_itemc              	   C   s¬   t  d| j› �¡�C t| jdƒ�$}t |tj¡ |D ]}| |¡ q| ¡  t |tj	¡ W d   ƒ n1 s7w   Y  W d   ƒ d S W d   ƒ d S 1 sOw   Y  d S )Nz
Appending Úab)
r   ÚTimedrt   r‰   r’   r“   r”   Úwriter   rš   )r   r�   rœ   r[   r   r   r   Ú_append_kvp_item8  s   ÿPùz*HyperVKvpReportingHandler._append_kvp_itemc                 C   sÒ   || j = t |¡}|dt|ƒd … }d}g }d| j  d }	 ||| j< d|| j < tj|| jd�}| jt|ƒ d }	| |d	j| j |d |	… d
�¡}
d ||¡}| 	|  
||
¡¡ |d7 }||	d … }|sh	 |S q)NrX   r   ú"z":""TÚ ©Ú
separatorsé   z"{key}":"{desc}")rª   Údescz{}|{})ÚMSG_KEYrh   ri   r˜   ÚDESC_IDX_KEYÚJSON_SEPARATORSÚHV_KVP_AZURE_MAX_VALUE_SIZEÚreplacerz   Úappendr¬   )r   rª   Ú	meta_dataÚdescriptionÚdes_in_jsonÚiÚresult_arrayÚmessage_place_holderÚdata_without_descÚroom_for_descr«   Úsubkeyr   r   r   Ú_break_downB  s8   


ÿÿÿþëz%HyperVKvpReportingHandler._break_downrª   r«   Úreturnc              	   C   sf   t |ƒ| jkr|d| jd … }|  ||¡g}z|  |¡ W dS  ttfy2   t d||¡ Y dS w )zJWrite KVP key-value.

        Values will be truncated as needed.
        r   rX   zfailed posting kvp=%s value=%sN)r˜   rÀ   r¬   r¶   rŠ   r‹   r'   r(   r©   r   r   r   Ú	write_key`  s   ÿz#HyperVKvpReportingHandler.write_keyc                 C   sŽ   |   |¡}|j|jt |jtj¡ ¡ dœ}t	|| j
ƒr!|j|| j
< |j|| j< tj|| jd�}t|ƒ| jkr>|  |||j¡S |  ||¡}|gS )z®
        encode the event into kvp data bytes.
        if the event content reaches the maximum length of kvp value.
        then it would be cut to multiple slices.
        )r4   ÚtypeÚtsr¹   )r¢   r4   r3   r   ÚfromtimestampÚ	timestampr   ÚutcÚ	isoformatÚhasattrÚ
RESULT_KEYrp   rÄ   r½   rh   ri   r¿   r˜   rÀ   rÌ   r¬   )r   r   rª   rÃ   r«   r[   r   r   r   Ú_encode_evento  s    
ÿú	z'HyperVKvpReportingHandler._encode_eventc              
   C   s
  	 d}zv| j jdd�}|d7 }g }|d ur:||  |¡7 }z| j jdd�}|d7 }W n tjy5   d }Y nw |d usz0z|  |¡ W n ttfy\ } zt 	d|¡ W Y d }~nd }~ww W t
|ƒD ]}| j  ¡  qbnt
|ƒD ]}| j  ¡  qow W n
 tyƒ   Y d S w q)NTr   rV   rX   Fz failed posting events to kvp, %s)rw   ra   r×   rL   ÚEmptyr¶   rŠ   r‹   r'   r(   Úranger`   ÚEOFError)r   Úitems_from_queuer   Úencoded_datard   Ú_r   r   r   r}   Œ  s>   ÿú€ÿ€ÿÿÿéz0HyperVKvpReportingHandler._publish_event_routinec                 C   s&   | j r	|j| j v r| j |¡ d S d S r:   )rv   r3   rw   rg   r   r   r   r   r   ª  s   ÿz'HyperVKvpReportingHandler.publish_eventc                 C   s   t  d¡ | j ¡  d S )Nz0HyperVReportingHandler flushing remaining events)r'   rf   rw   r2   r   r   r   r   r   ®  s   
zHyperVKvpReportingHandler.flush) r   r   r   r   r§   rÀ   r¦   r—   r{   r½   rÖ   r¾   r¿   ÚKVP_POOL_FILE_GUESTr‚   r    Úclassmethodru   rx   rŸ   r¢   r¬   r™   r¶   rÌ   ÚstrrÎ   r×   r}   r   r   r8   r   r   r,   r   rm   ¨   s:    ÿ


rm   r5   r;   ÚwebhookÚhyperv)#r   r’   rh   r$   r†   rL   r¤   rN   rƒ   r    r   r   r   Útypingr   r/   r   r   r   Úcloudinit.registryr	   r1   r   r'   r&   r
   ÚABCMetar   r   r9   r<   rm   ÚHandlerTypeÚavailable_handlersÚregister_itemr   r   r   r   Ú<module>   sJ   
`  üÿ