1#!/usr/bin/env python3
2# SPDX-License-Identifier: MIT
3#
4# This file is distributed under the MIT license, see below.
5#
6# The MIT License (MIT)
7#
8# Permission is hereby granted, free of charge, to any person obtaining a copy
9# of this software and associated documentation files (the "Software"), to deal
10# in the Software without restriction, including without limitation the rights
11# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12# copies of the Software, and to permit persons to whom the Software is
13# furnished to do so, subject to the following conditions:
14#
15# The above copyright notice and this permission notice shall be included in
16# all copies or substantial portions of the Software.
17#
18# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24# SOFTWARE.
25
26"""
27Prints out journal entries with no or bad catalog explanations.
28"""
29
30import re
31from systemd import journal, id128
32
33j = journal.Reader()
34
35logged = set()
36pattern = re.compile('@[A-Z0-9_]+@')
37
38mids = {v:k for k,v in id128.__dict__.items()
39        if k.startswith('SD_MESSAGE')}
40
41freq = 1000
42
43def log_entry(x):
44    if 'CODE_FILE' in x:
45        # some of our code was using 'CODE_FUNCTION' instead of 'CODE_FUNC'
46        print('{}:{} {}'.format(x.get('CODE_FILE', '???'),
47                                x.get('CODE_LINE', '???'),
48                                x.get('CODE_FUNC', None) or x.get('CODE_FUNCTION', '???')))
49    print('    {}'.format(x.get('MESSAGE', 'no message!')))
50    for k, v in x.items():
51        if k.startswith('CODE_') or k in {'MESSAGE_ID', 'MESSAGE'}:
52            continue
53        print('    {}={}'.format(k, v))
54    print()
55
56for i, x in enumerate(j):
57    if i % freq == 0:
58        print(i, end='\r')
59
60    try:
61        mid = x['MESSAGE_ID']
62    except KeyError:
63        continue
64    name = mids.get(mid, 'unknown')
65
66    try:
67        desc = journal.get_catalog(mid)
68    except FileNotFoundError:
69        if mid in logged:
70            continue
71
72        print('{} {.hex}: no catalog entry'.format(name, mid))
73        log_entry(x)
74        logged.add(mid)
75        continue
76
77    fields = [field[1:-1] for field in pattern.findall(desc)]
78    for field in fields:
79        index = (mid, field)
80        if field in x or index in logged:
81            continue
82        print('{} {.hex}: no field {}'.format(name, mid, field))
83        log_entry(x)
84        logged.add(index)
85