3 # Thomas Nagy, 2007-2010 (ita)
6 Debugging helper for parallel compilation, outputs
7 a file named pdebug.svg in the source directory::
10 opt.load('parallel_debug')
15 import re, sys, threading, time, traceback
17 from Queue import Queue
19 from queue import Queue
20 from waflib import Runner, Options, Task, Logs, Errors
22 SVG_TEMPLATE = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
23 <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
24 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0"
25 x="${project.x}" y="${project.y}" width="${project.width}" height="${project.height}" id="svg602" xml:space="preserve">
27 <style type='text/css' media='screen'>
28 g.over rect { stroke:#FF0000; fill-opacity:0.4 }
31 <script type='text/javascript'><![CDATA[
32 var svg = document.getElementsByTagName('svg')[0];
34 svg.addEventListener('mouseover', function(e) {
35 var g = e.target.parentNode;
36 var x = document.getElementById('r_' + g.id);
38 g.setAttribute('class', g.getAttribute('class') + ' over');
39 x.setAttribute('class', x.getAttribute('class') + ' over');
40 showInfo(e, g.id, e.target.attributes.tooltip.value);
44 svg.addEventListener('mouseout', function(e) {
45 var g = e.target.parentNode;
46 var x = document.getElementById('r_' + g.id);
48 g.setAttribute('class', g.getAttribute('class').replace(' over', ''));
49 x.setAttribute('class', x.getAttribute('class').replace(' over', ''));
54 function showInfo(evt, txt, details) {
56 tooltip = document.getElementById('tooltip');
58 var t = document.getElementById('tooltiptext');
59 t.firstChild.data = txt + " " + details;
61 var x = evt.clientX + 9;
62 if (x > 250) { x -= t.getComputedTextLength() + 16; }
63 var y = evt.clientY + 20;
64 tooltip.setAttribute("transform", "translate(" + x + "," + y + ")");
65 tooltip.setAttributeNS(null, "visibility", "visible");
67 var r = document.getElementById('tooltiprect');
68 r.setAttribute('width', t.getComputedTextLength() + 6);
72 function hideInfo(evt) {
73 var tooltip = document.getElementById('tooltip');
74 tooltip.setAttributeNS(null,"visibility","hidden");
78 <!-- inkscape requires a big rectangle or it will not export the pictures properly -->
80 x='${project.x}' y='${project.y}' width='${project.width}' height='${project.height}'
81 style="font-size:10;fill:#ffffff;fill-opacity:0.01;fill-rule:evenodd;stroke:#ffffff;"></rect>
84 <text x="${project.title_x}" y="${project.title_y}"
85 style="font-size:15px; text-anchor:middle; font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans">${project.title}</text>
89 ${for cls in project.groups}
90 <g id='${cls.classname}'>
91 ${for rect in cls.rects}
92 <rect x='${rect.x}' y='${rect.y}' width='${rect.width}' height='${rect.height}' tooltip='${rect.name}' style="font-size:10;fill:${rect.color};fill-rule:evenodd;stroke:#000000;stroke-width:0.4;" />
97 ${for info in project.infos}
98 <g id='r_${info.classname}'>
99 <rect x='${info.x}' y='${info.y}' width='${info.width}' height='${info.height}' style="font-size:10;fill:${info.color};fill-rule:evenodd;stroke:#000000;stroke-width:0.4;" />
100 <text x="${info.text_x}" y="${info.text_y}"
101 style="font-size:12px;font-style:normal;font-weight:normal;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;font-family:Bitstream Vera Sans"
106 ${if project.tooltip}
107 <g transform="translate(0,0)" visibility="hidden" id="tooltip">
108 <rect id="tooltiprect" y="-15" x="-3" width="1" height="20" style="stroke:black;fill:#edefc2;stroke-width:1"/>
109 <text id="tooltiptext" style="font-family:Arial; font-size:12;fill:black;"> </text>
116 COMPILE_TEMPLATE = '''def f(project):
118 def xml_escape(value):
119 return value.replace("&", "&").replace('"', """).replace("'", "'").replace("<", "<").replace(">", ">")
124 reg_act = re.compile(r"(?P<backslash>\\)|(?P<dollar>\$\$)|(?P<subst>\$\{(?P<code>[^}]*?)\})", re.M)
125 def compile_template(line):
135 extr.append(g('code'))
139 line2 = reg_act.sub(repl, line)
140 params = line2.split('<<|@|>>')
149 buf.append(indent * '\t' + txt)
151 for x in range(len(extr)):
153 app("lst.append(%r)" % params[x])
156 if f.startswith(('if', 'for')):
159 elif f.startswith('py:'):
161 elif f.startswith(('endif', 'endfor')):
163 elif f.startswith(('else', 'elif')):
167 elif f.startswith('xml:'):
168 app('lst.append(xml_escape(%s))' % f[4:])
170 #app('lst.append((%s) or "cannot find %s")' % (f, f))
171 app('lst.append(str(%s))' % f)
175 app("lst.append(%r)" % params[-1])
177 fun = COMPILE_TEMPLATE % "\n\t".join(buf)
178 # uncomment the following to debug the template
179 #for i, x in enumerate(fun.splitlines()):
181 return Task.funex(fun)
189 'YELLOW' : '#fefe44',
197 info = [] # list of (text,color)
199 def map_to_color(name):
203 cls = Task.classes[name]
205 return color2code['RED']
208 if cls.color in color2code:
209 return color2code[cls.color]
210 return color2code['RED']
213 m = self.generator.bld.producer
215 # TODO another place for this?
216 del self.generator.bld.task_sigs[self.uid()]
220 self.generator.bld.producer.set_running(1, self)
225 self.err_msg = traceback.format_exc()
226 self.hasrun = Task.EXCEPTION
229 m.error_handler(self)
234 self.hasrun = Task.CRASHED
238 except Errors.WafError:
241 self.err_msg = traceback.format_exc()
242 self.hasrun = Task.EXCEPTION
244 self.hasrun = Task.SUCCESS
245 if self.hasrun != Task.SUCCESS:
246 m.error_handler(self)
248 self.generator.bld.producer.set_running(-1, self)
250 Task.Task.process_back = Task.Task.process
251 Task.Task.process = process
253 old_start = Runner.Parallel.start
256 Options.options.dband
257 except AttributeError:
258 self.bld.fatal('use def options(opt): opt.load("parallel_debug")!')
260 self.taskinfo = Queue()
264 Runner.Parallel.start = do_start
266 lock_running = threading.Lock()
267 def set_running(self, by, tsk):
270 cache = self.lock_cache
271 except AttributeError:
272 cache = self.lock_cache = {}
276 vals = cache.values()
277 for i in range(self.numjobs):
285 self.taskinfo.put( (i, id(tsk), time.time(), tsk.__class__.__name__, self.processed, self.count, by, ",".join(map(str, tsk.outputs))) )
286 Runner.Parallel.set_running = set_running
288 def name2class(name):
289 return name.replace(' ', '_').replace('.', '_')
291 def make_picture(producer):
292 # first, cast the parameters
293 if not hasattr(producer.bld, 'path'):
299 tup = producer.taskinfo.get(False)
300 tmp.append(list(tup))
305 ini = float(tmp[0][2])
318 info.append((name, map_to_color(name)))
319 info.sort(key=lambda x: x[0])
325 acc.append("%d %d %f %r %d %d %d %s" % (x[0], x[1], x[2] - ini, x[3], x[4], x[5], thread_count, x[7]))
327 data_node = producer.bld.path.make_node('pdebug.dat')
328 data_node.write('\n'.join(acc))
330 tmp = [lst[:2] + [float(lst[2]) - ini] + lst[3:] for lst in tmp]
335 st[l[0]] = len(st.keys())
336 tmp = [ [st[lst[0]]] + lst[1:] for lst in tmp ]
337 THREAD_AMOUNT = len(st.keys())
342 st[l[1]] = len(st.keys())
343 tmp = [ [lst[0]] + [st[lst[1]]] + lst[2:] for lst in tmp ]
346 BAND = Options.options.dband
350 for x in range(len(tmp)):
360 for y in range(x + 1, len(tmp)):
364 #print id, thread_id, begin, end
365 #acc.append( ( 10*thread_id, 10*(thread_id+1), 10*begin, 10*end ) )
366 acc.append( (BAND * begin, BAND*thread_id, BAND*end - BAND*begin, BAND, line[3], line[7]) )
369 if Options.options.dmaxtime < 0.1:
376 gwidth = BAND * Options.options.dmaxtime
378 ratio = float(Options.options.dwidth) / gwidth
379 gwidth = Options.options.dwidth
380 gheight = BAND * (THREAD_AMOUNT + len(info) + 1.5)
383 # simple data model for our template
384 class tobject(object):
390 model.width = gwidth + 4
391 model.height = gheight + 4
393 model.tooltip = not Options.options.dnotooltip
395 model.title = Options.options.dtitle
396 model.title_x = gwidth / 2
397 model.title_y = gheight + - 5
400 for (x, y, w, h, clsname, name) in acc:
402 groups[clsname].append((x, y, w, h, name))
404 groups[clsname] = [(x, y, w, h, name)]
406 # groups of rectangles (else js highlighting is slow)
410 model.groups.append(g)
411 g.classname = name2class(cls)
413 for (x, y, w, h, name) in groups[cls]:
421 r.color = map_to_color(cls)
427 for (text, color) in info:
429 model.infos.append(inf)
430 inf.classname = name2class(text)
432 inf.y = 5 + (cnt + 0.5) * BAND
438 inf.text_x = 2 + 2 * BAND
439 inf.text_y = 5 + (cnt + 0.5) * BAND + 10
444 template1 = compile_template(SVG_TEMPLATE)
445 txt = template1(model)
447 node = producer.bld.path.make_node('pdebug.svg')
449 Logs.warn('Created the diagram %r', node)
452 opt.add_option('--dtitle', action='store', default='Parallel build representation for %r' % ' '.join(sys.argv),
453 help='title for the svg diagram', dest='dtitle')
454 opt.add_option('--dwidth', action='store', type='int', help='diagram width', default=800, dest='dwidth')
455 opt.add_option('--dtime', action='store', type='float', help='recording interval in seconds', default=0.009, dest='dtime')
456 opt.add_option('--dband', action='store', type='int', help='band width', default=22, dest='dband')
457 opt.add_option('--dmaxtime', action='store', type='float', help='maximum time, for drawing fair comparisons', default=0, dest='dmaxtime')
458 opt.add_option('--dnotooltip', action='store_true', help='disable tooltips', default=False, dest='dnotooltip')