DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (2e5cf37deea0)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

"""This script sends systemd unit output.

Some environment variables are consulted:

FROM
   Who the email will be from
TO
   who to send the email to (comma delimited list)
"""

import argparse
import datetime
from email.mime.text import MIMEText
import json
import os
import re
import subprocess
import sys


def get_unit_journal_output(unit):
    args = [
        'journalctl',
        '-o', 'json',
        '--unit', unit,
        # TODO make time configurable.
        '--since', '-5m',
    ]

    items = []
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for l in p.stdout:
        o = json.loads(l, encoding='utf-8')

        if 'MESSAGE' not in o:
            continue

        # Timestamp is in number of microseconds since epoch.
        ts = o['__REALTIME_TIMESTAMP']
        pid = o['_PID']
        s, us = divmod(int(ts), 1000000)
        dt = datetime.datetime.utcfromtimestamp(float(s) + float(us) / 1000000)
        items.append((dt, pid, o['MESSAGE']))

    p.wait()

    return items


def is_noop_unit_output(journal_output):
    # This function checks if every entry in the journalctl output is started by systemd
    # (ie PID == 1) and is simply a message indicating the service is started/being started.
    noop_regex = re.compile(r'^Start(ing|ed).*\.$')

    if all(noop_regex.match(message) and int(pid) == 1 for _, pid, message in journal_output):
        return True

    return False


def send_email(unit, hostname, email_from, email_to):
    body_lines = []
    journal_output = get_unit_journal_output(unit)

    if is_noop_unit_output(journal_output):
        return 0

    for dt, pid, message in journal_output:
        body_lines.append('%s [%s] %s' % (dt.isoformat(), pid, message))

    msg = MIMEText('\n'.join(body_lines), _charset='utf-8')
    msg['From'] = email_from
    msg['To'] = email_to
    msg['Subject'] = '%s unit output for %s' % (hostname, unit)

    # We just speak to sendmail because we're lazy. Plus we don't know
    # for certain the local machine is running a SMTP server.
    p = subprocess.Popen(['sendmail', email_to], stdin=subprocess.PIPE)
    p.stdin.write(msg.as_string())
    p.stdin.close()
    p.communicate()
    p.wait()

    return p.returncode


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('unit', help='Unit whose output to report')
    parser.add_argument('hostname', help='Hostname sending from')

    args = parser.parse_args()

    os.environ['ENCODING'] = 'utf-8'

    email_from = os.environ.get('FROM', 'systemd-mailer@%s' % args.hostname)

    if 'TO' not in os.environ:
        print('do not know who to send mail to')
        sys.exit(1)

    sys.exit(send_email(args.unit, args.hostname,
                        email_from, os.environ['TO']))