3 XV"@sddlmZddlZddlZddlZddlZ ddl Z ddl Z ddlmZmZmZmZmZmZmZmZejd(krzddlmZddlmZmZmZddlm 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 Z0d dZ1ddZ2ddZ3ddZ4ejd*kr(ddZ5nej6Z5e5e5e5e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e3e2e1e0e4e8e7e7e7e7e7e3d!Z9e:dZ;ddZdd 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_DEBUG)ChainMap) __version__sendv stream_fd) _ReaderNOPAPPEND INVALIDATE LOCAL_ONLY RUNTIME_ONLYSYSTEM SYSTEM_ONLY CURRENT_USEROS_ROOT _get_catalog)id128) MonotoniccCs$ttj|ddtj|ddfS)Nr) microsecondsr )bytes)r _datetime timedelta_uuidUUID)mr%/usr/lib64/python3.6/journal.py_convert_monotonic0sr'cCstjt|dS)N)r)r r!int)sr%r%r&_convert_source_monotonic5sr*cCstjj|dS)Ni@B)r datetime fromtimestamp)tr%r%r&_convert_realtime9sr.cCstjjt|dS)Ni@B)r r+r,r()r)r%r%r&_convert_timestamp=sr/cCs|S)Nr%)xr%r%r&_convert_trivialAsr1cCstj|jS)N)r"r#decode)r)r%r%r& _convert_uuidEsr3)! 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 S)N)set_IDENT_CHARACTER)r)r%r%r&_valid_field_nameqsr>cseZdZdZd%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|dkr"|dkr|dkrt}nd}tt|j|||tjdkrnt|_|dk r^|jjj ||jjj t nt j |_|dk r|jj |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 )r r ) rsuperr?__init___sys version_info _ChainMap convertersmapsappendDEFAULT_CONVERTERScopyupdate)selfflagspathfilesrE) __class__r%r&rAs  zReader.__init__c Cs2|jj|tj}y||Stk r,|SXdS)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)rEgetrr2 ValueError)rKkeyvalueZconvertr%r%r&_convert_fields zReader._convert_fieldcsRi}xH|jD]<\}t|tr:fdd|D|<qj||<qW|S)z6Convert entire journal entry utilising _convert_field.csg|]}j|qSr%)rT).0val)rRrKr%r& sz)Reader._convert_entry..)items isinstancelistrT)rKentryresultrSr%)rRrKr&_convert_entrys  zReader._convert_entrycCs|S)z=Return self. Part of the iterator protocol. r%)rKr%r%r&__iter__szReader.__iter__cCs|j}|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)rKZansr%r%r&__next__szReader.__next__r csBt|}|jdd|jDx|D]}tt|j|q&WdS)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||VqdS)N) _make_line)rUrRrVr%r%r& sz#Reader.add_match..N)rZextendrXr@r? add_match)rKargskwargsarg)rOr%r&res zReader.add_matchr csVtt|j|rPtt|j}|rP|j|d<|j|d<|j|d<|j|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. r9r:r;) r@r?Z_nextZ_get_allZ _get_realtimeZ_get_monotonicZ _get_cursorr]dict)rKskipr[)rOr%r&r_s     zReader.get_nextcCs |j| 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. )r_)rKrjr%r%r& get_previous szReader.get_previouscs$tfddttjDS)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|]}j|VqdS)N)rT)rUrS)fieldrKr%r&rc$sz&Reader.query_unique..)r<r@r? query_unique)rKrl)rO)rlrKr&rms zReader.query_uniquecs(|dkr dn t|d}tt|j|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 i@B)r(r@r?wait)rKZtimeoutus)rOr%r&ro's z Reader.waitcsJt|tjr$tt|jdd}nt|ts:t|d}tt|j|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.%fi@B) rYr r+r(floatZstrftimer@r? seek_realtime)rKZrealtime)rOr%r&rr4s    zReader.seek_realtimecsDt|tjr|j}t|d}t|tjr2|j}tt |j ||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. i@B) rYr r!Z total_secondsr(r"r#hexr@r?seek_monotonic)rKZ monotonicbootid)rOr%r&rtIs    zReader.seek_monotoniccCsLd|kodknr@x.t|dD]}|jd|dq&WntddS)zASet maximum log `level` by setting matches for PRIORITY. rr z%d)r7z!Log level must be 0 <= level <= 7N)rangererQ)rKlevelir%r%r& log_levelXszReader.log_levelcCs"t|tjr|j}|j|ddS)aAdd 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`). )r4N)rYr"r#rsre)rKZ messageidr%r%r&messageid_matchas zReader.messageid_matchcCs0|dkrtjj}n t|d|}|j|ddS)zAdd match for _BOOT_ID for current boot 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'). Nrs)r6)_id128Zget_bootrsgetattrre)rKrur%r%r& this_bootms  zReader.this_bootcCs0|dkrtjj}n t|d|}|j|ddS)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'). Nrs)r5)r|Z get_machinersr}re)rKZ machineidr%r%r& this_machinezs  zReader.this_machine)NNNN)r )r )r )N)N)N)N)__name__ __module__ __qualname____doc__rArTr]r^rarBrCnextrer_rkrmrorrrtrzr{r~r __classcell__r%r%)rOr&r?us&*        r?cCst|tjr|j}t|S)zlReturn catalog entry for the specified ID. `mid` should be either a UUID or a 32 digit hex number. )rYr"r#rsr)Zmidr%r%r& get_catalogs rcCsFt|tr|jdd|St|tr2|d|S|dt|SdS)Nzutf-8==)rYrencodestr)rlrSr%r%r&rbs    rbcKsd|g}|dk r,t|d|}|jd|||koH|koHdknrltjddddd\}}}|dk r|jd ||dk r|jd j||dk r|jd ||jd d |jDt|S)aASend 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. zMESSAGE=Nrsz MESSAGE_ID=)limitrr z CODE_FILE=zCODE_LINE={:d}z CODE_FUNC=css|]\}}t||VqdS)N)rb)rUrRrVr%r%r&rcszsend..)r}rG _traceback extract_stackformatrdrXr)ZMESSAGEr4 CODE_FILEr8 CODE_FUNCrgrfidr%r%r&sends  "rFcCsT|dkr:tj s*tjd s*tjddkr0d}n tjd}t|||}tj|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-cpythonwr )rBargvr_osfdopen)Z identifierZpriorityZ 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 sXtt|j|x |D]}t|std|qWd|krHtjd|d<||_||_dS)NzInvalid field name: ZSYSLOG_IDENTIFIERr) r@rrAr>rQrBrr_extra)rKrxZsender_functionrgname)rOr%r&rA,s zJournalHandler.__init__cCsy|j|}|j|j}|jj}|jr2|j|d<|jrB|j|d<|jrVt|j|d<|j |j |j |ft||j |j |j|j|j|jd|Wntk r|j|YnXdS)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)r7ZLOGGERZ THREAD_NAMEZ PROCESS_NAMErr8rN)r map_prioritylevelnorrIZexc_textexc_inforfrrJ__dict__rrZ threadNameZ processNamepathnamelinenoZfuncName ExceptionZ handleError)rKrecordmsgZpriZextrasr%r%r&emit8s,       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) rrrrrZNOTSETrrAr staticmethodrZ mapPriorityrr%r%)rOr&rs 2 & r)r r )r )r )NNNN)DZ __future__rsysrBr+r Zuuidr" tracebackrosrZloggingrZsyslogrrrrrrr r rC collectionsr rDZ_journalrrrZ_readerrrrrrrrrrrrrr|rtupler'r*r.r/r1r3r#r(rrHr<r=r>r?rrbrrZHandlerrr%r%r%r&s (  4       /,