buildstats.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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.nevr = "{}-{}-{}".format(name, version, revision)
  139. else:
  140. self.nevr = "{}-{}_{}-{}".format(name, 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. class BuildStats(dict):
  155. """Class representing buildstats of one build"""
  156. @property
  157. def num_tasks(self):
  158. """Get number of tasks"""
  159. num = 0
  160. for recipe in self.values():
  161. num += len(recipe.tasks)
  162. return num
  163. @classmethod
  164. def from_json(cls, bs_json):
  165. """Create new BuildStats object from JSON object"""
  166. buildstats = cls()
  167. for recipe in bs_json:
  168. if recipe['name'] in buildstats:
  169. raise BSError("Cannot handle multiple versions of the same "
  170. "package ({})".format(recipe['name']))
  171. bsrecipe = BSRecipe(recipe['name'], recipe['epoch'],
  172. recipe['version'], recipe['revision'])
  173. for task, data in recipe['tasks'].items():
  174. bsrecipe.tasks[task] = BSTask(data)
  175. buildstats[recipe['name']] = bsrecipe
  176. return buildstats
  177. @staticmethod
  178. def from_file_json(path):
  179. """Load buildstats from a JSON file"""
  180. with open(path) as fobj:
  181. bs_json = json.load(fobj)
  182. return BuildStats.from_json(bs_json)
  183. @staticmethod
  184. def split_nevr(nevr):
  185. """Split name and version information from recipe "nevr" string"""
  186. n_e_v, revision = nevr.rsplit('-', 1)
  187. match = re.match(r'^(?P<name>\S+)-((?P<epoch>[0-9]{1,5})_)?(?P<version>[0-9]\S*)$',
  188. n_e_v)
  189. if not match:
  190. # If we're not able to parse a version starting with a number, just
  191. # take the part after last dash
  192. match = re.match(r'^(?P<name>\S+)-((?P<epoch>[0-9]{1,5})_)?(?P<version>[^-]+)$',
  193. n_e_v)
  194. name = match.group('name')
  195. version = match.group('version')
  196. epoch = match.group('epoch')
  197. return name, epoch, version, revision
  198. @classmethod
  199. def from_dir(cls, path):
  200. """Load buildstats from a buildstats directory"""
  201. if not os.path.isfile(os.path.join(path, 'build_stats')):
  202. raise BSError("{} does not look like a buildstats directory".format(path))
  203. log.debug("Reading buildstats directory %s", path)
  204. buildstats = cls()
  205. subdirs = os.listdir(path)
  206. for dirname in subdirs:
  207. recipe_dir = os.path.join(path, dirname)
  208. if not os.path.isdir(recipe_dir):
  209. continue
  210. name, epoch, version, revision = cls.split_nevr(dirname)
  211. bsrecipe = BSRecipe(name, epoch, version, revision)
  212. for task in os.listdir(recipe_dir):
  213. bsrecipe.tasks[task] = BSTask.from_file(
  214. os.path.join(recipe_dir, task))
  215. if name in buildstats:
  216. raise BSError("Cannot handle multiple versions of the same "
  217. "package ({})".format(name))
  218. buildstats[name] = bsrecipe
  219. return buildstats
  220. def aggregate(self, buildstats):
  221. """Aggregate other buildstats into this"""
  222. if set(self.keys()) != set(buildstats.keys()):
  223. raise ValueError("Refusing to aggregate buildstats, set of "
  224. "recipes is different")
  225. for pkg, data in buildstats.items():
  226. self[pkg].aggregate(data)
  227. def diff_buildstats(bs1, bs2, stat_attr, min_val=None, min_absdiff=None):
  228. """Compare the tasks of two buildstats"""
  229. tasks_diff = []
  230. pkgs = set(bs1.keys()).union(set(bs2.keys()))
  231. for pkg in pkgs:
  232. tasks1 = bs1[pkg].tasks if pkg in bs1 else {}
  233. tasks2 = bs2[pkg].tasks if pkg in bs2 else {}
  234. if not tasks1:
  235. pkg_op = '+'
  236. elif not tasks2:
  237. pkg_op = '-'
  238. else:
  239. pkg_op = ' '
  240. for task in set(tasks1.keys()).union(set(tasks2.keys())):
  241. task_op = ' '
  242. if task in tasks1:
  243. val1 = getattr(bs1[pkg].tasks[task], stat_attr)
  244. else:
  245. task_op = '+'
  246. val1 = 0
  247. if task in tasks2:
  248. val2 = getattr(bs2[pkg].tasks[task], stat_attr)
  249. else:
  250. val2 = 0
  251. task_op = '-'
  252. if val1 == 0:
  253. reldiff = float('inf')
  254. else:
  255. reldiff = 100 * (val2 - val1) / val1
  256. if min_val and max(val1, val2) < min_val:
  257. log.debug("Filtering out %s:%s (%s)", pkg, task,
  258. max(val1, val2))
  259. continue
  260. if min_absdiff and abs(val2 - val1) < min_absdiff:
  261. log.debug("Filtering out %s:%s (difference of %s)", pkg, task,
  262. val2-val1)
  263. continue
  264. tasks_diff.append(TaskDiff(pkg, pkg_op, task, task_op, val1, val2,
  265. val2-val1, reldiff))
  266. return tasks_diff
  267. class BSVerDiff(object):
  268. """Class representing recipe version differences between two buildstats"""
  269. def __init__(self, bs1, bs2):
  270. RecipeVerDiff = namedtuple('RecipeVerDiff', 'left right')
  271. recipes1 = set(bs1.keys())
  272. recipes2 = set(bs2.keys())
  273. self.new = dict([(r, bs2[r]) for r in sorted(recipes2 - recipes1)])
  274. self.dropped = dict([(r, bs1[r]) for r in sorted(recipes1 - recipes2)])
  275. self.echanged = {}
  276. self.vchanged = {}
  277. self.rchanged = {}
  278. self.unchanged = {}
  279. common = recipes2.intersection(recipes1)
  280. if common:
  281. for recipe in common:
  282. rdiff = RecipeVerDiff(bs1[recipe], bs2[recipe])
  283. if bs1[recipe].epoch != bs2[recipe].epoch:
  284. self.echanged[recipe] = rdiff
  285. elif bs1[recipe].version != bs2[recipe].version:
  286. self.vchanged[recipe] = rdiff
  287. elif bs1[recipe].revision != bs2[recipe].revision:
  288. self.rchanged[recipe] = rdiff
  289. else:
  290. self.unchanged[recipe] = rdiff