Skip to main content

SystemD wrapper in Cython

Project description

Latest Version https://img.shields.io/pypi/wheel/cysystemd.svg https://img.shields.io/pypi/pyversions/cysystemd.svg https://img.shields.io/pypi/l/cysystemd.svg

Python systemd wrapper using Cython

Installation

All packages available on github releases.

Debian/Ubuntu

Install repository key

wget -qO - 'https://bintray.com/user/downloadSubjectPublicKey?username=bintray' | \
   apt-key add -

Install the repository file

Debian Jessie:

echo "deb http://dl.bintray.com/mosquito/cysystemd jessie main" > /etc/apt/sources.list.d/cysystemd.list
apt-get update
apt-get install python-cysystemd python3-cysystemd

Ubuntu Xenial:

echo "deb http://dl.bintray.com/mosquito/cysystemd xenial main" > /etc/apt/sources.list.d/cysystemd.list
apt-get update
apt-get install python-cysystemd python3-cysystemd

Ubuntu Bionic:

echo "deb http://dl.bintray.com/mosquito/cysystemd bionic main" > /etc/apt/sources.list.d/cysystemd.list
apt-get update
apt-get install python-cysystemd python3-cysystemd

Centos 7

yum localinstall \
   https://github.com/mosquito/cysystemd/releases/download/0.17.1/python-cysystemd-0.17.1-1.centos7.x86_64.rpm

Installation from sources

You should install systemd headers

For debian users:

apt-get install build-essential \
    libsystemd-journal-dev \
    libsystemd-daemon-dev \
    libsystemd-dev

For CentOS/RHEL

yum install gcc systemd-devel

And install it from pypi

pip install cysystemd

Usage examples

Writing to journald

Logging handler for python logger

from cysystemd import journal
import logging
import uuid

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
logger.addHandler(journal.JournaldLogHandler())

try:
    log.info("Trying to do something")
    raise Exception('foo')
except:
    logger.exception("Test Exception %s", 1)

Systemd daemon notification

from cysystemd.daemon import notify, Notification

# Send READY=1
notify(Notification.READY)

# Send status
notify(Notification.STATUS, "I'm fine.")

# Send stopping
notify(Notification.STOPPING)

Write message into Systemd journal

from cysystemd import journal


journal.write("Hello Lennart")

# Or send structured data
journal.send(
    message="Hello Lennart",
    priority=journal.Priority.INFO,
    some_field='some value',
)

Reading journald

Reading all systemd records

from cysystemd.reader import JournalReader, JournalOpenMode

journal_reader = JournalReader()
journal_reader.open(JournalOpenMode.SYSTEM)
journal_reader.seek_head()

for record in journal_reader:
   print(record.data['MESSAGE'])

Read only cron logs

from cysystemd.reader import JournalReader, JournalOpenMode, Rule


rules = (
   Rule("SYSLOG_IDENTIFIER", "CRON") &
   Rule("_SYSTEMD_UNIT", "crond.service") |
   Rule("_SYSTEMD_UNIT", "cron.service")
)

cron_reader = JournalReader()
cron_reader.open(JournalOpenMode.SYSTEM)
cron_reader.seek_head()
cron_reader.add_filter(rules)

for record in cron_reader:
   print(record.data['MESSAGE'])

Polling records

from cysystemd.reader import JournalReader, JournalOpenMode


reader = JournalReader()
reader.open(JournalOpenMode.SYSTEM)
reader.seek_tail()

poll_timeout = 255

while True:
   reader.wait(poll_timeout)

   for record in reader:
      print(record.data['MESSAGE'])

JournalD open modes

  • CURRENT_USER

  • LOCAL_ONLY

  • RUNTIME_ONLY

  • SYSTEM

  • SYSTEM_ONLY

from cysystemd.reader import JournalReader, JournalOpenMode

reader = JournalReader()
reader.open(JournalOpenMode.CURRENT_USER)

JournalD entry

JournalEntry class has some special properties and methods:

  • data - journal entry content (dict)

  • date - entry timestamp (datetime instance)

  • cursor - systemd identification bytes for this entry

  • boot_id() - returns bootid

  • get_realtime_sec() - entry epoch (float)

  • get_realtime_usec() - entry epoch (int microseconds)

  • get_monotonic_sec() - entry monotonic time (float)

  • get_monotonic_usec() - entry monotonic time (int microseconds)

  • __getitem__(key) - shoutcut for entry.data[key]

JournalD reader

JournalReader class has some special properties and methods:

  • open(flags=JournalOpenMode.CURRENT_USER) - opening journald with selected mode

  • open_directory(path) - opening journald from path

  • open_files(*filename) - opening journald from files

  • data_threshold - may be used to get or set the data field size threshold for data returned by fething entry data.

  • closed - returns True when journal reader closed

  • locked - returns True when journal reader locked

  • idle - returns True when journal reader opened

  • seek_head - move reader pointer to the first entry

  • seek_tail - move reader pointer to the last entry

  • seek_monotonic_usec - seeks to the entry with the specified monotonic timestamp, i.e. CLOCK_MONOTONIC. Since monotonic time restarts on every reboot a boot ID needs to be specified as well.

  • seek_realtime_usec - seeks to the entry with the specified realtime (wallclock) timestamp, i.e. CLOCK_REALTIME. Note that the realtime clock is not necessarily monotonic. If a realtime timestamp is ambiguous, it is not defined which position is sought to.

  • seek_cursor - seeks to the entry located at the specified cursor (see JournalEntry.cursor).

  • wait(timeout) - It will synchronously wait until the journal gets changed. The maximum time this call sleeps may be controlled with the timeout_usec parameter.

  • __iter__ - returns JournalReader object

  • __next__ - calls next() or raise StopIteration

  • next(skip=0) - returns the next JournalEntry. The skip parameter skips some entries.

  • previous(skip=0) - returns the previous JournalEntry. The skip parameter skips some entries.

  • skip_next(skip) - skips next entries.

  • skip_previous(skip) - skips next entries.

  • add_filter(rule) - adding filter rule. See read-only-cron-logs as example.

  • clear_filter - reset all filters

  • fd - returns a special file descriptor

  • events - returns EPOLL events

  • timeout - returns internal timeout

  • process_events() - After each poll() wake-up process_events() needs to be called to process events. This call will also indicate what kind of change has been detected.

  • get_catalog() - retrieves a message catalog entry for the current journal entry. This will look up an entry in the message catalog by using the “MESSAGE_ID=” field of the current journal entry. Before returning the entry all journal field names in the catalog entry text enclosed in “@” will be replaced by the respective field values of the current entry. If a field name referenced in the message catalog entry does not exist, in the current journal entry, the “@” will be removed, but the field name otherwise left untouched.

  • get_catalog_for_message_id(message_id: UUID) - works similar to get_catalog() but the entry is looked up by the specified message ID (no open journal context is necessary for this), and no field substitution is performed.

Asyncio support

Initial asyncio support for reading journal asynchronously.

AsyncJournalReader

Blocking methods were wrapped by threads. Method wait() use epoll on journald file descriptor.

import asyncio
import json

from cysystemd.reader import JournalOpenMode
from cysystemd.async_reader import AsyncJournalReader


async def main():
    reader = AsyncJournalReader()
    await reader.open(JournalOpenMode.SYSTEM)
    await reader.seek_tail()

    while await reader.wait():
        async for record in reader:
            print(
                json.dumps(
                    record.data,
                    indent=1,
                    sort_keys=True
                )
            )

if __name__ == '__main__':
    asyncio.run(main())

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cysystemd-1.4.5.tar.gz (195.8 kB view details)

Uploaded Source

Built Distributions

cysystemd-1.4.5-cp39-cp39-manylinux2014_x86_64.whl (1.7 MB view details)

Uploaded CPython 3.9

cysystemd-1.4.5-cp38-cp38-manylinux2014_x86_64.whl (1.6 MB view details)

Uploaded CPython 3.8

cysystemd-1.4.5-cp37-cp37m-manylinux2014_x86_64.whl (1.6 MB view details)

Uploaded CPython 3.7m

cysystemd-1.4.5-cp36-cp36m-manylinux2014_x86_64.whl (1.6 MB view details)

Uploaded CPython 3.6m

cysystemd-1.4.5-cp35-cp35m-manylinux2014_x86_64.whl (1.6 MB view details)

Uploaded CPython 3.5m

File details

Details for the file cysystemd-1.4.5.tar.gz.

File metadata

  • Download URL: cysystemd-1.4.5.tar.gz
  • Upload date:
  • Size: 195.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.3

File hashes

Hashes for cysystemd-1.4.5.tar.gz
Algorithm Hash digest
SHA256 1123561be2f176395ec6a68af8fc99f49ee82caecaab477336a2a2d1dcd6a7e7
MD5 712d393ca79247135b9eb038180fcaa5
BLAKE2b-256 c25e84b504bdafbe697aee4a32ee8233550e9ad45280871ffb7c4c24aded8e05

See more details on using hashes here.

File details

Details for the file cysystemd-1.4.5-cp39-cp39-manylinux2014_x86_64.whl.

File metadata

  • Download URL: cysystemd-1.4.5-cp39-cp39-manylinux2014_x86_64.whl
  • Upload date:
  • Size: 1.7 MB
  • Tags: CPython 3.9
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.3

File hashes

Hashes for cysystemd-1.4.5-cp39-cp39-manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 318265924bce1bb77b082b3ba917567ab827be238b89ea2cee55d83a68ee7d3f
MD5 94e094620d116bc1661549b96c1bf070
BLAKE2b-256 5923b6774715cc621805b061f76445c46eae81653215cee260387100f0136cc2

See more details on using hashes here.

File details

Details for the file cysystemd-1.4.5-cp38-cp38-manylinux2014_x86_64.whl.

File metadata

  • Download URL: cysystemd-1.4.5-cp38-cp38-manylinux2014_x86_64.whl
  • Upload date:
  • Size: 1.6 MB
  • Tags: CPython 3.8
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.3

File hashes

Hashes for cysystemd-1.4.5-cp38-cp38-manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 df0cab649ba8a5de44172bc8adaaa287458d3dec03e1eb0dbea14c95a51f3744
MD5 c3bb857477ee730132d7a1df12411406
BLAKE2b-256 d1653cb87e20690e8bc85992bff07b59e484303f95ebc4168a1bbf65d33ea3ac

See more details on using hashes here.

File details

Details for the file cysystemd-1.4.5-cp37-cp37m-manylinux2014_x86_64.whl.

File metadata

  • Download URL: cysystemd-1.4.5-cp37-cp37m-manylinux2014_x86_64.whl
  • Upload date:
  • Size: 1.6 MB
  • Tags: CPython 3.7m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.3

File hashes

Hashes for cysystemd-1.4.5-cp37-cp37m-manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 20185af2d2207258260db0dcaf3e164c398ee4977a9c082f026bd35865619fb3
MD5 c32177b40847dc85d1e53f75c4f8590e
BLAKE2b-256 0047bc985cd2d01541077ada16b4732d9843f50364e2bed9a3e0bee1520c2259

See more details on using hashes here.

File details

Details for the file cysystemd-1.4.5-cp36-cp36m-manylinux2014_x86_64.whl.

File metadata

  • Download URL: cysystemd-1.4.5-cp36-cp36m-manylinux2014_x86_64.whl
  • Upload date:
  • Size: 1.6 MB
  • Tags: CPython 3.6m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.3

File hashes

Hashes for cysystemd-1.4.5-cp36-cp36m-manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 b89d7ababab17fcc993fb7f5a6d6518c9537654343af76c9a7c65a313b9df479
MD5 1210b90a8806e47b3c5e0cf557153439
BLAKE2b-256 c65b5a94ec25c7083204af662c8657d47dc626c26a0ed57c72ff76743e28d660

See more details on using hashes here.

File details

Details for the file cysystemd-1.4.5-cp35-cp35m-manylinux2014_x86_64.whl.

File metadata

  • Download URL: cysystemd-1.4.5-cp35-cp35m-manylinux2014_x86_64.whl
  • Upload date:
  • Size: 1.6 MB
  • Tags: CPython 3.5m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.3

File hashes

Hashes for cysystemd-1.4.5-cp35-cp35m-manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 cf2d44012cd5d99368c23c9c735be1f7626c1375029243155fc13eb21abaa5da
MD5 cc1de96df3be6bd5b8913b3ba0ef3ba0
BLAKE2b-256 06027cc3af034125a39e037702bb6e4c20b40cfe1436f870c56859423d941f0d

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page