attr.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #! /usr/bin/python
  2. import os
  3. import sys
  4. import glob
  5. import optparse
  6. import tempfile
  7. import logging
  8. import shutil
  9. import ConfigParser
  10. class Fail(Exception):
  11. def __init__(self, test, msg):
  12. self.msg = msg
  13. self.test = test
  14. def getMsg(self):
  15. return '\'%s\' - %s' % (self.test.path, self.msg)
  16. class Unsup(Exception):
  17. def __init__(self, test):
  18. self.test = test
  19. def getMsg(self):
  20. return '\'%s\'' % self.test.path
  21. class Event(dict):
  22. terms = [
  23. 'cpu',
  24. 'flags',
  25. 'type',
  26. 'size',
  27. 'config',
  28. 'sample_period',
  29. 'sample_type',
  30. 'read_format',
  31. 'disabled',
  32. 'inherit',
  33. 'pinned',
  34. 'exclusive',
  35. 'exclude_user',
  36. 'exclude_kernel',
  37. 'exclude_hv',
  38. 'exclude_idle',
  39. 'mmap',
  40. 'comm',
  41. 'freq',
  42. 'inherit_stat',
  43. 'enable_on_exec',
  44. 'task',
  45. 'watermark',
  46. 'precise_ip',
  47. 'mmap_data',
  48. 'sample_id_all',
  49. 'exclude_host',
  50. 'exclude_guest',
  51. 'exclude_callchain_kernel',
  52. 'exclude_callchain_user',
  53. 'wakeup_events',
  54. 'bp_type',
  55. 'config1',
  56. 'config2',
  57. 'branch_sample_type',
  58. 'sample_regs_user',
  59. 'sample_stack_user',
  60. ]
  61. def add(self, data):
  62. for key, val in data:
  63. log.debug(" %s = %s" % (key, val))
  64. self[key] = val
  65. def __init__(self, name, data, base):
  66. log.debug(" Event %s" % name);
  67. self.name = name;
  68. self.group = ''
  69. self.add(base)
  70. self.add(data)
  71. def compare_data(self, a, b):
  72. # Allow multiple values in assignment separated by '|'
  73. a_list = a.split('|')
  74. b_list = b.split('|')
  75. for a_item in a_list:
  76. for b_item in b_list:
  77. if (a_item == b_item):
  78. return True
  79. elif (a_item == '*') or (b_item == '*'):
  80. return True
  81. return False
  82. def equal(self, other):
  83. for t in Event.terms:
  84. log.debug(" [%s] %s %s" % (t, self[t], other[t]));
  85. if not self.has_key(t) or not other.has_key(t):
  86. return False
  87. if not self.compare_data(self[t], other[t]):
  88. return False
  89. return True
  90. def diff(self, other):
  91. for t in Event.terms:
  92. if not self.has_key(t) or not other.has_key(t):
  93. continue
  94. if not self.compare_data(self[t], other[t]):
  95. log.warning("expected %s=%s, got %s" % (t, self[t], other[t]))
  96. # Test file description needs to have following sections:
  97. # [config]
  98. # - just single instance in file
  99. # - needs to specify:
  100. # 'command' - perf command name
  101. # 'args' - special command arguments
  102. # 'ret' - expected command return value (0 by default)
  103. #
  104. # [eventX:base]
  105. # - one or multiple instances in file
  106. # - expected values assignments
  107. class Test(object):
  108. def __init__(self, path, options):
  109. parser = ConfigParser.SafeConfigParser()
  110. parser.read(path)
  111. log.warning("running '%s'" % path)
  112. self.path = path
  113. self.test_dir = options.test_dir
  114. self.perf = options.perf
  115. self.command = parser.get('config', 'command')
  116. self.args = parser.get('config', 'args')
  117. try:
  118. self.ret = parser.get('config', 'ret')
  119. except:
  120. self.ret = 0
  121. self.expect = {}
  122. self.result = {}
  123. log.debug(" loading expected events");
  124. self.load_events(path, self.expect)
  125. def is_event(self, name):
  126. if name.find("event") == -1:
  127. return False
  128. else:
  129. return True
  130. def load_events(self, path, events):
  131. parser_event = ConfigParser.SafeConfigParser()
  132. parser_event.read(path)
  133. # The event record section header contains 'event' word,
  134. # optionaly followed by ':' allowing to load 'parent
  135. # event' first as a base
  136. for section in filter(self.is_event, parser_event.sections()):
  137. parser_items = parser_event.items(section);
  138. base_items = {}
  139. # Read parent event if there's any
  140. if (':' in section):
  141. base = section[section.index(':') + 1:]
  142. parser_base = ConfigParser.SafeConfigParser()
  143. parser_base.read(self.test_dir + '/' + base)
  144. base_items = parser_base.items('event')
  145. e = Event(section, parser_items, base_items)
  146. events[section] = e
  147. def run_cmd(self, tempdir):
  148. cmd = "PERF_TEST_ATTR=%s %s %s -o %s/perf.data %s" % (tempdir,
  149. self.perf, self.command, tempdir, self.args)
  150. ret = os.WEXITSTATUS(os.system(cmd))
  151. log.info(" '%s' ret %d " % (cmd, ret))
  152. if ret != int(self.ret):
  153. raise Unsup(self)
  154. def compare(self, expect, result):
  155. match = {}
  156. log.debug(" compare");
  157. # For each expected event find all matching
  158. # events in result. Fail if there's not any.
  159. for exp_name, exp_event in expect.items():
  160. exp_list = []
  161. log.debug(" matching [%s]" % exp_name)
  162. for res_name, res_event in result.items():
  163. log.debug(" to [%s]" % res_name)
  164. if (exp_event.equal(res_event)):
  165. exp_list.append(res_name)
  166. log.debug(" ->OK")
  167. else:
  168. log.debug(" ->FAIL");
  169. log.debug(" match: [%s] matches %s" % (exp_name, str(exp_list)))
  170. # we did not any matching event - fail
  171. if (not exp_list):
  172. exp_event.diff(res_event)
  173. raise Fail(self, 'match failure');
  174. match[exp_name] = exp_list
  175. # For each defined group in the expected events
  176. # check we match the same group in the result.
  177. for exp_name, exp_event in expect.items():
  178. group = exp_event.group
  179. if (group == ''):
  180. continue
  181. for res_name in match[exp_name]:
  182. res_group = result[res_name].group
  183. if res_group not in match[group]:
  184. raise Fail(self, 'group failure')
  185. log.debug(" group: [%s] matches group leader %s" %
  186. (exp_name, str(match[group])))
  187. log.debug(" matched")
  188. def resolve_groups(self, events):
  189. for name, event in events.items():
  190. group_fd = event['group_fd'];
  191. if group_fd == '-1':
  192. continue;
  193. for iname, ievent in events.items():
  194. if (ievent['fd'] == group_fd):
  195. event.group = iname
  196. log.debug('[%s] has group leader [%s]' % (name, iname))
  197. break;
  198. def run(self):
  199. tempdir = tempfile.mkdtemp();
  200. try:
  201. # run the test script
  202. self.run_cmd(tempdir);
  203. # load events expectation for the test
  204. log.debug(" loading result events");
  205. for f in glob.glob(tempdir + '/event*'):
  206. self.load_events(f, self.result);
  207. # resolve group_fd to event names
  208. self.resolve_groups(self.expect);
  209. self.resolve_groups(self.result);
  210. # do the expectation - results matching - both ways
  211. self.compare(self.expect, self.result)
  212. self.compare(self.result, self.expect)
  213. finally:
  214. # cleanup
  215. shutil.rmtree(tempdir)
  216. def run_tests(options):
  217. for f in glob.glob(options.test_dir + '/' + options.test):
  218. try:
  219. Test(f, options).run()
  220. except Unsup, obj:
  221. log.warning("unsupp %s" % obj.getMsg())
  222. def setup_log(verbose):
  223. global log
  224. level = logging.CRITICAL
  225. if verbose == 1:
  226. level = logging.WARNING
  227. if verbose == 2:
  228. level = logging.INFO
  229. if verbose >= 3:
  230. level = logging.DEBUG
  231. log = logging.getLogger('test')
  232. log.setLevel(level)
  233. ch = logging.StreamHandler()
  234. ch.setLevel(level)
  235. formatter = logging.Formatter('%(message)s')
  236. ch.setFormatter(formatter)
  237. log.addHandler(ch)
  238. USAGE = '''%s [OPTIONS]
  239. -d dir # tests dir
  240. -p path # perf binary
  241. -t test # single test
  242. -v # verbose level
  243. ''' % sys.argv[0]
  244. def main():
  245. parser = optparse.OptionParser(usage=USAGE)
  246. parser.add_option("-t", "--test",
  247. action="store", type="string", dest="test")
  248. parser.add_option("-d", "--test-dir",
  249. action="store", type="string", dest="test_dir")
  250. parser.add_option("-p", "--perf",
  251. action="store", type="string", dest="perf")
  252. parser.add_option("-v", "--verbose",
  253. action="count", dest="verbose")
  254. options, args = parser.parse_args()
  255. if args:
  256. parser.error('FAILED wrong arguments %s' % ' '.join(args))
  257. return -1
  258. setup_log(options.verbose)
  259. if not options.test_dir:
  260. print 'FAILED no -d option specified'
  261. sys.exit(-1)
  262. if not options.test:
  263. options.test = 'test*'
  264. try:
  265. run_tests(options)
  266. except Fail, obj:
  267. print "FAILED %s" % obj.getMsg();
  268. sys.exit(-1)
  269. sys.exit(0)
  270. if __name__ == '__main__':
  271. main()