a XV"@sddlmZddlZddlZddlZddlZ ddl Z ddl Z ddlmZmZmZmZmZmZmZmZejdkrzddlmZddlmZmZmZddlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*dd l+m,Z-ejd krdd lm.Z.ne/Z.d d Z0ddZ1ddZ2ddZ3ddZ4ejd kr(ddZ5nej6Z5e5e5e5e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e3e2e1e0e4e8e7e7e7e7e7e3d!Z9e:dZ;ddZd d!Z?d)d"d#Z@ded$fd%d&ZAGd'd(d(e jBZCdS)*)divisionN) LOG_EMERG LOG_ALERTLOG_CRITLOG_ERR LOG_WARNING LOG_NOTICELOG_INFO LOG_DEBUGr )ChainMap) __version__sendv stream_fd) _ReaderNOPAPPEND INVALIDATE LOCAL_ONLY RUNTIME_ONLYSYSTEM SYSTEM_ONLY CURRENT_USEROS_ROOT _get_catalog)id128r ) MonotoniccCs$ttj|ddtj|ddfS)NrZ microsecondsr)bytes)r _datetime timedelta_uuidUUID)mr'5/usr/lib64/python3.9/site-packages/systemd/journal.py_convert_monotonic0sr)cCstjt|dS)Nr )r"r#intsr'r'r(_convert_source_monotonic5sr-cCstj|dSN@B)r"datetime fromtimestamp)tr'r'r(_convert_realtime9sr3cCstjt|dSr.)r"r0r1r*r+r'r'r(_convert_timestamp=sr4cCs|SNr')xr'r'r(_convert_trivialAsr7cCst|Sr5)r$r%decoder+r'r'r( _convert_uuidEsr9)! MESSAGE_ID _MACHINE_ID_BOOT_IDPRIORITYZLEADERZ SESSION_IDZUSERSPACE_USECZ INITRD_USECZ KERNEL_USECZ_UIDZ_GIDZ_PIDZSYSLOG_FACILITYZ SYSLOG_PIDZ_AUDIT_SESSIONZ_AUDIT_LOGINUIDZ_SYSTEMD_SESSIONZ_SYSTEMD_OWNER_UID CODE_LINEZERRNOZ EXIT_STATUSZ_SOURCE_REALTIME_TIMESTAMP__REALTIME_TIMESTAMPZ_SOURCE_MONOTONIC_TIMESTAMP__MONOTONIC_TIMESTAMP__CURSORZCOREDUMPZ COREDUMP_PIDZ COREDUMP_UIDZ COREDUMP_GIDZCOREDUMP_SESSIONZCOREDUMP_SIGNALZCOREDUMP_TIMESTAMPZ%ABCDEFGHIJKLMNOPQRTSUVWXYZ_0123456789cCst|t Sr5)set_IDENT_CHARACTERr+r'r'r(_valid_field_nameqsrDcseZdZdZd%fdd ZddZddZd d Zd d Ze j d krHeZ fddZ d&fdd Z d'ddZfddZd(fdd ZfddZd)fdd ZddZdd Zd*d!d"Zd+d#d$ZZS),ReaderaAccess systemd journal entries. Entries are subject to filtering and limits, see `add_match`, `this_boot`, `this_machine` functions and the `data_treshold` attribute. Note that in order to access the system journal, a non-root user must have the necessary privileges, see journalctl(1) for details. Unprivileged users can access only their own journal. 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. Ncs|dur"|dur|durt}nd}tt||||tjdkrnt|_|dur^|jj ||jj t nt |_|dur|j |dS)aCreate a new Reader. Argument `flags` defines the 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, either a file system path or a file descriptor. Note that `flags`, `path`, and `files` 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. Nrr ) rsuperrE__init___sys version_info _ChainMap convertersmapsappendDEFAULT_CONVERTERScopyupdate)selfflagspathfilesrK __class__r'r(rGs  zReader.__init__cCs6|j|tj}z ||WSty0|YS0dS)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)rKgetr!r8 ValueError)rQkeyvalueZconvertr'r'r(_convert_fields   zReader._convert_fieldcsNi}|D]<\}t|tr8fdd|D|<q ||<q |S)z6Convert entire journal entry utilising _convert_field.csg|]}|qSr'r[).0valrYrQr'r( z)Reader._convert_entry..)items isinstancelistr[)rQentryresultrZr'r_r(_convert_entrys  zReader._convert_entrycCs|S)z=Return self. Part of the iterator protocol. r')rQr'r'r(__iter__szReader.__iter__cCs|}|r|StdS)zReturn the next entry in the journal. Returns self.get_next() or raises StopIteration. Part of the iterator protocol. N)get_next StopIteration)rQZansr'r'r(__next__szReader.__next__rcs>t|}|dd|D|D]}tt||q$dS)aHAdd one or more matches to the filter journal log entries. All matches of different field are combined with logical AND, and matches of the same field are automatically combined with logical OR. Matches can be passed as strings of form "FIELD=value", or keyword arguments FIELD="value". css|]\}}t||VqdSr5 _make_liner]rYr^r'r'r( raz#Reader.add_match..N)rdextendrbrFrE add_match)rQargskwargsargrUr'r(rqszReader.add_matchrcsVtt||rPtt|}|rP||d<||d<||d<||StS)aReturn the next log entry as a dictionary. Entries will be processed with converters specified during Reader creation. Optional `skip` value will return the `skip`-th log entry. Currently a standard dictionary of fields is returned, but in the future this might be changed to a different mapping type, so the calling code should not make assumptions about a specific type. r?r@rA) rFrEZ_nextZ_get_allZ _get_realtimeZ_get_monotonicZ _get_cursorrgdict)rQskiprerUr'r(ris     zReader.get_nextcCs || S)aReturn the previous log entry. Equivalent to get_next(-skip). Optional `skip` value will return the -`skip`-th log entry. Entries will be processed with converters specified during Reader creation. Currently a standard dictionary of fields is returned, but in the future this might be changed to a different mapping type, so the calling code should not make assumptions about a specific type. )ri)rQrvr'r'r( get_previous szReader.get_previouscs$tfddttDS)zReturn a list of unique values appearing in the journal for the given `field`. Note this does not respect any journal matches. Entries will be processed with converters specified during Reader creation. c3s|]}|VqdSr5r\)r]rZfieldrQr'r(ro$sz&Reader.query_unique..)rBrFrE query_unique)rQryrUrxr(rzs zReader.query_uniquecs(|dur dn t|d}tt||S)aEWait for a change in the journal. `timeout` is the maximum time in seconds to wait, or None which means 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/)r*rFrEwait)rQtimeoutusrUr'r(r|'s z Reader.waitcsJt|tjr$tt|dd}nt|ts:t|d}tt||S)a(Seek to a matching journal entry nearest to `timestamp` time. Argument `realtime` must be either an integer UNIX timestamp (in microseconds since the beginning of the UNIX epoch), or an float UNIX timestamp (in seconds since the beginning of the UNIX epoch), or a datetime.datetime instance. The integer form is deprecated. >>> import time >>> from systemd import journal >>> yesterday = time.time() - 24 * 60**2 >>> j = journal.Reader() >>> j.seek_realtime(yesterday) z%s.%fr/) rcr"r0r*floatstrftimerFrE seek_realtime)rQZrealtimerUr'r(r4s    zReader.seek_realtimecsDt|tjr|}t|d}t|tjr2|j}tt | ||S)aGSeek 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. r/) rcr"r#Z total_secondsr*r$r%hexrFrEseek_monotonic)rQ monotonicbootidrUr'r(rIs    zReader.seek_monotoniccCsHd|krdkr>> 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. zMESSAGE=Nrz MESSAGE_ID=)limitrr z CODE_FILE=zCODE_LINE={:d}z CODE_FUNC=css|]\}}t||VqdSr5rlrnr'r'r(rorazsend..)rrM _traceback extract_stackformatrprbr)ZMESSAGEr: CODE_FILEr> CODE_FUNCrsrridr'r'r(sends  "rFcCsP|dur6tjr&tjdr&tjddkr,d}n tjd}t|||}t|ddS)aReturn 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') # doctest: +SKIP >>> res = stream.write('message...\n') # doctest: +SKIP will produce the following message in the journal:: PRIORITY=7 SYSLOG_IDENTIFIER=myapp MESSAGE=message... If identifier is None, a suitable default based on sys.argv[0] will be used. This interface can be used conveniently with the print function: >>> from __future__ import print_function >>> stream = journal.stream() # doctest: +SKIP >>> 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. Nrz-cZpythonwr)rHargvr_osfdopen)Z identifierpriorityZ level_prefixfdr'r'r(streams "  rcs@eZdZdZejeffdd ZddZe ddZ e Z Z S)JournalHandleraJournal 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.warning("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.warning("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') <...JournalHandler ...> 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]). The function used to actually send messages can be overridden using the `sender_function` parameter. c sTtt|||D]}t|std|qd|vrDtjd|d<||_||_dS)NzInvalid field name: ZSYSLOG_IDENTIFIERr) rFrrGrDrXrHrr_extra)rQrZsender_functionrsnamerUr'r(rG,szJournalHandler.__init__c Csz||}||j}|j}|jr2|j|d<|jrB|j|d<|jrVt|j|d<| |j |j |ft||j |j |j|j|j|jd|Wnty||Yn0dS)aWrite `record` as a 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. ZEXCEPTION_TEXTZEXCEPTION_INFOZ CODE_ARGS)r=ZLOGGERZ THREAD_NAMEZ PROCESS_NAMErr>rN)r map_prioritylevelnorrOZexc_textexc_inforrrrP__dict__rrZ threadNameZ processNamepathnamelinenoZfuncName ExceptionZ handleError)rQrecordmsgZpriextrasr'r'r(emit8s0       zJournalHandler.emitcCsN|tjkrtS|tjkrtS|tjkr*tS|tjkr8tS|tj krFt St SdS)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) _loggingDEBUGr INFOr ZWARNINGrZERRORrZCRITICALrr)rr'r'r(r^s     zJournalHandler.map_priority) rrrrrZNOTSETrrGr staticmethodrZ mapPriorityrr'r'rUr(rs 3 & r)NNNN)DZ __future__rsysrHr0r"Zuuidr$ tracebackrosrZloggingrZsyslogrrrrrrr r rI collectionsr rJZ_journalrrrZ_readerrrrrrrrrrrrrrrtupler)r-r3r4r7r9r%r*r!rNrBrCrDrErrmrrZHandlerrr'r'r'r(s (  4    $   0,