-
Notifications
You must be signed in to change notification settings - Fork 9
/
verify-loader
executable file
·397 lines (368 loc) · 13.4 KB
/
verify-loader
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#!/usr/bin/env python3
#
# ViaQ logging load generator
#
# Copyright 2021 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
import time
import argparse
import signal
import io
import fcntl
from collections import defaultdict
try:
from systemd import journal
except ImportError:
journal_available = False
else:
journal_available = True
F_SETPIPE_SZ = 1031 # Linux 2.6.35+
F_GETPIPE_SZ = 1032 # Linux 2.6.35+
REPORT_INTERVAL = 10
MB = 1024 * 1024
# If running verify-loader as a background process, we can still do:
# kill -INT ${pid}
# kill -TERM ${pid}
# to make it exit the main loop and print the statistics.
def handle_sig_term(signum, frame):
raise KeyboardInterrupt
class Context(object):
def __init__(self):
self.prev = None
self.count = 0
self.bytes = 0
self.report_count = 0
self.report_bytes = 0
self.duplicates = 0
self.skips = 0
self.report_skips = 0
self.report_duplicates = 0
def msg(self, seq, length):
self.report_count += 1
self.count += 1
self.report_bytes += length
self.bytes += length
if self.prev is None:
self.prev = seq
return None
elif seq == (self.prev + 1):
# Normal and expected code path
self.prev = seq
return None
else:
ret_prev = self.prev
if seq <= self.prev:
self.duplicates += 1
self.report_duplicates += 1
else:
assert seq > (self.prev + 1), (
"Logic bomb! Should not be possible"
)
self.skips += 1
self.report_skips += 1
# Since the sequence jumped ahead, save the new value as the
# previous in order to be sure to stay with the jump.
self.prev = seq
return ret_prev
def report(self):
if self.report_count > 0:
self.count += self.report_count
self.bytes += self.report_bytes
self.report_count = 0
self.report_bytes = 0
self.report_skips = 0
self.report_duplicates = 0
ret_val = True
else:
ret_val = False
return ret_val
def print_stats(invocid, ctx, payload):
now = time.time()
try:
stats, _ = payload.rsplit(b' ', 1)
rawvals = stats.strip()[:-1].split(b' ')
vals = []
for val in rawvals:
if val:
vals.append(val)
if vals[1][-1] == 115:
timestamp, statseq = float(vals[1][:-1]), int(vals[2])
if statseq != ctx.prev:
raise Exception(
f"Statistics sequence number, {statseq:d}, doest not"
f" match sequence from log record itself, {ctx.prev:d}"
)
else:
raise Exception(
"Invalid floating point timestamp value encountered:"
f" {vals[1]}"
)
if len(vals) == 7:
lclrate, gblrate = float(vals[3]), float(vals[4])
skp, skr = int(vals[5]), int(vals[6])
elif len(vals) == 10:
lclrate, gblrate = float(vals[3]), float(vals[7])
skp, skr = int(vals[8]), int(vals[9])
else:
raise Exception("Logic bomb!")
except Exception as exc:
print(
f"Error parsing payload statistics: {exc!r}, payload: {payload!r}",
file=sys.stderr,
)
sys.exit(1)
else:
offset = now - timestamp
print(
f"verify-loader - loader stats ({invocid}): {now:.2f}s"
f" ({offset:4.2f}s) {lclrate:12.3f}"
f" {gblrate:12.3f} {statseq:d} {ctx.count:d} {ctx.skips:d}"
f" {ctx.duplicates:d} {skp:d} {skr:d}",
flush=True
)
def verify(
input_gen, report_interval=REPORT_INTERVAL, emit_loader_stats=False,
debug=False
):
signal.signal(signal.SIGTERM, handle_sig_term)
ret_val = 0
ignored_bytes = 0
ignored_count = 0
report_bytes = 0
report_ignored_bytes = 0
report_ignored_count = 0
contexts = defaultdict(Context)
start = time.time()
report_start = start
rptperiod = (report_interval, start)
try:
for line in input_gen:
line_len = len(line)
if not line.startswith(b"loader seq - "):
if debug:
print(f"verify-loader -- ignored {line[:80]}...")
report_ignored_bytes += line_len
report_ignored_count += 1
else:
try:
_, invocid, seqval, payload = line.split(b'-', 4)
except Exception:
report_ignored_bytes += line_len
report_ignored_count += 1
else:
try:
seq = int(seqval)
except Exception:
report_ignored_bytes += line_len
report_ignored_count += 1
else:
report_bytes += line_len
invocid = invocid.strip()
ctx = contexts[invocid]
prev = ctx.msg(seq, line_len)
if debug and (prev is not None):
# Bad record encountered, flag it
print(
f"verify-loader -- {invocid}: bad record,"
f" current sequence #: {seq:d}, previous"
f" sequence #: {prev:d}",
flush=True
)
if emit_loader_stats and payload.startswith(
b" (stats:"
):
print_stats(invocid, ctx, payload)
now = time.time()
if now >= rptperiod[1]:
rptperiod = (
rptperiod[0], rptperiod[1] + rptperiod[0]
)
ignored_bytes += report_ignored_bytes
ignored_count += report_ignored_count
total_bytes = 0
total_count = 0
total_skips = 0
total_dupes = 0
report_count = 0
report_skips = 0
report_dupes = 0
for invocid, ctx in contexts.items():
report_count += ctx.report_count
report_skips += ctx.report_skips
report_dupes += ctx.report_duplicates
if ctx.report():
print(
f"verify-loader - loader {invocid}: {ctx.count:d}"
f" {ctx.skips:d} {ctx.duplicates:d}",
flush=True
)
total_bytes += ctx.bytes
total_count += ctx.count
total_skips += ctx.skips
total_dupes += ctx.duplicates
print(
"verify-loader interval %.3f - %.3f :"
" read rate: %.3f MB/sec, %.3f /sec, %d skips,"
" %d duplicates "
"(ignored %.3f MB/sec, %.3f /sec); "
"overall read rate: %.3f MB/sec, %.3f /sec, %d skips,"
" %d duplicates "
"(ignored %.3f MB/sec, %.3f /sec)"
% (
report_start,
now,
(report_bytes / MB) / (now - report_start),
(report_count / (now - report_start)),
report_skips,
report_dupes,
(report_ignored_bytes / MB) / (now - report_start),
(report_ignored_count / (now - report_start)),
(total_bytes / MB) / (now - start),
(total_count / (now - start)),
total_skips,
total_dupes,
(ignored_bytes / MB) / (now - start),
(ignored_count / (now - start)),
),
flush=True
)
report_bytes = 0
report_ignored_bytes = 0
report_ignored_count = 0
# In case outputing the report takes a significant amount of
# time, we reset the check for the next report here.
report_start = time.time()
except KeyboardInterrupt:
pass
finally:
now = time.time()
ignored_bytes += report_ignored_bytes
ignored_count += report_ignored_count
total_bytes = 0
total_count = 0
tot_skips = 0
tot_dupes = 0
for invocid, ctx in contexts.items():
ctx.report()
total_bytes += ctx.bytes
total_count += ctx.count
tot_skips += ctx.skips
tot_dupes += ctx.duplicates
if ignored_count + total_count > 0:
for invocid, ctx in contexts.items():
print(
f"verify-loader - loader {invocid}: {ctx.count:d}"
f" {ctx.skips:d} {ctx.duplicates:d}"
)
print(
"verify-loader overall %.3f - %.3f read rate: %.3f MB/sec,"
" %.3f /sec, %d skips, %d duplicates "
"(ignored %.3f MB/sec, %.3f /sec)"
% (
start,
now,
(total_bytes / MB) / (now - start),
(total_count / (now - start)),
tot_skips,
tot_dupes,
(ignored_bytes / MB) / (now - start),
(ignored_count / (now - start)),
)
)
if tot_skips + tot_dupes > 0:
ret_val = 1
return ret_val
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Message payload generator.')
parser.add_argument(
'file', metavar='FILE', nargs='?',
default='-',
help='file to read, if empty, stdin is used'
)
parser.add_argument(
'--report-interval', metavar='INTERVAL', dest='reportint', type=int,
default=REPORT_INTERVAL,
help=(
'the # seconds between reports'
f' (defaults to {REPORT_INTERVAL} seconds)'
)
)
parser.add_argument(
'--emit-loader-stats', dest='emitloaderstats', action="store_true",
help=(
'emit statistics embedded in logs from the loader'
' (defaults to False)'
)
)
parser.add_argument(
'--read-journal', dest='readjournal', action="store_true",
help='read directly from the systemd journal (defaults to False)'
)
parser.add_argument(
'--debug', dest='debug', action="store_true",
help='Turn on debugging (defaults to False)'
)
args = parser.parse_args()
if args.readjournal and not journal_available:
print(
"systemd journal module not available, most likely running using"
" pypy3",
file=sys.stderr
)
sys.exit(1)
if args.file == '-':
if args.readjournal:
j = journal.Reader()
# The fileno() method ends up creating the inotify file descriptor
# which in turn prevents this client from leaking open journal log
# files.
j.fileno()
j.seek_tail()
j.get_previous()
def jreader():
while True:
for entry in j:
yield entry['MESSAGE'].encode('utf-8')
# We have to wait in a loop here because the journal code
# runs as C code, where Python exception handling is not
# in play.
ret = journal.NOP
while ret == journal.NOP:
ret = j.wait(0.1)
input_gen = jreader()
else:
r_fd = sys.stdin.fileno()
try:
buffer_size = fcntl.fcntl(r_fd, F_GETPIPE_SZ)
except OSError:
# Default when not a pipe.
buffer_size = 65536
assert buffer_size >= 4096, (
f"Expected pipe size to be >= 4096, was {buffer_size!r}"
)
fo = io.FileIO(r_fd)
input_gen = io.BufferedReader(fo, buffer_size=buffer_size)
else:
if args.readjournal:
print(
"*** Warning *** ignoring request to read from the systemd"
" journal (--read-journal) since we have an actual file"
f" argument provided ({args.file}) ..."
)
input_gen = open(args.file, 'rb', 1)
sys.exit(
verify(input_gen, args.reportint, args.emitloaderstats, args.debug)
)