
0VM              B   @   s  d  d l  m 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 e j dH k rw d  d l m Z d  d l m Z m Z m Z m Z m Z m Z m Z m Z d d l m Z m Z m Z d d l m  Z  m! Z! m" Z" m# Z# m$ Z$ m% Z% m& Z& m' Z' m( Z( m) Z) d d	 l* m+ Z, e j dI k rEd d
 l m- Z- n e. Z- d d   Z/ d d   Z0 d d   Z1 d d   Z2 d d   Z3 e j dJ k rd d   Z4 n	 e j5 Z4 d e4 d e4 d e4 d e6 d e6 d e6 d e6 d e6 d e6 d  e6 d! e6 d" e6 d# e6 d$ e6 d% e6 d& e6 d' e6 d( e6 d) e6 d* e6 d+ e6 d, e2 d- e1 d. e0 d/ e/ d0 e3 d1 e7 d2 e6 d3 e6 d4 e6 d5 e6 d6 e6 d7 e2 i! Z8 e9 d8  Z: d9 d:   Z; Gd; d<   d< e   Z< d= d>   Z= d? d@   Z> d d d d dA dB  Z? e dC dD dE  Z@ GdF dG   dG e jA  ZB d S)K    )divisionN   )ChainMap)	LOG_EMERG	LOG_ALERTLOG_CRITLOG_ERRLOG_WARNING
LOG_NOTICELOG_INFO	LOG_DEBUG   )__version__sendv	stream_fd)
_ReaderNOPAPPEND
INVALIDATE
LOCAL_ONLYRUNTIME_ONLYSYSTEMSYSTEM_ONLYCURRENT_USER_get_catalog)id128)	Monotonicc             C   s0   t  t j d |  d  t j d |  d  f  S)Nmicrosecondsr   bytesr   )r   	_datetime	timedelta_uuidUUID)m r$   1/usr/lib/python3/dist-packages/systemd/journal.py_convert_monotonic-   s    r&   c             C   s   t  j d t |    S)Nr   )r   r    int)sr$   r$   r%   _convert_source_monotonic1   s    r)   c             C   s   t  j j |  d  S)Ni@B )r   datetimefromtimestamp)tr$   r$   r%   _convert_realtime4   s    r-   c             C   s   t  j j t |   d  S)Ni@B )r   r*   r+   r'   )r(   r$   r$   r%   _convert_timestamp7   s    r.   c             C   s   |  S)Nr$   )xr$   r$   r%   _convert_trivial:   s    r0   c             C   s   t  j |  j    S)N)r!   r"   decode)r(   r$   r$   r%   _convert_uuid>   s    r2   
MESSAGE_ID_MACHINE_ID_BOOT_IDPRIORITYZLEADERZ
SESSION_IDZUSERSPACE_USECZINITRD_USECZKERNEL_USECZ_UIDZ_GIDZ_PIDZSYSLOG_FACILITYZ
SYSLOG_PIDZ_AUDIT_SESSIONZ_AUDIT_LOGINUIDZ_SYSTEMD_SESSIONZ_SYSTEMD_OWNER_UID	CODE_LINEZERRNOZEXIT_STATUSZ_SOURCE_REALTIME_TIMESTAMP__REALTIME_TIMESTAMPZ_SOURCE_MONOTONIC_TIMESTAMP__MONOTONIC_TIMESTAMP__CURSORZCOREDUMPZCOREDUMP_PIDZCOREDUMP_UIDZCOREDUMP_GIDZCOREDUMP_SESSIONZCOREDUMP_SIGNALZCOREDUMP_TIMESTAMPZ%ABCDEFGHIJKLMNOPQRTSUVWXYZ_0123456789c             C   s   t  |   t S)N)set_IDENT_CHARACTER)r(   r$   r$   r%   _valid_field_namei   s    r=   c                   s3  e  Z d  Z d Z d d d d   f d d  Z d d   Z d d	   Z d
 d   Z d d   Z e	 j
 d& k  ru e Z   f d d   Z d   f d d  Z d d d  Z   f d d   Z d   f d d  Z   f d d   Z d   f d d  Z d d   Z d  d!   Z d d" d#  Z d d$ d%  Z   S)'Readera  Reader allows the access and filtering of systemd journal
    entries. Note that in order to access the system journal, a
    non-root user must be in the `systemd-journal` group.

    Example usage to print out all informational or higher level
    messages for systemd-udevd for this boot:

    >>> from systemd import journal
    >>> j = journal.Reader()
    >>> j.this_boot()
    >>> j.log_level(journal.LOG_INFO)
    >>> j.add_match(_SYSTEMD_UNIT="systemd-udevd.service")
    >>> for entry in j:                                 # doctest: +SKIP
    ...    print(entry['MESSAGE'])
    starting version ...

    See systemd.journal-fields(7) for more info on typical fields
    found in the journal.
    r   Nc                s   t  t |   j | | |  t j d k rl t   |  _ | d k	 rV |  j j j |  |  j j j t	  n+ t	 j
   |  _ | d k	 r |  j j |  d S)a  Create an instance of Reader, which allows filtering and
        return of journal entries.

        Argument `flags` sets open flags of the journal, which can be one
        of, or ORed combination of constants: LOCAL_ONLY (default) opens
        journal on local machine only; RUNTIME_ONLY opens only
        volatile journal files; and SYSTEM_ONLY opens only
        journal files of system services and the kernel.

        Argument `path` is the directory of journal files. Note that
        `flags` and `path` are exclusive.

        Argument `converters` is a dictionary which updates the
        DEFAULT_CONVERTERS to convert journal field values. Field
        names are used as keys into this dictionary. The values must
        be single argument functions, which take a `bytes` object and
        return a converted value. When there's no entry for a field
        name, then the default UTF-8 decoding will be attempted. If
        the conversion fails with a ValueError, unconverted bytes
        object will be returned. (Note that ValueEror is a superclass
        of UnicodeDecodeError).

        Reader implements the context manager protocol: the journal
        will be closed when exiting the block.
        r   N)r   r   )superr>   __init___sysversion_info	_ChainMap
convertersmapsappendDEFAULT_CONVERTERScopyupdate)selfflagspathfilesrD   )	__class__r$   r%   r@      s    zReader.__init__c             C   sC   |  j  j | t j  } y | |  SWn t k
 r> | SYn Xd S)a.  Convert value using self.converters[key]

        If `key` is not present in self.converters, a standard unicode
        decoding will be attempted.  If the conversion (either
        key-specific or the default one) fails with a ValueError, the
        original bytes object will be returned.
        N)rD   getr   r1   
ValueError)rJ   keyvalueZconvertr$   r$   r%   _convert_field   s
    zReader._convert_fieldc                so   i  } xb | j    D]T \   } t | t  rQ    f d d   | D |   <q  j   |  |   <q W| S)z5Convert entire journal entry utilising _convert_fieldc                s"   g  |  ] }  j    |   q Sr$   )rS   ).0val)rQ   rJ   r$   r%   
<listcomp>   s   	 z)Reader._convert_entry.<locals>.<listcomp>)items
isinstancelistrS   )rJ   entryresultrR   r$   )rQ   rJ   r%   _convert_entry   s    #zReader._convert_entryc             C   s   |  S)z9Part of iterator protocol.
        Returns self.
        r$   )rJ   r$   r$   r%   __iter__   s    zReader.__iter__c             C   s#   |  j    } | r | St    d S)z\Part of iterator protocol.
        Returns self.get_next() or raises StopIteration.
        N)get_nextStopIteration)rJ   Zansr$   r$   r%   __next__   s    zReader.__next__r   c                sW   t  |  } | j d d   | j   D  x$ | D] } t t |   j |  q3 Wd S)aO  Add one or more matches to the filter journal log entries.
        All matches of different field are combined in a logical AND,
        and matches of the same field are automatically combined in a
        logical OR.
        Matches can be passed as strings of form "FIELD=value", or
        keyword arguments FIELD="value".
        c             s   s$   |  ] \ } } t  | |  Vq d  S)N)
_make_line)rT   rQ   rU   r$   r$   r%   	<genexpr>   s    z#Reader.add_match.<locals>.<genexpr>N)rY   extendrW   r?   r>   	add_match)rJ   argskwargsarg)rN   r$   r%   rd      s     zReader.add_matchr   c                sw   t  t |   j |  rp t  t |   j   } | rp |  j   | d <|  j   | d <|  j   | d <|  j |  St   S)a  Return the next log entry as a mapping type, currently
        a standard dictionary of fields.

        Optional skip value will return the `skip`\-th log entry.

        Entries will be processed with converters specified during
        Reader creation.
        r8   r9   r:   )	r?   r>   Z_nextZ_get_allZ_get_realtimeZ_get_monotonicZ_get_cursorr\   dict)rJ   skiprZ   )rN   r$   r%   r^      s    	zReader.get_nextc             C   s   |  j  |  S)a5  Return the previous log entry as a mapping type,
        currently a standard dictionary of fields.

        Optional skip value will return the -`skip`\-th log entry.

        Entries will be processed with converters specified during
        Reader creation.

        Equivalent to get_next(-skip).
        )r^   )rJ   ri   r$   r$   r%   get_previous   s    zReader.get_previousc                s2   t     f d d   t t   j    D  S)zReturn unique values appearing in the journal for given `field`.

        Note this does not respect any journal matches.

        Entries will be processed with converters specified during
        Reader creation.
        c             3   s!   |  ] }  j    |  Vq d  S)N)rS   )rT   rR   )fieldrJ   r$   r%   rb     s   z&Reader.query_unique.<locals>.<genexpr>)r;   r?   r>   query_unique)rJ   rk   )rN   )rk   rJ   r%   rl      s    zReader.query_uniquec                s8   | d k r d n t  | d  } t t |   j |  S)a1  Wait for a change in the journal. `timeout` is the maximum
        time in seconds to wait, or None, to wait forever.

        Returns one of NOP (no change), APPEND (new entries have been
        added to the end of the journal), or INVALIDATE (journal files
        have been added or removed).
        Nr   i@B )r'   r?   r>   wait)rJ   Ztimeoutus)rN   r$   r%   rn     s    "zReader.waitc                sG   t  | t j  r+ t | j d   d } t t |   j t |   S)zSeek to a matching journal entry nearest to `realtime` time.

        Argument `realtime` must be either an integer unix timestamp
        or datetime.datetime instance.
        z%s.%fi@B )	rX   r   r*   floatZstrftimer?   r>   seek_realtimer'   )rJ   Zrealtime)rN   r$   r%   rq     s    zReader.seek_realtimec                sb   t  | t j  r | j   } t | d  } t  | t j  rI | j } t t	 |   j
 | |  S)aG  Seek to a matching journal entry nearest to `monotonic` time.

        Argument `monotonic` is a timestamp from boot in either
        seconds or a datetime.timedelta instance. Argument `bootid`
        is a string or UUID representing which boot the monotonic time
        is reference to. Defaults to current bootid.
        i@B )rX   r   r    Ztotalsecondsr'   r!   r"   hexr?   r>   seek_monotonic)rJ   Z	monotonicbootid)rN   r$   r%   rs     s    	zReader.seek_monotonicc             C   s^   d | k o d k n rN x; t  | d  D] } |  j d d |  q- Wn t d   d S)zASet maximum log `level` by setting matches for PRIORITY.
        r      r   r6   z%dz!Log level must be 0 <= level <= 7N)rangerd   rP   )rJ   levelir$   r$   r%   	log_level,  s    zReader.log_levelc             C   s/   t  | t j  r | j } |  j d |  d S)a  Add match for log entries with specified `messageid`.

        `messageid` can be string of hexadicimal digits or a UUID
        instance. Standard message IDs can be found in systemd.id128.

        Equivalent to add_match(MESSAGE_ID=`messageid`).
        r3   N)rX   r!   r"   rr   rd   )rJ   Z	messageidr$   r$   r%   messageid_match5  s    	zReader.messageid_matchc             C   sD   | d k r t  j   j } n t | d |  } |  j d |  d S)zAdd match for _BOOT_ID equal to current boot ID or the specified
        boot ID.

        If specified, bootid should be either a UUID or a 32 digit hex
        number.

        Equivalent to add_match(_BOOT_ID='bootid').
        Nrr   r5   )_id128Zget_bootrr   getattrrd   )rJ   rt   r$   r$   r%   	this_bootA  s    	zReader.this_bootc             C   sD   | d k r t  j   j } n t | d |  } |  j d |  d S)zAdd match for _MACHINE_ID equal to the ID of this machine.

        If specified, machineid should be either a UUID or a 32 digit
        hex number.

        Equivalent to add_match(_MACHINE_ID='machineid').
        Nrr   r4   )r{   Zget_machinerr   r|   rd   )rJ   Z	machineidr$   r$   r%   this_machineP  s    zReader.this_machine)r   )__name__
__module____qualname____doc__r@   rS   r\   r]   r`   rA   rB   nextrd   r^   rj   rl   rn   rq   rs   ry   rz   r}   r~   r$   r$   )rN   r%   r>   l   s&   %


	r>   c             C   s%   t  |  t j  r |  j }  t |   S)N)rX   r!   r"   rr   r   )midr$   r$   r%   get_catalog_  s    	r   c             C   sU   t  | t  r$ |  j d  d | St  | t  rE |  d t |  S|  d | Sd  S)Nzutf-8   ==)rX   r   encoder'   str)rk   rR   r$   r$   r%   ra   d  s
    ra   c             K   s  d |  g } | d k	 r< t  | d |  } | j d |  | | k o^ | k o^ d k n r t j d d  d d d  \ } } } | d k	 r | j d	 |  | d k	 r | j d
 j |   | d k	 r | j d |  | j d d   | j   D  t |   S)aI  Send a message to the journal.

    >>> from systemd import journal
    >>> journal.send('Hello world')
    >>> journal.send('Hello, again, world', FIELD2='Greetings!')
    >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')

    Value of the MESSAGE argument will be used for the MESSAGE=
    field. MESSAGE must be a string and will be sent as UTF-8 to the
    journal.

    MESSAGE_ID can be given to uniquely identify the type of
    message. It must be a string or a uuid.UUID object.

    CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to identify
    the caller. Unless at least on of the three is given, values are
    extracted from the stack frame of the caller of send(). CODE_FILE
    and CODE_FUNC must be strings, CODE_LINE must be an integer.

    Additional fields for the journal entry can only be specified as
    keyword arguments. The payload can be either a string or bytes. A
    string will be sent as UTF-8, and bytes will be sent as-is to the
    journal.

    Other useful fields include PRIORITY, SYSLOG_FACILITY,
    SYSLOG_IDENTIFIER, SYSLOG_PID.
    zMESSAGE=Nrr   zMESSAGE_ID=limit   r   r   z
CODE_FILE=zCODE_LINE={:d}z
CODE_FUNC=c             s   s$   |  ] \ } } t  | |  Vq d  S)N)ra   )rT   rQ   rU   r$   r$   r%   rb     s    zsend.<locals>.<genexpr>)r|   rF   
_tracebackextract_stackformatrc   rW   r   )ZMESSAGEr3   	CODE_FILEr7   	CODE_FUNCrf   re   idr$   r$   r%   sendl  s    ') r   Fc             C   s%   t  |  | |  } t j | d d  S)a  Return a file object wrapping a stream to journal.

    Log messages written to this file as simple newline sepearted text
    strings are written to the journal.

    The file will be line buffered, so messages are actually sent
    after a newline character is written.

    >>> from systemd import journal
    >>> stream = journal.stream('myapp')
    >>> res = stream.write('message...\n')

    will produce the following message in the journal::

    PRIORITY=7
    SYSLOG_IDENTIFIER=myapp
    MESSAGE=message...

    Using the interface with print might be more convinient:

    >>> from __future__ import print_function
    >>> print('message...', file=stream)                 # doctest: +SKIP

    priority is the syslog priority, one of `LOG_EMERG`,
    `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`,
    `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`.

    level_prefix is a boolean. If true, kernel-style log priority
    level prefixes (such as '<1>') are interpreted. See
    sd-daemon(3) for more information.
    wr   )r   _osfdopen)Z
identifierZpriorityZlevel_prefixfdr$   r$   r%   stream  s    !r   c                   sL   e  Z d  Z d Z e j   f d d  Z d d   Z e d d    Z	   S)JournalHandlera5  Journal handler class for the Python logging framework.

    Please see the Python logging module documentation for an
    overview: http://docs.python.org/library/logging.html.

    To create a custom logger whose messages go only to journal:

    >>> import logging
    >>> log = logging.getLogger('custom_logger_name')
    >>> log.propagate = False
    >>> log.addHandler(JournalHandler())
    >>> log.warn("Some message: %s", 'detail')

    Note that by default, message levels `INFO` and `DEBUG` are
    ignored by the logging framework. To enable those log levels:

    >>> log.setLevel(logging.DEBUG)

    To redirect all logging messages to journal regardless of where
    they come from, attach it to the root logger:

    >>> logging.root.addHandler(JournalHandler())

    For more complex configurations when using `dictConfig` or
    `fileConfig`, specify `systemd.journal.JournalHandler` as the
    handler class.  Only standard handler configuration options
    are supported: `level`, `formatter`, `filters`.

    To attach journal MESSAGE_ID, an extra field is supported:

    >>> import uuid
    >>> mid = uuid.UUID('0123456789ABCDEF0123456789ABCDEF')
    >>> log.warn("Message with ID", extra={'MESSAGE_ID': mid})

    Fields to be attached to all messages sent through this handler
    can be specified as keyword arguments. This probably makes sense
    only for SYSLOG_IDENTIFIER and similar fields which are constant
    for the whole program:

    >>> JournalHandler(SYSLOG_IDENTIFIER='my-cool-app')
    <systemd.journal.JournalHandler object at ...>

    The following journal fields will be sent: `MESSAGE`, `PRIORITY`,
    `THREAD_NAME`, `CODE_FILE`, `CODE_LINE`, `CODE_FUNC`, `LOGGER`
    (name as supplied to getLogger call), `MESSAGE_ID` (optional, see
    above), `SYSLOG_IDENTIFIER` (defaults to sys.argv[0]).
    c                sm   t  t |   j |  x* | D]" } t |  s t d |   q Wd | k r` t j d | d <| |  _ d  S)NzInvalid field name: ZSYSLOG_IDENTIFIERr   )r?   r   r@   r=   rP   rA   argv_extra)rJ   rw   rf   name)rN   r$   r%   r@     s    zJournalHandler.__init__c             C   s   y |  j  |  } |  j | j  } t | d d  } t | d | d t  |  d | j d | j d | j d | j d | j	 |  j
 Wn t k
 r |  j |  Yn Xd S)	a  Write record as journal event.

        MESSAGE is taken from the message provided by the user, and
        PRIORITY, LOGGER, THREAD_NAME, CODE_{FILE,LINE,FUNC} fields
        are appended automatically. In addition, record.MESSAGE_ID
        will be used if present.
        r3   Nr6   ZLOGGERZTHREAD_NAMEr   r7   r   )r   mapPrioritylevelnor|   r   r   Z
threadNamepathnamelinenoZfuncNamer   	ExceptionZhandleError)rJ   recordmsgZprir   r$   r$   r%   emit  s    					zJournalHandler.emitc             C   sg   |  t  j k r t S|  t  j k r& t S|  t  j k r9 t S|  t  j k rL t S|  t  j	 k r_ t
 St Sd S)zMap logging levels to journald priorities.

        Since Python log level numbers are "sparse", we have to map
        numbers in between the standard levels too.
        N)_loggingDEBUGr   INFOr   ZWARNINGr	   ZERRORr   ZCRITICALr   r   )r   r$   r$   r%   r     s    zJournalHandler.mapPriority)
r   r   r   r   r   ZNOTSETr@   r   staticmethodr   r$   r$   )rN   r%   r     s   /
r   )r   r   )r   )r   )CZ
__future__r   sysrA   r*   r   Zuuidr!   	tracebackr   osr   Zloggingr   rB   collectionsr   rC   Zsyslogr   r   r   r   r	   r
   r   r   Z_journalr   r   r   Z_readerr   r   r   r   r   r   r   r   r   r    r   r{   r   tupler&   r)   r-   r.   r0   r2   r"   r'   r   rG   r;   r<   r=   r>   r   ra   r   r   ZHandlerr   r$   r$   r$   r%   <module>   s   :F	0$