buildstats.py 12 KB

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