Debian Codegraph @

rpython/tool/logparser.py

raw symbols SCIP
1 #! /usr/bin/env python
2 """
3 Syntax:
4 python logparser.py <action> <logfilename> <output> <options...>
5
6 Actions:
7 draw-time draw a timeline image of the log (format PNG by default)
8 print-summary print a summary of the log
9 """
10 from __future__ import print_function
11
12 import sys, re
13 from rpython.rlib.debug import DebugLog
14 from rpython.tool import progressbar
15
16 def parse_log_file(filename, verbose=True):
17 f = open(filename, 'r')
18 if f.read(2) == 'BZ':
19 f.close()
20 import bz2
21 f = bz2.BZ2File(filename, 'r')
22 else:
23 f.seek(0)
24 lines = f.readlines()
25 f.close()
26 #
27 return parse_log(lines, verbose=verbose)
28
29 def parse_log(lines, verbose=False):
30 color = "(?:\x1b.*?m)?"
31 r_start = re.compile(color + r"\[([0-9a-fA-F]+)\] \{([\w-]+)" + color + "$")
32 r_stop = re.compile(color + r"\[([0-9a-fA-F]+)\] ([\w-]+)\}" + color + "$")
33 lasttime = 0
34 log = DebugLog()
35 time_decrase = False
36 performance_log = True
37 nested = 0
38 #
39 if verbose and sys.stdout.isatty():
40 progress = progressbar.ProgressBar(color='green')
41 counter = 0
42 else:
43 progress = None
44 single_percent = len(lines) / 100
45 if verbose:
46 vnext = 0
47 else:
48 vnext = -1
49 for i, line in enumerate(lines):
50 if i == vnext:
51 if progress is not None:
52 progress.render(counter)
53 counter += 1
54 vnext += single_percent
55 else:
56 sys.stderr.write('%d%%..' % int(100.0*i/len(lines)))
57 vnext += 500000
58 line = line.rstrip()
59 match = r_start.match(line)
60 if match:
61 record = log.debug_start
62 nested += 1
63 else:
64 match = r_stop.match(line)
65 if match:
66 record = log.debug_stop
67 nested -= 1
68 else:
69 log.debug_print(line)
70 performance_log = performance_log and nested == 0
71 continue
72 time = int(int(match.group(1), 16))
73 time_decrase = time_decrase or time < lasttime
74 lasttime = time
75 try:
76 record(match.group(2), time=int(match.group(1), 16))
77 except:
78 print("Line", i)
79 raise
80 if verbose:
81 sys.stderr.write('loaded\n')
82 if performance_log and time_decrase:
83 print("The time decreases! The log file may have been"
84 " produced on a multi-CPU machine and the process"
85 " moved between CPUs.")
86 return log
87
88 def extract_category(log, catprefix='', toplevel=False):
89 got = []
90 resulttext = []
91 for entry in log:
92 if entry[0] == 'debug_print':
93 resulttext.append(entry[1])
94 elif len(entry) == 4:
95 got.extend(extract_category(
96 entry[3], catprefix, toplevel=entry[0].startswith(catprefix)))
97 else:
98 resulttext.append('... LOG TRUCATED ...')
99 if toplevel:
100 resulttext.append('')
101 got.insert(0, '\n'.join(resulttext))
102 return got
103
104 def print_log(log):
105 for entry in log:
106 if entry[0] == 'debug_print':
107 print(entry[1])
108 else:
109 print("{%s" % entry[0])
110 if len(entry)>3:
111 print_log(entry[3])
112 print("%s}" % entry[0])
113
114 def kill_category(log, catprefix=''):
115 newlog = []
116 for entry in log:
117 if not entry[0].startswith(catprefix):
118 if len(entry) > 3:
119 newlog.append(entry[:3] +
120 (kill_category(entry[3], catprefix),))
121 else:
122 newlog.append(entry)
123 return newlog
124
125 def getsubcategories(log):
126 return [entry for entry in log if entry[0] != 'debug_print']
127
128 def gettimebounds(log):
129 # returns (mintime, maxtime)
130 maincats = getsubcategories(log)
131 return (maincats[0][1], maincats[-1][2])
132
133 def gettotaltimes(log):
134 # returns a dict {'label' or None: totaltime}
135 def rectime(category1, timestart1, timestop1, subcats):
136 substartstop = []
137 for entry in getsubcategories(subcats):
138 if len(entry) != 4:
139 continue
140 rectime(*entry)
141 substartstop.append(entry[1:3]) # (start, stop)
142 # compute the total time for category1 as the part of the
143 # interval [timestart1, timestop1] that is not covered by
144 # any interval from one of the subcats.
145 mytime = 0
146 substartstop.sort()
147 for substart, substop in substartstop:
148 if substart >= timestop1:
149 break
150 if substart > timestart1:
151 mytime += substart - timestart1
152 if timestart1 < substop:
153 timestart1 = substop
154 if timestart1 < timestop1:
155 mytime += timestop1 - timestart1
156 #
157 try:
158 result[category1] += mytime
159 except KeyError:
160 result[category1] = mytime
161 #
162 result = {}
163 timestart0, timestop0 = gettimebounds(log)
164 rectime(None, timestart0, timestop0, log)
165 return result
166
167 # ____________________________________________________________
168
169
170 COLORS = {
171 None: (248, 248, 248),
172 '': (160, 160, 160),
173 'gc-': (224, 0, 0),
174 'gc-minor': (192, 0, 16),
175 'gc-collect': (255, 0, 0),
176 'jit-': (0, 224, 0),
177 'jit-running': (192, 255, 160),
178 'jit-tracing': (0, 255, 0),
179 'jit-optimize': (160, 255, 0),
180 'jit-backend': (0, 255, 144),
181 'jit-blackhole': (0, 160, 0),
182 }
183 SUMMARY = {
184 None: 'normal execution',
185 '': 'other',
186 'gc-': 'gc',
187 'jit-': 'jit',
188 'jit-running': 'jit-running',
189 }
190
191 def getcolor(category):
192 while category not in COLORS:
193 category = category[:-1]
194 return COLORS[category]
195
196 def getlightercolor((r, g, b)):
197 return ((r*2+255)//3, (g*2+255)//3, (b*2+255)//3)
198
199 def getdarkercolor((r, g, b)):
200 return (r*2//3, g*2//3, b*2//3)
201
202 def getlabel(text, _cache={}):
203 try:
204 return _cache[text]
205 except KeyError:
206 pass
207 from PIL import Image, ImageDraw
208 if None not in _cache:
209 image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
210 draw = ImageDraw.Draw(image)
211 _cache[None] = draw
212 else:
213 draw = _cache[None]
214 sx, sy = draw.textsize(text)
215 texthoriz = Image.new("RGBA", (sx, sy), (0, 0, 0, 0))
216 ImageDraw.Draw(texthoriz).text((0, 0), text, fill=(0, 0, 0))
217 textvert = texthoriz.rotate(90)
218 _cache[text] = sx, sy, texthoriz, textvert
219 return _cache[text]
220
221 def bevelrect(draw, (x1, y1, x2, y2), color):
222 if x2 <= x1:
223 x2 = x1 + 1 # minimal width
224 elif x2 >= x1 + 4:
225 draw.line((x1, y1+1, x1, y2-1), fill=getlightercolor(color))
226 x1 += 1
227 x2 -= 1
228 draw.line((x2, y1+1, x2, y2-1), fill=getdarkercolor(color))
229 draw.line((x1, y1, x2-1, y1), fill=getlightercolor(color))
230 y1 += 1
231 y2 -= 1
232 draw.line((x1, y2, x2-1, y2), fill=getdarkercolor(color))
233 draw.rectangle((x1, y1, x2-1, y2-1), fill=color)
234
235 # ----------
236
237 def get_timeline_image(log, width, height):
238 from PIL import Image, ImageDraw
239 timestart0, timestop0 = gettimebounds(log)
240 assert timestop0 > timestart0
241 timefactor = float(width) / (timestop0 - timestart0)
242 #
243 def recdraw(sublist, subheight):
244 firstx1 = None
245 for entry in sublist:
246 try:
247 category1, timestart1, timestop1, subcats = entry
248 except ValueError:
249 continue
250 x1 = int((timestart1 - timestart0) * timefactor)
251 x2 = int((timestop1 - timestart0) * timefactor)
252 y1 = (height - subheight) / 2
253 y2 = y1 + subheight
254 y1 = int(y1)
255 y2 = int(y2)
256 color = getcolor(category1)
257 if firstx1 is None:
258 firstx1 = x1
259 bevelrect(draw, (x1, y1, x2, y2), color)
260 subcats = getsubcategories(subcats)
261 if subcats:
262 x2 = recdraw(subcats, subheight * 0.94) - 1
263 sx, sy, texthoriz, textvert = getlabel(category1)
264 if sx <= x2-x1-8:
265 image.paste(texthoriz, (x1+5, y1+5), texthoriz)
266 elif sy <= x2-x1-2:
267 image.paste(textvert, (x1+1, y1+5), textvert)
268 return firstx1
269 #
270 image = Image.new("RGBA", (width, height), (255, 255, 255, 0))
271 draw = ImageDraw.Draw(image)
272 recdraw(getsubcategories(log), height)
273 return image
274
275 # ----------
276
277 def render_histogram(times, time0, labels, width, barheight):
278 # Render a histogram showing horizontal time bars are given by the
279 # 'times' dictionary. Each entry has the label specified by 'labels',
280 # or by default the key used in 'times'.
281 from PIL import Image, ImageDraw
282 times = [(time, key) for (key, time) in times.items()]
283 times.sort()
284 times.reverse()
285 images = []
286 for time, key in times:
287 fraction = float(time) / time0
288 if fraction < 0.01:
289 break
290 color = getcolor(key)
291 image = Image.new("RGBA", (width, barheight), (255, 255, 255, 0))
292 draw = ImageDraw.Draw(image)
293 x2 = int(fraction * width)
294 bevelrect(draw, (0, 0, x2, barheight), color)
295 # draw the labels "x%" and "key"
296 percent = "%.1f%%" % (100.0 * fraction,)
297 s1x, s1y, textpercent, vtextpercent = getlabel(percent)
298 s2x, _, textlabel, _ = getlabel(labels.get(key, key))
299 t1x = 5
300 if t1x + s1x >= x2 - 3:
301 if t1x + s1y < x2 - 3:
302 textpercent = vtextpercent
303 s1x = s1y
304 else:
305 t1x = x2 + 6
306 t2x = t1x + s1x + 12
307 if t2x + s2x >= x2 - 3:
308 t2x = max(t2x, x2 + 8)
309 image.paste(textpercent, (t1x, 5), textpercent)
310 image.paste(textlabel, (t2x, 5), textlabel)
311 images.append(image)
312 if not images:
313 return None
314 return combine(images, spacing=0, border=1, horizontal=False)
315
316 def get_timesummary_single_image(totaltimes, totaltime0, componentdict,
317 width, barheight):
318 # Compress the totaltimes dict so that its only entries left are
319 # from componentdict. We do that by taking the times assigned to
320 # subkeys in totaltimes and adding them to the superkeys specified
321 # in componentdict.
322 totaltimes = totaltimes.copy()
323 for key, value in totaltimes.items():
324 if key in componentdict:
325 continue
326 del totaltimes[key]
327 if key is not None:
328 while key not in componentdict:
329 key = key[:-1]
330 try:
331 totaltimes[key] += value
332 except KeyError:
333 totaltimes[key] = value
334 return render_histogram(totaltimes, totaltime0, componentdict,
335 width, barheight)
336
337 def get_timesummary_image(log, summarywidth, summarybarheight):
338 timestart0, timestop0 = gettimebounds(log)
339 totaltime0 = timestop0 - timestart0
340 totaltimes = gettotaltimes(log)
341 spacing = 50
342 width = (summarywidth - spacing) // 2
343 img1 = get_timesummary_single_image(totaltimes, totaltime0, SUMMARY,
344 width, summarybarheight)
345 if None in totaltimes:
346 del totaltimes[None]
347 img2 = render_histogram(totaltimes, totaltime0, {},
348 width, summarybarheight)
349 if img2 is None:
350 return img1
351 return combine([img1, img2], spacing=spacing, horizontal=True)
352
353 # ----------
354
355 def combine(imagelist, spacing=50, border=0, horizontal=False):
356 if len(imagelist) <= 1 and not border:
357 return imagelist[0]
358 from PIL import Image, ImageDraw
359 wlist = [image.size[0] for image in imagelist]
360 hlist = [image.size[1] for image in imagelist]
361 if horizontal:
362 w = sum(wlist) + spacing*(len(imagelist)-1)
363 h = max(hlist)
364 else:
365 w = max(wlist)
366 h = sum(hlist) + spacing*(len(imagelist)-1)
367 w += 2*border
368 h += 2*border
369 bigimage = Image.new("RGBA", (w, h), (255, 255, 255, 0))
370 if border:
371 draw = ImageDraw.Draw(bigimage)
372 draw.rectangle((0, 0, w-1, border-1), fill=(0, 0, 0))
373 draw.rectangle((0, h-border, w-1, h-1), fill=(0, 0, 0))
374 draw.rectangle((0, 0, border-1, h-1), fill=(0, 0, 0))
375 draw.rectangle((w-1, 0, w-border, h-1), fill=(0, 0, 0))
376 x = border
377 y = border
378 for image in imagelist:
379 bigimage.paste(image, (x, y))
380 if horizontal:
381 x += image.size[0] + spacing
382 else:
383 y += image.size[1] + spacing
384 return bigimage
385
386 def draw_timeline_image(log, output=None, mainwidth=3000, mainheight=150,
387 summarywidth=850, summarybarheight=40):
388 mainwidth = int(mainwidth)
389 mainheight = int(mainheight)
390 summarywidth = int(summarywidth)
391 summarybarheight = int(summarybarheight)
392 images = []
393 if mainwidth > 0 and mainheight > 0:
394 images.append(get_timeline_image(log, mainwidth, mainheight))
395 if summarywidth > 0 and summarybarheight > 0:
396 images.append(get_timesummary_image(log, summarywidth,
397 summarybarheight))
398 image = combine(images, horizontal=False)
399 if output is None:
400 image.save(sys.stdout, format='png')
401 else:
402 image.save(output)
403
404 def print_summary(log, out):
405 totaltimes = gettotaltimes(log)
406 if out == '-':
407 outfile = sys.stdout
408 else:
409 outfile = open(out, "w")
410 l = totaltimes.items()
411 l.sort(cmp=lambda a, b: cmp(b[1], a[1]))
412 total = sum([b for a, b in l])
413 for a, b in l:
414 if a is None:
415 a = 'normal-execution'
416 s = " " * (50 - len(a))
417 print(a, s, "%.2f" % (b*100./total) + "%", file=outfile)
418 if out != '-':
419 outfile.close()
420
421 # ____________________________________________________________
422
423
424 ACTIONS = {
425 'draw-time': (draw_timeline_image, ['output=',
426 'mainwidth=', 'mainheight=',
427 'summarywidth=', 'summarybarheight=',
428 ]),
429 'print-summary': (print_summary, []),
430 }
431
432 if __name__ == '__main__':
433 import getopt
434 if len(sys.argv) < 3:
435 print(__doc__)
436 sys.exit(2)
437 action = sys.argv[1]
438 func, longopts = ACTIONS[action]
439 options, args = getopt.gnu_getopt(sys.argv[2:], '', longopts)
440 if len(args) != 2:
441 print(__doc__)
442 sys.exit(2)
443
444 kwds = {}
445 for name, value in options:
446 assert name.startswith('--')
447 kwds[name[2:]] = value
448 log = parse_log_file(args[0])
449 func(log, args[1], **kwds)