chiark / gitweb /
systemctl: try to reload daemon after enable/disable only when not running in a chroot
[elogind.git] / src / python-systemd / journal.py
1 #  -*- Mode: python; coding:utf-8; indent-tabs-mode: nil -*- */
2 #
3 #  This file is part of systemd.
4 #
5 #  Copyright 2012 David Strauss <david@davidstrauss.net>
6 #  Copyright 2012 Zbigniew JÄ™drzejewski-Szmek <zbyszek@in.waw.pl>
7 #  Copyright 2012 Marti Raudsepp <marti@juffo.org>
8 #
9 #  systemd is free software; you can redistribute it and/or modify it
10 #  under the terms of the GNU Lesser General Public License as published by
11 #  the Free Software Foundation; either version 2.1 of the License, or
12 #  (at your option) any later version.
13 #
14 #  systemd is distributed in the hope that it will be useful, but
15 #  WITHOUT ANY WARRANTY; without even the implied warranty of
16 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 #  Lesser General Public License for more details.
18 #
19 #  You should have received a copy of the GNU Lesser General Public License
20 #  along with systemd; If not, see <http://www.gnu.org/licenses/>.
21
22 from __future__ import division
23
24 import sys as _sys
25 import datetime as _datetime
26 import functools as _functools
27 import uuid as _uuid
28 import traceback as _traceback
29 import os as _os
30 from os import SEEK_SET, SEEK_CUR, SEEK_END
31 import logging as _logging
32 if _sys.version_info >= (3,):
33     from collections import ChainMap as _ChainMap
34 from syslog import (LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,
35                     LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG)
36 from ._journal import sendv, stream_fd
37 from ._reader import (_Reader, NOP, APPEND, INVALIDATE,
38                       LOCAL_ONLY, RUNTIME_ONLY, SYSTEM_ONLY)
39 from . import id128 as _id128
40
41 if _sys.version_info >= (3,):
42     from ._reader import Monotonic
43 else:
44     Monotonic = tuple
45
46 _MONOTONIC_CONVERTER = lambda p: Monotonic((_datetime.timedelta(microseconds=p[0]),
47                                             _uuid.UUID(bytes=p[1])))
48 _REALTIME_CONVERTER = lambda x: _datetime.datetime.fromtimestamp(x / 1E6)
49 DEFAULT_CONVERTERS = {
50     'MESSAGE_ID': _uuid.UUID,
51     '_MACHINE_ID': _uuid.UUID,
52     '_BOOT_ID': _uuid.UUID,
53     'PRIORITY': int,
54     'LEADER': int,
55     'SESSION_ID': int,
56     'USERSPACE_USEC': int,
57     'INITRD_USEC': int,
58     'KERNEL_USEC': int,
59     '_UID': int,
60     '_GID': int,
61     '_PID': int,
62     'SYSLOG_FACILITY': int,
63     'SYSLOG_PID': int,
64     '_AUDIT_SESSION': int,
65     '_AUDIT_LOGINUID': int,
66     '_SYSTEMD_SESSION': int,
67     '_SYSTEMD_OWNER_UID': int,
68     'CODE_LINE': int,
69     'ERRNO': int,
70     'EXIT_STATUS': int,
71     '_SOURCE_REALTIME_TIMESTAMP': _REALTIME_CONVERTER,
72     '__REALTIME_TIMESTAMP': _REALTIME_CONVERTER,
73     '_SOURCE_MONOTONIC_TIMESTAMP': _MONOTONIC_CONVERTER,
74     '__MONOTONIC_TIMESTAMP': _MONOTONIC_CONVERTER,
75     'COREDUMP': bytes,
76     'COREDUMP_PID': int,
77     'COREDUMP_UID': int,
78     'COREDUMP_GID': int,
79     'COREDUMP_SESSION': int,
80     'COREDUMP_SIGNAL': int,
81     'COREDUMP_TIMESTAMP': _REALTIME_CONVERTER,
82 }
83
84 if _sys.version_info >= (3,):
85     _convert_unicode = _functools.partial(str, encoding='utf-8')
86 else:
87     _convert_unicode = _functools.partial(unicode, encoding='utf-8')
88
89 class Reader(_Reader):
90     """Reader allows the access and filtering of systemd journal
91     entries. Note that in order to access the system journal, a
92     non-root user must be in the `adm` group.
93
94     Example usage to print out all error or higher level messages
95     for systemd-udevd for the boot:
96
97     >>> myjournal = journal.Reader()
98     >>> myjournal.add_boot_match(journal.CURRENT_BOOT)
99     >>> myjournal.add_loglevel_matches(journal.LOG_ERR)
100     >>> myjournal.add_match(_SYSTEMD_UNIT="systemd-udevd.service")
101     >>> for entry in myjournal:
102     ...    print(entry['MESSAGE'])
103
104     See systemd.journal-fields(7) for more info on typical fields
105     found in the journal.
106     """
107     def __init__(self, converters=None, flags=LOCAL_ONLY, path=None):
108         """Create an instance of Reader, which allows filtering and
109         return of journal entries.
110         Argument `converters` is a dictionary which updates the
111         DEFAULT_CONVERTERS to convert journal field values.
112         Argument `flags` sets open flags of the journal, which can be one
113         of, or ORed combination of constants: LOCAL_ONLY (default) opens
114         journal on local machine only; RUNTIME_ONLY opens only
115         volatile journal files; and SYSTEM_ONLY opens only
116         journal files of system services and the kernel.
117         Argument `path` is the directory of journal files. Note that
118         currently flags are ignored when `path` is present as they are
119         currently not relevant.
120         """
121         super(Reader, self).__init__(flags, path)
122         if _sys.version_info >= (3,3):
123             self.converters = _ChainMap()
124             if converters is not None:
125                 self.converters.maps.append(converters)
126             self.converters.maps.append(DEFAULT_CONVERTERS)
127         else:
128             self.converters = DEFAULT_CONVERTERS.copy()
129             if converters is not None:
130                 self.converters.update(converters)
131
132     def _convert_field(self, key, value):
133         """Convert value based on callable from self.converters
134         based of field/key"""
135         try:
136             result = self.converters[key](value)
137         except:
138             # Default conversion in unicode
139             try:
140                 result = _convert_unicode(value)
141             except UnicodeDecodeError:
142                 # Leave in default bytes
143                 result = value
144         return result
145
146     def _convert_entry(self, entry):
147         """Convert entire journal entry utilising _covert_field"""
148         result = {}
149         for key, value in entry.items():
150             if isinstance(value, list):
151                 result[key] = [self._convert_field(key, val) for val in value]
152             else:
153                 result[key] = self._convert_field(key, value)
154         return result
155
156     def add_match(self, *args, **kwargs):
157         """Add one or more matches to the filter journal log entries.
158         All matches of different field are combined in a logical AND,
159         and matches of the same field are automatically combined in a
160         logical OR.
161         Matches can be passed as strings of form "FIELD=value", or
162         keyword arguments FIELD="value".
163         """
164         args = list(args)
165         args.extend(_make_line(key, val) for key, val in kwargs.items())
166         for arg in args:
167             super(Reader, self).add_match(arg)
168
169     def get_next(self, skip=1):
170         """Return the next log entry as a dictionary of fields.
171
172         Optional skip value will return the `skip`\-th log entry.
173
174         Entries will be processed with converters specified during
175         Reader creation.
176         """
177         return self._convert_entry(
178             super(Reader, self).get_next(skip))
179
180     def query_unique(self, field):
181         """Return unique values appearing in the journal for given `field`.
182
183         Note this does not respect any journal matches.
184
185         Entries will be processed with converters specified during
186         Reader creation.
187         """
188         return set(self._convert_field(field, value)
189             for value in super(Reader, self).query_unique(field))
190
191     def seek_realtime(self, realtime):
192         """Seek to a matching journal entry nearest to `realtime` time.
193
194         Argument `realtime` must be either an integer unix timestamp
195         or datetime.datetime instance.
196         """
197         if isinstance(realtime, _datetime.datetime):
198             realtime = float(realtime.strftime("%s.%f"))
199         return super(Reader, self).seek_realtime(realtime)
200
201     def seek_monotonic(self, monotonic, bootid=None):
202         """Seek to a matching journal entry nearest to `monotonic` time.
203
204         Argument `monotonic` is a timestamp from boot in either
205         seconds or a datetime.timedelta instance. Argument `bootid`
206         is a string or UUID representing which boot the monotonic time
207         is reference to. Defaults to current bootid.
208         """
209         if isinstance(monotonic, _datetime.timedelta):
210             monotonic = monotonic.totalseconds()
211         if isinstance(bootid, _uuid.UUID):
212             bootid = bootid.get_hex()
213         return super(Reader, self).seek_monotonic(monotonic, bootid)
214
215     def log_level(self, level):
216         """Set maximum log `level` by setting matches for PRIORITY.
217         """
218         if 0 <= level <= 7:
219             for i in range(level+1):
220                 self.add_match(PRIORITY="%s" % i)
221         else:
222             raise ValueError("Log level must be 0 <= level <= 7")
223
224     def messageid_match(self, messageid):
225         """Add match for log entries with specified `messageid`.
226
227         `messageid` can be string of hexadicimal digits or a UUID
228         instance. Standard message IDs can be found in systemd.id128.
229
230         Equivalent to add_match(MESSAGE_ID=`messageid`).
231         """
232         if isinstance(messageid, _uuid.UUID):
233             messageid = messageid.get_hex()
234         self.add_match(MESSAGE_ID=messageid)
235
236     def this_boot(self, bootid=None):
237         """Add match for _BOOT_ID equal to current boot ID or the specified boot ID.
238
239         If specified, bootid should be either a UUID or a 32 digit hex number.
240
241         Equivalent to add_match(_BOOT_ID='bootid').
242         """
243         if bootid is None:
244             bootid = _id128.get_boot().hex
245         else:
246             bootid = getattr(bootid, 'hex', bootid)
247         self.add_match(_BOOT_ID=bootid)
248
249     def this_machine(self, machineid=None):
250         """Add match for _MACHINE_ID equal to the ID of this machine.
251
252         If specified, machineid should be either a UUID or a 32 digit hex number.
253
254         Equivalent to add_match(_MACHINE_ID='machineid').
255         """
256         if machineid is None:
257             machineid = _id128.get_machine().hex
258         else:
259             machineid = getattr(machineid, 'hex', machineid)
260         self.add_match(_MACHINE_ID=machineid)
261
262
263 def _make_line(field, value):
264         if isinstance(value, bytes):
265                 return field.encode('utf-8') + b'=' + value
266         else:
267                 return field + '=' + value
268
269 def send(MESSAGE, MESSAGE_ID=None,
270          CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
271          **kwargs):
272         r"""Send a message to the journal.
273
274         >>> journal.send('Hello world')
275         >>> journal.send('Hello, again, world', FIELD2='Greetings!')
276         >>> journal.send('Binary message', BINARY=b'\xde\xad\xbe\xef')
277
278         Value of the MESSAGE argument will be used for the MESSAGE=
279         field. MESSAGE must be a string and will be sent as UTF-8 to
280         the journal.
281
282         MESSAGE_ID can be given to uniquely identify the type of
283         message. It must be a string or a uuid.UUID object.
284
285         CODE_LINE, CODE_FILE, and CODE_FUNC can be specified to
286         identify the caller. Unless at least on of the three is given,
287         values are extracted from the stack frame of the caller of
288         send(). CODE_FILE and CODE_FUNC must be strings, CODE_LINE
289         must be an integer.
290
291         Additional fields for the journal entry can only be specified
292         as keyword arguments. The payload can be either a string or
293         bytes. A string will be sent as UTF-8, and bytes will be sent
294         as-is to the journal.
295
296         Other useful fields include PRIORITY, SYSLOG_FACILITY,
297         SYSLOG_IDENTIFIER, SYSLOG_PID.
298         """
299
300         args = ['MESSAGE=' + MESSAGE]
301
302         if MESSAGE_ID is not None:
303                 id = getattr(MESSAGE_ID, 'hex', MESSAGE_ID)
304                 args.append('MESSAGE_ID=' + id)
305
306         if CODE_LINE == CODE_FILE == CODE_FUNC == None:
307                 CODE_FILE, CODE_LINE, CODE_FUNC = \
308                         _traceback.extract_stack(limit=2)[0][:3]
309         if CODE_FILE is not None:
310                 args.append('CODE_FILE=' + CODE_FILE)
311         if CODE_LINE is not None:
312                 args.append('CODE_LINE={:d}'.format(CODE_LINE))
313         if CODE_FUNC is not None:
314                 args.append('CODE_FUNC=' + CODE_FUNC)
315
316         args.extend(_make_line(key, val) for key, val in kwargs.items())
317         return sendv(*args)
318
319 def stream(identifier, priority=LOG_DEBUG, level_prefix=False):
320         r"""Return a file object wrapping a stream to journal.
321
322         Log messages written to this file as simple newline sepearted
323         text strings are written to the journal.
324
325         The file will be line buffered, so messages are actually sent
326         after a newline character is written.
327
328         >>> stream = journal.stream('myapp')
329         >>> stream
330         <open file '<fdopen>', mode 'w' at 0x...>
331         >>> stream.write('message...\n')
332
333         will produce the following message in the journal::
334
335           PRIORITY=7
336           SYSLOG_IDENTIFIER=myapp
337           MESSAGE=message...
338
339         Using the interface with print might be more convinient:
340
341         >>> from __future__ import print_function
342         >>> print('message...', file=stream)
343
344         priority is the syslog priority, one of `LOG_EMERG`,
345         `LOG_ALERT`, `LOG_CRIT`, `LOG_ERR`, `LOG_WARNING`,
346         `LOG_NOTICE`, `LOG_INFO`, `LOG_DEBUG`.
347
348         level_prefix is a boolean. If true, kernel-style log priority
349         level prefixes (such as '<1>') are interpreted. See
350         sd-daemon(3) for more information.
351         """
352
353         fd = stream_fd(identifier, priority, level_prefix)
354         return _os.fdopen(fd, 'w', 1)
355
356 class JournalHandler(_logging.Handler):
357         """Journal handler class for the Python logging framework.
358
359         Please see the Python logging module documentation for an
360         overview: http://docs.python.org/library/logging.html.
361
362         To create a custom logger whose messages go only to journal:
363
364         >>> log = logging.getLogger('custom_logger_name')
365         >>> log.propagate = False
366         >>> log.addHandler(journal.JournalHandler())
367         >>> log.warn("Some message: %s", detail)
368
369         Note that by default, message levels `INFO` and `DEBUG` are
370         ignored by the logging framework. To enable those log levels:
371
372         >>> log.setLevel(logging.DEBUG)
373
374         To attach journal MESSAGE_ID, an extra field is supported:
375
376         >>> import uuid
377         >>> mid = uuid.UUID('0123456789ABCDEF0123456789ABCDEF')
378         >>> log.warn("Message with ID", extra={'MESSAGE_ID': mid})
379
380         To redirect all logging messages to journal regardless of where
381         they come from, attach it to the root logger:
382
383         >>> logging.root.addHandler(journal.JournalHandler())
384
385         For more complex configurations when using `dictConfig` or
386         `fileConfig`, specify `systemd.journal.JournalHandler` as the
387         handler class.  Only standard handler configuration options
388         are supported: `level`, `formatter`, `filters`.
389
390         The following journal fields will be sent:
391         `MESSAGE`, `PRIORITY`, `THREAD_NAME`, `CODE_FILE`, `CODE_LINE`,
392         `CODE_FUNC`, `LOGGER` (name as supplied to getLogger call),
393         `MESSAGE_ID` (optional, see above).
394         """
395
396         def emit(self, record):
397                 """Write record as journal event.
398
399                 MESSAGE is taken from the message provided by the
400                 user, and PRIORITY, LOGGER, THREAD_NAME,
401                 CODE_{FILE,LINE,FUNC} fields are appended
402                 automatically. In addition, record.MESSAGE_ID will be
403                 used if present.
404                 """
405                 try:
406                         msg = self.format(record)
407                         pri = self.mapPriority(record.levelno)
408                         mid = getattr(record, 'MESSAGE_ID', None)
409                         send(msg,
410                              MESSAGE_ID=mid,
411                              PRIORITY=format(pri),
412                              LOGGER=record.name,
413                              THREAD_NAME=record.threadName,
414                              CODE_FILE=record.pathname,
415                              CODE_LINE=record.lineno,
416                              CODE_FUNC=record.funcName)
417                 except Exception:
418                         self.handleError(record)
419
420         @staticmethod
421         def mapPriority(levelno):
422                 """Map logging levels to journald priorities.
423
424                 Since Python log level numbers are "sparse", we have
425                 to map numbers in between the standard levels too.
426                 """
427                 if levelno <= _logging.DEBUG:
428                         return LOG_DEBUG
429                 elif levelno <= _logging.INFO:
430                         return LOG_INFO
431                 elif levelno <= _logging.WARNING:
432                         return LOG_WARNING
433                 elif levelno <= _logging.ERROR:
434                         return LOG_ERR
435                 elif levelno <= _logging.CRITICAL:
436                         return LOG_CRIT
437                 else:
438                         return LOG_ALERT