Debian Codegraph @

power-usage-report

raw symbols SCIP
1 #!/usr/bin/python3
2
3 # (C) 2012, 2013 Canonical Ltd.
4 # Author: Martin Pitt <[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 import subprocess
19 import sys
20 import os
21 import time
22 import re
23 import functools
24 import tempfile
25 import json
26
27 # standard time for measuring in seconds
28 DURATION = 60
29
30
31 def check_dependencies():
32 '''Check if necessary programs are installed and privileges are available.'''
33
34 err = ''
35
36 if os.geteuid() != 0:
37 err += 'You need to run this program as root.\n\n'
38
39 if subprocess.call(['which', 'powertop'], stdout=subprocess.PIPE) != 0:
40 err += 'powertop not found, please install it.\n\n'
41
42 if err:
43 sys.stderr.write(err)
44 sys.exit(1)
45
46
47 def probe():
48 '''Call probes and return their output in a dict.'''
49
50 # ensure that programs run without translations, to avoid breaking parsing
51 env = os.environ.copy()
52 env['LC_MESSAGES'] = 'C'
53
54 sys.stderr.write('Starting measurement for %i seconds...\n' % DURATION)
55 (fd, powertop_csv) = tempfile.mkstemp(suffix='.csv', prefix='powertop')
56 os.close(fd)
57 powertop = subprocess.Popen(['powertop', '--csv=' + powertop_csv,
58 '--time=' + str(DURATION + 1)],
59 stdout=subprocess.PIPE, env=env)
60 # let powertop initialize; calls lspci and some shell scripts which skew
61 # the fatrace results
62 time.sleep(1)
63
64 output = {}
65 fatrace = subprocess.Popen(['fatrace', '-jtts', str(DURATION), '-p', str(powertop.pid)],
66 stdout=subprocess.PIPE, env=env)
67 output['fatrace'] = fatrace.communicate()[0].decode('UTF-8', errors='ignore')
68
69 powertop.communicate()
70 with open(powertop_csv, 'rb') as f:
71 output['powertop'] = f.read().decode('UTF-8', errors='ignore')
72 os.unlink(powertop_csv)
73
74 return output
75
76
77 def parse_fatrace_events(lines):
78 '''Parse fatrace output lines.
79
80 Split lines into fields, filter out bursts of identical events (usually
81 from reading/writing larger blocks).
82
83 Return array of (program, pid, mode, file) tuples.
84 '''
85 prev_timestamp = None
86
87 events = []
88
89 for line in lines:
90 event = json.loads(line)
91
92 timestamp = event['timestamp']
93 if prev_timestamp and (timestamp - prev_timestamp < 0.01) and event == events[-1]:
94 continue
95 prev_timestamp = timestamp
96
97 events.append(event)
98
99 return events
100
101
102 def group_fatrace_events(events):
103 '''Group fatrace events.
104
105 Return dict program -> file > [#reads,#writes]
106 '''
107 groups = {}
108 for event in events:
109 if event['types'] == 'C':
110 # ignore read-close events for now
111 continue
112
113 comm = event['comm'] if 'comm' in event else 'unknown'
114 if 'path' in event:
115 path = event['path']
116 elif 'device' in event:
117 path = 'device %i:%i inode %i' % (*event['device'], event['inode'])
118 else:
119 path = 'unknown'
120 stat = groups.setdefault(comm, {}).setdefault(path, [0, 0])
121 if 'W' in event['types']:
122 stat[1] += 1
123 elif event['types'] in ('R', 'O', 'RO'):
124 stat[0] += 1
125
126 return groups
127
128
129 def fatrace_report(raw_out):
130 '''Generate disk access report from raw fatrace output'''
131
132 lines = raw_out.splitlines()
133 event_lines = parse_fatrace_events(lines)
134 events = group_fatrace_events(event_lines)
135
136 # sort programs by number of events
137 events_per_prog = []
138 for prog, filemap in events.items():
139 count = functools.reduce(lambda sum, rw: sum + rw[0] + rw[1], filemap.values(), 0)
140 events_per_prog.append((prog, count))
141 events_per_prog.sort(key=lambda i: i[1], reverse=True)
142
143 for (prog, count) in events_per_prog:
144 print('======= %s: %i file access events ======' % (prog, count))
145 for file, (r, w) in events[prog].items():
146 s = file + ':'
147 if r > 0:
148 s += ' %i reads' % r
149 if w > 0:
150 s += ' %i writes' % w
151 print(s)
152 print('')
153
154
155 def powertop_report(raw_out):
156 '''Generate report from raw powertop output'''
157
158 # map powertop's headers to our headers for interesting parts
159 blocks = [
160 ('overview of software power consumers', 'Wakeups'),
161 ('device power report', 'Devices'),
162 ('process device activity', 'Process Device Activity'),
163 ]
164
165 # filter out multiple empty lines
166 lines = re.sub('\n{3,}', '\n\n', raw_out).splitlines()
167 i = 0
168
169 for (search_header, print_header) in blocks:
170 # skip until search_header
171 while i < len(lines) and search_header not in lines[i].lower():
172 i += 1
173 i += 1 # skip header
174 # skip empty lines
175 while not lines[i]:
176 i += 1
177
178 print('====== %s ======' % print_header)
179 while i < len(lines) and lines[i] and not lines[i].startswith('_____'):
180 print(lines[i])
181 i += 1
182 print('')
183
184
185 def main():
186 check_dependencies()
187
188 # Announce that we are about to start
189 sys.stderr.write('''Measurement will begin in 5 seconds. Please make sure that the
190 computer is idle, i. e. do not press keys, start or operate programs, and that
191 programs are not busy with active tasks other than the one you want to examine.\n''')
192 time.sleep(5)
193
194 output = probe()
195
196 sys.stderr.write('Measurement complete. Generating report...\n')
197 fatrace_report(output['fatrace'])
198 powertop_report(output['powertop'])
199
200 if __name__ == '__main__':
201 main()