blob: 3b76286ba57a57ae9a9cf08e52324613b176f956 [file] [log] [blame]
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001#
2# Copyright (c) 2017, Intel Corporation.
3#
Brad Bishopc342db32019-05-15 21:57:59 -04004# SPDX-License-Identifier: GPL-2.0-only
Brad Bishopd7bf8c12018-02-25 22:55:05 -05005#
6"""Functionality for analyzing buildstats"""
7import json
8import logging
9import os
10import re
Andrew Geissler517393d2023-01-13 08:55:19 -060011from collections import namedtuple
Brad Bishopd7bf8c12018-02-25 22:55:05 -050012from statistics import mean
13
14
15log = logging.getLogger()
16
17
18taskdiff_fields = ('pkg', 'pkg_op', 'task', 'task_op', 'value1', 'value2',
19 'absdiff', 'reldiff')
20TaskDiff = namedtuple('TaskDiff', ' '.join(taskdiff_fields))
21
22
23class BSError(Exception):
24 """Error handling of buildstats"""
25 pass
26
27
28class BSTask(dict):
29 def __init__(self, *args, **kwargs):
30 self['start_time'] = None
31 self['elapsed_time'] = None
32 self['status'] = None
33 self['iostat'] = {}
34 self['rusage'] = {}
35 self['child_rusage'] = {}
36 super(BSTask, self).__init__(*args, **kwargs)
37
38 @property
39 def cputime(self):
40 """Sum of user and system time taken by the task"""
41 rusage = self['rusage']['ru_stime'] + self['rusage']['ru_utime']
42 if self['child_rusage']:
43 # Child rusage may have been optimized out
44 return rusage + self['child_rusage']['ru_stime'] + self['child_rusage']['ru_utime']
45 else:
46 return rusage
47
48 @property
49 def walltime(self):
50 """Elapsed wall clock time"""
51 return self['elapsed_time']
52
53 @property
54 def read_bytes(self):
55 """Bytes read from the block layer"""
56 return self['iostat']['read_bytes']
57
58 @property
59 def write_bytes(self):
60 """Bytes written to the block layer"""
61 return self['iostat']['write_bytes']
62
63 @property
64 def read_ops(self):
65 """Number of read operations on the block layer"""
66 if self['child_rusage']:
67 # Child rusage may have been optimized out
68 return self['rusage']['ru_inblock'] + self['child_rusage']['ru_inblock']
69 else:
70 return self['rusage']['ru_inblock']
71
72 @property
73 def write_ops(self):
74 """Number of write operations on the block layer"""
75 if self['child_rusage']:
76 # Child rusage may have been optimized out
77 return self['rusage']['ru_oublock'] + self['child_rusage']['ru_oublock']
78 else:
79 return self['rusage']['ru_oublock']
80
81 @classmethod
82 def from_file(cls, buildstat_file):
83 """Read buildstat text file"""
84 bs_task = cls()
85 log.debug("Reading task buildstats from %s", buildstat_file)
86 end_time = None
87 with open(buildstat_file) as fobj:
88 for line in fobj.readlines():
89 key, val = line.split(':', 1)
90 val = val.strip()
91 if key == 'Started':
92 start_time = float(val)
93 bs_task['start_time'] = start_time
94 elif key == 'Ended':
95 end_time = float(val)
96 elif key.startswith('IO '):
97 split = key.split()
98 bs_task['iostat'][split[1]] = int(val)
99 elif key.find('rusage') >= 0:
100 split = key.split()
101 ru_key = split[-1]
102 if ru_key in ('ru_stime', 'ru_utime'):
103 val = float(val)
104 else:
105 val = int(val)
106 ru_type = 'rusage' if split[0] == 'rusage' else \
107 'child_rusage'
108 bs_task[ru_type][ru_key] = val
109 elif key == 'Status':
110 bs_task['status'] = val
111 if end_time is not None and start_time is not None:
112 bs_task['elapsed_time'] = end_time - start_time
113 else:
114 raise BSError("{} looks like a invalid buildstats file".format(buildstat_file))
115 return bs_task
116
117
118class BSTaskAggregate(object):
119 """Class representing multiple runs of the same task"""
120 properties = ('cputime', 'walltime', 'read_bytes', 'write_bytes',
121 'read_ops', 'write_ops')
122
123 def __init__(self, tasks=None):
124 self._tasks = tasks or []
125 self._properties = {}
126
127 def __getattr__(self, name):
128 if name in self.properties:
129 if name not in self._properties:
130 # Calculate properties on demand only. We only provide mean
131 # value, so far
132 self._properties[name] = mean([getattr(t, name) for t in self._tasks])
133 return self._properties[name]
134 else:
135 raise AttributeError("'BSTaskAggregate' has no attribute '{}'".format(name))
136
137 def append(self, task):
138 """Append new task"""
139 # Reset pre-calculated properties
140 assert isinstance(task, BSTask), "Type is '{}' instead of 'BSTask'".format(type(task))
141 self._properties = {}
142 self._tasks.append(task)
143
144
145class BSRecipe(object):
146 """Class representing buildstats of one recipe"""
147 def __init__(self, name, epoch, version, revision):
148 self.name = name
149 self.epoch = epoch
150 self.version = version
151 self.revision = revision
152 if epoch is None:
153 self.evr = "{}-{}".format(version, revision)
154 else:
155 self.evr = "{}_{}-{}".format(epoch, version, revision)
156 self.tasks = {}
157
158 def aggregate(self, bsrecipe):
159 """Aggregate data of another recipe buildstats"""
160 if self.nevr != bsrecipe.nevr:
161 raise ValueError("Refusing to aggregate buildstats, recipe version "
162 "differs: {} vs. {}".format(self.nevr, bsrecipe.nevr))
163 if set(self.tasks.keys()) != set(bsrecipe.tasks.keys()):
164 raise ValueError("Refusing to aggregate buildstats, set of tasks "
165 "in {} differ".format(self.name))
166
167 for taskname, taskdata in bsrecipe.tasks.items():
168 if not isinstance(self.tasks[taskname], BSTaskAggregate):
169 self.tasks[taskname] = BSTaskAggregate([self.tasks[taskname]])
170 self.tasks[taskname].append(taskdata)
171
172 @property
173 def nevr(self):
174 return self.name + '-' + self.evr
175
176
177class BuildStats(dict):
178 """Class representing buildstats of one build"""
179
180 @property
181 def num_tasks(self):
182 """Get number of tasks"""
183 num = 0
184 for recipe in self.values():
185 num += len(recipe.tasks)
186 return num
187
188 @classmethod
189 def from_json(cls, bs_json):
190 """Create new BuildStats object from JSON object"""
191 buildstats = cls()
192 for recipe in bs_json:
193 if recipe['name'] in buildstats:
194 raise BSError("Cannot handle multiple versions of the same "
195 "package ({})".format(recipe['name']))
196 bsrecipe = BSRecipe(recipe['name'], recipe['epoch'],
197 recipe['version'], recipe['revision'])
198 for task, data in recipe['tasks'].items():
199 bsrecipe.tasks[task] = BSTask(data)
200
201 buildstats[recipe['name']] = bsrecipe
202
203 return buildstats
204
205 @staticmethod
206 def from_file_json(path):
207 """Load buildstats from a JSON file"""
208 with open(path) as fobj:
209 bs_json = json.load(fobj)
210 return BuildStats.from_json(bs_json)
211
212
213 @staticmethod
214 def split_nevr(nevr):
215 """Split name and version information from recipe "nevr" string"""
216 n_e_v, revision = nevr.rsplit('-', 1)
217 match = re.match(r'^(?P<name>\S+)-((?P<epoch>[0-9]{1,5})_)?(?P<version>[0-9]\S*)$',
218 n_e_v)
219 if not match:
220 # If we're not able to parse a version starting with a number, just
221 # take the part after last dash
222 match = re.match(r'^(?P<name>\S+)-((?P<epoch>[0-9]{1,5})_)?(?P<version>[^-]+)$',
223 n_e_v)
224 name = match.group('name')
225 version = match.group('version')
226 epoch = match.group('epoch')
227 return name, epoch, version, revision
228
229 @classmethod
230 def from_dir(cls, path):
231 """Load buildstats from a buildstats directory"""
232 if not os.path.isfile(os.path.join(path, 'build_stats')):
233 raise BSError("{} does not look like a buildstats directory".format(path))
234
235 log.debug("Reading buildstats directory %s", path)
236
237 buildstats = cls()
238 subdirs = os.listdir(path)
239 for dirname in subdirs:
240 recipe_dir = os.path.join(path, dirname)
Andrew Geissler517393d2023-01-13 08:55:19 -0600241 if dirname == "reduced_proc_pressure" or not os.path.isdir(recipe_dir):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500242 continue
243 name, epoch, version, revision = cls.split_nevr(dirname)
244 bsrecipe = BSRecipe(name, epoch, version, revision)
245 for task in os.listdir(recipe_dir):
246 bsrecipe.tasks[task] = BSTask.from_file(
247 os.path.join(recipe_dir, task))
248 if name in buildstats:
249 raise BSError("Cannot handle multiple versions of the same "
250 "package ({})".format(name))
251 buildstats[name] = bsrecipe
252
253 return buildstats
254
255 def aggregate(self, buildstats):
256 """Aggregate other buildstats into this"""
257 if set(self.keys()) != set(buildstats.keys()):
258 raise ValueError("Refusing to aggregate buildstats, set of "
Andrew Geissler99467da2019-02-25 18:54:23 -0600259 "recipes is different: %s" % (set(self.keys()) ^ set(buildstats.keys())))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500260 for pkg, data in buildstats.items():
261 self[pkg].aggregate(data)
262
263
Brad Bishop96ff1982019-08-19 13:50:42 -0400264def diff_buildstats(bs1, bs2, stat_attr, min_val=None, min_absdiff=None, only_tasks=[]):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500265 """Compare the tasks of two buildstats"""
266 tasks_diff = []
267 pkgs = set(bs1.keys()).union(set(bs2.keys()))
268 for pkg in pkgs:
269 tasks1 = bs1[pkg].tasks if pkg in bs1 else {}
270 tasks2 = bs2[pkg].tasks if pkg in bs2 else {}
Brad Bishop96ff1982019-08-19 13:50:42 -0400271 if only_tasks:
272 tasks1 = {k: v for k, v in tasks1.items() if k in only_tasks}
273 tasks2 = {k: v for k, v in tasks2.items() if k in only_tasks}
274
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500275 if not tasks1:
276 pkg_op = '+'
277 elif not tasks2:
278 pkg_op = '-'
279 else:
280 pkg_op = ' '
281
282 for task in set(tasks1.keys()).union(set(tasks2.keys())):
283 task_op = ' '
284 if task in tasks1:
285 val1 = getattr(bs1[pkg].tasks[task], stat_attr)
286 else:
287 task_op = '+'
288 val1 = 0
289 if task in tasks2:
290 val2 = getattr(bs2[pkg].tasks[task], stat_attr)
291 else:
292 val2 = 0
293 task_op = '-'
294
295 if val1 == 0:
296 reldiff = float('inf')
297 else:
298 reldiff = 100 * (val2 - val1) / val1
299
300 if min_val and max(val1, val2) < min_val:
301 log.debug("Filtering out %s:%s (%s)", pkg, task,
302 max(val1, val2))
303 continue
304 if min_absdiff and abs(val2 - val1) < min_absdiff:
305 log.debug("Filtering out %s:%s (difference of %s)", pkg, task,
306 val2-val1)
307 continue
308 tasks_diff.append(TaskDiff(pkg, pkg_op, task, task_op, val1, val2,
309 val2-val1, reldiff))
310 return tasks_diff
311
312
313class BSVerDiff(object):
314 """Class representing recipe version differences between two buildstats"""
315 def __init__(self, bs1, bs2):
316 RecipeVerDiff = namedtuple('RecipeVerDiff', 'left right')
317
318 recipes1 = set(bs1.keys())
319 recipes2 = set(bs2.keys())
320
321 self.new = dict([(r, bs2[r]) for r in sorted(recipes2 - recipes1)])
322 self.dropped = dict([(r, bs1[r]) for r in sorted(recipes1 - recipes2)])
323 self.echanged = {}
324 self.vchanged = {}
325 self.rchanged = {}
326 self.unchanged = {}
327 self.empty_diff = False
328
329 common = recipes2.intersection(recipes1)
330 if common:
331 for recipe in common:
332 rdiff = RecipeVerDiff(bs1[recipe], bs2[recipe])
333 if bs1[recipe].epoch != bs2[recipe].epoch:
334 self.echanged[recipe] = rdiff
335 elif bs1[recipe].version != bs2[recipe].version:
336 self.vchanged[recipe] = rdiff
337 elif bs1[recipe].revision != bs2[recipe].revision:
338 self.rchanged[recipe] = rdiff
339 else:
340 self.unchanged[recipe] = rdiff
341
342 if len(recipes1) == len(recipes2) == len(self.unchanged):
343 self.empty_diff = True
344
345 def __bool__(self):
346 return not self.empty_diff