/
main.py
202 lines (167 loc) · 7.48 KB
/
main.py
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""
Copyright (c) 2015 Tim Waugh <tim@cyberelk.net>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import argparse
import logging
import os
import sys
from systemd import journal
from journal_brief import (SelectiveReader,
LatestJournalEntries,
get_formatter,
list_formatters,
JournalFilter)
from journal_brief.config import Config, ConfigError
from journal_brief.constants import PACKAGE, CONFIG_DIR, PRIORITY_MAP
from journal_brief.debrief import Debriefer
log = logging.getLogger('cli')
class InstanceConfig(object):
def __init__(self, config, args):
self.config = config
self.args = args
def get(self, key, default_value=None):
config_key = key.replace('_', '-')
args_key = key.replace('-', '_')
try:
value = getattr(self.args, args_key)
log.debug("%s=%r from args", args_key, value)
except AttributeError:
value = None
finally:
if value is None:
value = self.config.get(config_key, default_value)
if value is not None:
log.debug("%s=%r from config", args_key, value)
return value
class NullStream(object):
def write(self, str):
pass
def flush(self):
pass
class CLI(object):
def __init__(self, args=None):
self.args = self.get_args(args or sys.argv[1:])
config = Config(config_file=self.args.conf)
self.config = InstanceConfig(config, self.args)
def get_args(self, args):
description = 'Show new journal entries since last run'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('-b', action='store_true', default=False,
help='process all entries from the current boot')
parser.add_argument('-p', '--priority', metavar='PRI',
help='show entries at priority PRI and lower',
choices=['emerg', 'alert', 'crit', 'err',
'warning', 'notice', 'info', 'debug'])
parser.add_argument('--conf', metavar='FILE',
help='use FILE as config file')
parser.add_argument('--debug', action='store_true', default=False,
help='enable debugging')
parser.add_argument('--dry-run', action='store_true', default=False,
help='do not update cursor bookmark file')
help = ('output format for journal entries, '
'comma-separated list from {0}'.format(list_formatters()))
parser.add_argument('-o', '--output', metavar='FORMAT', help=help)
parser.add_argument('--help-output', action='store_true',
default=False,
help='display information about output formats')
cmds = parser.add_subparsers(dest='cmd')
debrief = cmds.add_parser('debrief', help='create exclusions config')
cmds.add_parser('reset', help='reset cursor bookmark and exit')
cmds.add_parser('stats', help='show statistics')
return parser.parse_args(args)
def show_stats(self, jfilter, exclusions):
jfilter.format(NullStream())
stats = jfilter.get_statistics()
log.debug("stats: %r", stats)
strf = "{FREQ:>10} {EXCLUSION}"
print(strf.format(FREQ='FREQUENCY', EXCLUSION='EXCLUSION'))
for stat in stats:
print(strf.format(FREQ=stat.hits,
EXCLUSION=repr(dict(stat.exclusion))))
def run(self):
default_output_format = 'reboot,short'
if self.args.help_output:
print("Available output formats:")
for output in list_formatters():
print("\n{0}:".format(output))
formatter = get_formatter(output)
docstring = [line.strip()
for line in formatter.__doc__.splitlines()]
while docstring and not docstring[0]:
del docstring[0]
while docstring and not docstring[-1]:
del docstring[-1]
print('\n'.join([' ' + line for line in docstring]))
print("\nMultiple output formats can be used at the same time.")
print("The default is '{0}'".format(default_output_format))
return
if self.config.get('debug'):
logging.basicConfig(level=logging.DEBUG)
cursor_file = self.config.get('cursor-file')
if not cursor_file.startswith('/'):
cursor_file = os.path.join(CONFIG_DIR, cursor_file)
log.debug("cursor-file=%r", cursor_file)
if self.args.cmd == 'reset':
log.debug('reset: removing %r', cursor_file)
try:
os.unlink(cursor_file)
except IOError:
pass
return
log_level = None
priority = self.config.get('priority')
if priority:
log_level = int(PRIORITY_MAP[priority])
log.debug("priority=%r from args/config", log_level)
if self.args.cmd == 'debrief':
formatters = [get_formatter('config')]
else:
formats = self.config.get('output',
default_output_format).split(',')
formatters = [get_formatter(format) for format in formats]
default_inclusions = self.config.get('inclusions')
if default_inclusions:
inclusions = default_inclusions[:]
else:
inclusions = []
for formatter in formatters:
if formatter.FILTER_INCLUSIONS is not None:
inclusions.extend(formatter.FILTER_INCLUSIONS)
reader = SelectiveReader(this_boot=self.args.b,
log_level=log_level,
inclusions=inclusions)
with LatestJournalEntries(cursor_file=cursor_file,
reader=reader,
dry_run=self.args.dry_run,
seek_cursor=not self.args.b) as entries:
exclusions = self.config.get('exclusions', [])
jfilter = JournalFilter(entries, formatters,
default_inclusions=default_inclusions,
default_exclusions=exclusions)
if self.args.cmd == 'stats':
self.show_stats(jfilter, exclusions)
else:
jfilter.format(sys.stdout)
def run():
try:
CLI().run()
except KeyboardInterrupt:
pass
except IOError as ex:
sys.stderr.write("{0}: {1}\n".format(PACKAGE, os.strerror(ex.errno)))
sys.exit(1)
except ConfigError:
sys.exit(1)
if __name__ == '__main__':
run()