buildstats.py 13 KB

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