Debian Codegraph @

src/cyclictest/get_cyclictest_snapshot.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """ Program to get a snapshot of a running instance of cyclictest """
3
4 # SPDX-License-Identifier: GPL-2.0-or-later
5 # Copyright (C) 2020 John Kacur <[email protected]>
6
7 import subprocess
8 import argparse
9 import re
10 import glob
11 import sys
12
13 parser = argparse.ArgumentParser(description='Get a snapshot of running instances of cyclictest')
14 parser.add_argument('-l', '--list', action='store_true', help='list the main pid(s) of running instances of cyclictest')
15 parser.add_argument('-s', '--snapshot', nargs='*', metavar='pid', help='take a snapshot of running instances of cyclictest')
16 parser.add_argument('-p', '--print', nargs='*', metavar='pid', help='print the snapshots')
17 args = parser.parse_args()
18
19 class Snapshot:
20 """ Class for getting a snapshot of a running cyclictest instance """
21
22 warned = False
23
24 @classmethod
25 def print_warning(cls):
26 """ print a warning one time only even if called multiple times """
27 if not cls.warned:
28 cls.warned = True
29 print("No cyclictest instance found")
30
31 def __init__(self):
32 self.pids = []
33 self.shm_files = []
34 self.refresh()
35
36 def refresh(self):
37 """ Create a list of running cyclictest instances. """
38 self.pids = []
39 self.shm_files = glob.glob('/dev/shm/cyclictest*')
40 self.shm_files.sort()
41 for shm_file in self.shm_files:
42 pid = re.search('[0-9]*$', shm_file).group()
43 self.pids += [pid]
44
45 def take_snapshot(self, spids=None):
46 """ Send USR2 to all running instances of cyclictest,
47 or just to a specific pid (spids) if specified. """
48 if spids is None:
49 if not self.pids:
50 Snapshot.print_warning()
51 for pid in self.pids:
52 subprocess.run(["kill", "-s", "USR2", pid])
53 else:
54 for pid in spids:
55 subprocess.run(["kill", "-s", "USR2", pid])
56
57 def print_pids(self):
58 """ Print the list of pids of running cyclictest instances. """
59 if not self.pids:
60 Snapshot.print_warning()
61 for pid in self.pids:
62 print(pid)
63
64 def print(self, spids=None):
65 """ Print the data in /dev/shm/cyclictest* """
66 if spids is None:
67 if not self.shm_files:
68 Snapshot.print_warning()
69 for shm_file in self.shm_files:
70 with open(shm_file, 'r') as f:
71 data = f.read()
72 print(data)
73 else:
74 for spid in spids:
75 if spid in self.pids:
76 shm_file = '/dev/shm/cyclictest' + spid
77 with open(shm_file, 'r') as f:
78 data = f.read()
79 print(data)
80 else:
81 Snapshot.print_warning()
82
83 snapshot = Snapshot()
84
85 if args.list:
86 snapshot.print_pids()
87
88 if args.snapshot is not None:
89 if args.snapshot:
90 snapshot.take_snapshot(args.snapshot)
91 else:
92 snapshot.take_snapshot()
93
94 if args.print is not None:
95 if args.print:
96 snapshot.print(args.print)
97 else:
98 snapshot.print()
99
100 if len(sys.argv) == 1:
101 snapshot.take_snapshot()
102 snapshot.print()