graphsched.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. import re, sys, os
  4. from PIL import Image, ImageDraw, ImageFont
  5. # Font search paths and acceptable names. Order matters.
  6. FONT_DIRS = "/usr/share/fonts/truetype/freefont","/usr/share/fonts/truetype", "/usr/lib/fonts/", "/Library/Fonts"
  7. FONT_NAMES = "FreeMono.ttf", "Andale Mono.ttf", "Arial Black.ttf", "Hei.ttf.ttf", "Courier New.ttf", "DejaVuSans.ttf"
  8. def findfont(names=FONT_NAMES, dirs=FONT_DIRS):
  9. """Return first existing path or None."""
  10. for d in dirs:
  11. if os.path.isdir(d):
  12. for f in names:
  13. f = os.path.join(d, f)
  14. if os.path.isfile(f):
  15. return f
  16. assert False, 'Error: check FONT_NAMES / FONT_DIRS.'
  17. CMDS = ['LOAD', 'CPU', 'BLOCK', 'UNBLOCK', 'EXIT', 'DEADLINE']
  18. LOAD, CPU, BLOCK, UNBLOCK, EXIT, DEADLINE = range(6)
  19. COLOR_GRAY = ('#a0a0a0', '#d0d0d0')
  20. COLOR_BLACK = '#000000'
  21. COLORS = [
  22. ('#c0ffc0', '#e7ffe7'), # Verde claro
  23. ('#0000ff', '#b7b7f7'), # Azul
  24. ('#ff0000', '#f7b7b7'), # Rojo
  25. ('#d0d0d0', '#f4f4f4'), # Gris
  26. ('#00e000', '#b7efb7'), # Verde
  27. ('#ffff00', '#f7f7b7'), # Amarillo
  28. ('#c0c0ff', '#e7e7ff'), # Azul claro
  29. ]
  30. STATES = ['READY', 'BLOCKED', 'RUNNING', 'UNLOADED']
  31. READY, BLOCKED, RUNNING, UNLOAD, RUNNINGBLOCKED = range(5)
  32. def iround(m):
  33. """Rounds the number to the nearest number with only one significative digit."""
  34. n = 1
  35. while (m + n/2) / n >= 10:
  36. n*= 10
  37. while (m + n/2) / n >= 5:
  38. n*= 5
  39. rm = m - (m/n)*n
  40. return ((m+rm)/n)*n
  41. def parseData(fin):
  42. ln = 0
  43. result = []
  44. cores = 0
  45. settings = None
  46. idleCore = -1
  47. lastTick = -1
  48. for l in fin:
  49. ln += 1
  50. vls = l.split()
  51. if l and l[0] == '#':
  52. if l[:11] == '# SETTINGS ':
  53. settings = l[11:].strip()
  54. continue
  55. if (vls[0] not in CMDS):
  56. sys.stderr.write('Warning: Ignoring line %d: %s' % (ln, l))
  57. continue
  58. if len(vls) == 4 and vls[0] == 'CPU':
  59. if vls[1] != lastTick:
  60. idleCore = -1
  61. lastTick = vls[1]
  62. #Muestro solo el primer core en llegar a idle
  63. if vls[2] == "-1" and idleCore == -1:
  64. idleCore = int(vls[3])
  65. lastTick = vls[1]
  66. if vls[2] != "-1" or int(vls[3]) == idleCore:
  67. result.append((CMDS.index(vls[0]), int(vls[1]), int(vls[2]), int(vls[3])))
  68. core = int(vls[3])
  69. if (cores <=core):
  70. cores = core+1
  71. else:
  72. result.append((CMDS.index(vls[0]), int(vls[1]), int(vls[2]), -1))
  73. #Sobra una ronda de cores idles
  74. result.pop()
  75. return settings, result, cores
  76. def dataGantt(data):
  77. g = dict()
  78. for cmd, tm, pid, core in data:
  79. if pid not in g: g[pid] = []
  80. g[pid].append((tm,cmd,core))
  81. return g
  82. def drawGantt(data, fout, rg=3, width=1024, height=600, fontpath=None, ncores=None, settings=None, caption=None):
  83. if fontpath is None:
  84. fontpath = findfont()
  85. xmarks = 10
  86. subxmarks = 5
  87. n = len(data)
  88. xmin = min(min(tm for tm,_,_ in data[pid]) for pid in data)
  89. xmax = max(max(tm for tm,_,_ in data[pid]) for pid in data)+1
  90. # Inicializa Grafico
  91. xstp = iround((xmax+xmarks-1)/xmarks)
  92. xgap = xstp*xmarks
  93. ystp = 30
  94. if ystp*n > height: ystp = height/n
  95. gw,gh = width-60,n*ystp
  96. gx,gy = 5+20+ 30 , 5 + 30 + 5 + gh
  97. iw,ih = gx+gw+8, gy+5+17+5
  98. if caption: ih += 24
  99. # Nueva IMG
  100. img = Image.new("RGB", (iw,ih), (255,255,255))
  101. draw = ImageDraw.Draw(img)
  102. font = ImageFont.truetype(fontpath, 12)
  103. # Marcas en Y:
  104. pids = sorted(pid for pid in data if pid >= 0)
  105. if -1 in data: pids.append(-1)
  106. pids.reverse()
  107. for i in xrange(len(pids)):
  108. ly = gy - i*ystp - ystp/2
  109. draw.line((gx-2,ly,gx-4,ly), fill=COLOR_BLACK)
  110. txt = str(pids[i] if pids[i] >= 0 else 'IDLE')
  111. tw,th = draw.textsize(txt, font=font)
  112. draw.text((gx-2 -5 -tw, ly - th/2), txt, font=font, fill=COLOR_BLACK)
  113. # Marcas en X:
  114. for i in xrange(2*subxmarks*xmarks):
  115. x = xmin - xmin%xstp + xstp * i / subxmarks
  116. if x < xmin: continue
  117. if x > xmax: break
  118. lx = gx + x*gw / xmax
  119. draw.line((lx,gy+1,lx,gy+3), fill=COLOR_BLACK if i%subxmarks==0 else COLOR_GRAY[0])
  120. if x > xmin: draw.line((lx,gy-1,lx,gy-gh), fill=COLOR_BLACK if i%subxmarks==0 else COLOR_GRAY[0])
  121. if i%subxmarks==0:
  122. txt = str(x)
  123. tw,th = draw.textsize(txt, font=font)
  124. draw.text((lx-tw/2, gy+3), txt, font=font, fill=COLOR_BLACK)
  125. # Ejes
  126. draw.line((gx,gy,gx+gw,gy), fill=COLOR_BLACK)
  127. draw.line((gx-1,gy,gx-1,gy-gh), fill=COLOR_BLACK)
  128. # Leyenda
  129. lx,ly = gx,gy-gh-25
  130. bzs = 15
  131. for i in xrange(len(STATES)):
  132. draw.rectangle((lx,ly,lx+bzs,ly+bzs), fill=COLORS[i][0])
  133. draw.rectangle((lx+1,ly+1,lx+bzs-1,ly+bzs-1), fill=COLORS[i][1])
  134. lx += bzs + 3
  135. vl = STATES[i]
  136. tw,th = draw.textsize(vl, font=font)
  137. draw.text((lx, ly+(bzs-th)/2), vl, font=font, fill=COLOR_BLACK)
  138. lx += tw + 10
  139. if settings:
  140. draw.text((lx + 20, ly+(bzs-th)/2), str(settings), font=font, fill=COLOR_BLACK)
  141. if caption:
  142. draw.text((50, ih - 24), str(caption), font=font, fill=COLOR_BLACK)
  143. # Grafico
  144. for i in xrange(len(pids)):
  145. sts = [UNLOAD for j in xrange(xmax+2)]
  146. cores = [0 for j in xrange(xmax+2)]
  147. p = 0
  148. l = data[pids[i]]
  149. blk = False
  150. ldd = False
  151. deadline = 0
  152. for j in xrange(xmax+1):
  153. cpu = False
  154. core = -1
  155. while p < len(l) and l[p][0] <= j:
  156. ev = l[p][1]
  157. if ev == BLOCK: blk = True
  158. elif ev == DEADLINE: deadline = j
  159. elif ev == UNBLOCK: blk = False
  160. elif ev == LOAD: ldd = True
  161. elif ev == EXIT: ldd = False
  162. elif ev == CPU:
  163. cpu = True
  164. core = l[p][2]
  165. p += 1
  166. if not ldd and pids[i] != -1: st = UNLOAD
  167. elif cpu and blk: st = RUNNINGBLOCKED
  168. elif cpu and not blk: st = RUNNING
  169. elif not cpu and blk: st = BLOCKED
  170. else: st = READY
  171. sts[j] = st
  172. cores[j] = core
  173. ly = gy - i*ystp - ystp/2
  174. uy = ly-ystp/3
  175. by = ly+ystp/3
  176. loadedj = -1;
  177. unloadedx = -1
  178. for j in xrange(xmax):
  179. x = gx + j*gw / xmax
  180. nx = gx + (j+1)*gw / xmax
  181. st = sts[j]
  182. extend = (j>0) and (sts[j-1] == sts[j])
  183. if st != UNLOAD or True:
  184. if st == RUNNINGBLOCKED:
  185. extend = (j>0) and (sts[j-1] == BLOCKED or sts[j-1] == sts[j])
  186. draw.rectangle((x,uy-1,nx-1,ly), fill=COLORS[BLOCKED][0])
  187. draw.rectangle((x+1-(2 if extend else 0),uy,nx-2,ly-1), fill=COLORS[BLOCKED][1])
  188. extend = (j>0) and (sts[j-1] == RUNNING or sts[j-1] == sts[j])
  189. draw.rectangle((x,ly+1,nx-1,by+1), fill=COLORS[RUNNING][0])
  190. draw.rectangle((x+1-(2 if extend else 0),ly+2,nx-2,by), fill=COLORS[RUNNING][1])
  191. #l TIENE LA TUPLA (CICLO, , CORE)
  192. #ACA HAY QUE CHEQUEAR SI ESTA TUPLA ES LA PRIMERA CON CICLO C Y EL CICLO (C-1) NO ESTA EN LA LISTA
  193. #if pids[i] >= 0:
  194. # draw.text((x+1, by+1), str(cores[j]), font=font, fill=COLOR_BLACK)
  195. if unloadedx == -1:
  196. unloadedx = x
  197. loadedj = cores[j];
  198. elif loadedj != cores[j]:
  199. dist = (x-unloadedx)/2
  200. draw.text((unloadedx + dist -2, by-16), str(loadedj), font=font, fill=COLOR_BLACK)
  201. unloadedx = x
  202. loadedj = cores[j];
  203. elif st == RUNNING:
  204. draw.rectangle((x,uy-1,nx,by+1), fill=COLORS[st][0])
  205. draw.rectangle((x+1-(2 if extend else 0),uy,nx-2,by), fill=COLORS[st][1])
  206. if unloadedx == -1:
  207. unloadedx = x
  208. loadedj = cores[j];
  209. elif loadedj != cores[j]:
  210. if pids[i] >= 0:
  211. dist = (x-unloadedx)/2
  212. draw.text((unloadedx + dist -2, by-16), str(loadedj), font=font, fill=COLOR_BLACK)
  213. unloadedx = x
  214. loadedj = cores[j];
  215. #l TIENE LA TUPLA (CICLO, , CORE)
  216. #ACA HAY QUE CHEQUEAR SI ESTA TUPLA ES LA PRIMERA CON CICLO C Y EL CICLO (C-1) NO ESTA EN LA LISTA
  217. #if pids[i] >= 0:
  218. # draw.text((x+5, by-16), str(cores[j]), font=font, fill=COLOR_BLACK)
  219. else:
  220. draw.rectangle((x,uy-1,nx,by+1), fill=COLORS[st][0])
  221. draw.rectangle((x+1-(2 if extend else 0),uy,nx-2,by), fill=COLORS[st][1])
  222. if unloadedx <> -1:
  223. if pids[i] >= 0:
  224. dist = (x-unloadedx)/2
  225. if ncores is not None and ncores>1:
  226. draw.text((unloadedx + dist -3, by-16), str(loadedj), font=font, fill=COLOR_BLACK)
  227. draw.text((unloadedx + dist -2, by-16), str(loadedj), font=font, fill=COLOR_BLACK) # 'bold'
  228. unloadedx = -1
  229. if st == RUNNING and j>0 and sts[j-1] == RUNNINGBLOCKED:
  230. draw.rectangle((x+1-2,ly+2,nx-2,by), fill=COLORS[st][1])
  231. if st == BLOCKED and j>0 and sts[j-1] == RUNNINGBLOCKED:
  232. draw.rectangle((x+1-2,uy,nx-2,ly-1), fill=COLORS[st][1])
  233. if deadline > 0 and j == deadline:
  234. #Linea de DEADLINE
  235. draw.line((nx-1,uy-1,nx-1,by+1), fill='#790000',width=6)
  236. if isinstance(fout, str):
  237. dr = os.path.dirname(fout)
  238. if dr != "" and not os.path.isdir(dr):
  239. os.makedirs(dr, 0755)
  240. img.save(fout, "PNG")
  241. #img.resize(((png_box+1)*n-1, png_box), Image.ANTIALIAS).save(pngfn, "PNG")
  242. def main(argv):
  243. if '-c' in argv or '--caption' in argv:
  244. hit = '-c' if '-c' in argv else '--caption'
  245. pos = argv.index(hit)
  246. argv.pop(pos)
  247. caption = argv.pop(pos)
  248. else:
  249. caption = None
  250. if len(argv) <= 1:
  251. fin = sys.stdin
  252. fout = sys.stdout
  253. else:
  254. fin = open(argv[1], 'r')
  255. fout = argv[1]+'.png'
  256. settings, data, cores = parseData(fin)
  257. gantt = dataGantt(data)
  258. drawGantt(gantt, fout, ncores=cores, settings=settings, caption=caption)
  259. if __name__ == "__main__":
  260. main(sys.argv)