bootgraph.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. # Tool for analyzing boot timing
  5. # Copyright (c) 2013, Intel Corporation.
  6. #
  7. # This program is free software; you can redistribute it and/or modify it
  8. # under the terms and conditions of the GNU General Public License,
  9. # version 2, as published by the Free Software Foundation.
  10. #
  11. # This program is distributed in the hope it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  14. # more details.
  15. #
  16. # Authors:
  17. # Todd Brandt <todd.e.brandt@linux.intel.com>
  18. #
  19. # Description:
  20. # This tool is designed to assist kernel and OS developers in optimizing
  21. # their linux stack's boot time. It creates an html representation of
  22. # the kernel boot timeline up to the start of the init process.
  23. #
  24. # ----------------- LIBRARIES --------------------
  25. import sys
  26. import time
  27. import os
  28. import string
  29. import re
  30. import platform
  31. import shutil
  32. from datetime import datetime, timedelta
  33. from subprocess import call, Popen, PIPE
  34. import sleepgraph as aslib
  35. def pprint(msg):
  36. print(msg)
  37. sys.stdout.flush()
  38. # ----------------- CLASSES --------------------
  39. # Class: SystemValues
  40. # Description:
  41. # A global, single-instance container used to
  42. # store system values and test parameters
  43. class SystemValues(aslib.SystemValues):
  44. title = 'BootGraph'
  45. version = '2.2'
  46. hostname = 'localhost'
  47. testtime = ''
  48. kernel = ''
  49. dmesgfile = ''
  50. ftracefile = ''
  51. htmlfile = 'bootgraph.html'
  52. testdir = ''
  53. kparams = ''
  54. result = ''
  55. useftrace = False
  56. usecallgraph = False
  57. suspendmode = 'boot'
  58. max_graph_depth = 2
  59. graph_filter = 'do_one_initcall'
  60. reboot = False
  61. manual = False
  62. iscronjob = False
  63. timeformat = '%.6f'
  64. bootloader = 'grub'
  65. blexec = []
  66. def __init__(self):
  67. self.kernel, self.hostname = 'unknown', platform.node()
  68. self.testtime = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
  69. if os.path.exists('/proc/version'):
  70. fp = open('/proc/version', 'r')
  71. self.kernel = self.kernelVersion(fp.read().strip())
  72. fp.close()
  73. self.testdir = datetime.now().strftime('boot-%y%m%d-%H%M%S')
  74. def kernelVersion(self, msg):
  75. m = re.match(r'^[Ll]inux *[Vv]ersion *(?P<v>\S*) .*', msg)
  76. if m:
  77. return m.group('v')
  78. return 'unknown'
  79. def checkFtraceKernelVersion(self):
  80. m = re.match(r'^(?P<x>[0-9]*)\.(?P<y>[0-9]*)\.(?P<z>[0-9]*).*', self.kernel)
  81. if m:
  82. val = tuple(map(int, m.groups()))
  83. if val >= (4, 10, 0):
  84. return True
  85. return False
  86. def kernelParams(self):
  87. cmdline = 'initcall_debug log_buf_len=32M'
  88. if self.useftrace:
  89. if self.cpucount > 0:
  90. bs = min(self.memtotal // 2, 2*1024*1024) // self.cpucount
  91. else:
  92. bs = 131072
  93. cmdline += ' trace_buf_size=%dK trace_clock=global '\
  94. 'trace_options=nooverwrite,funcgraph-abstime,funcgraph-cpu,'\
  95. 'funcgraph-duration,funcgraph-proc,funcgraph-tail,'\
  96. 'nofuncgraph-overhead,context-info,graph-time '\
  97. 'ftrace=function_graph '\
  98. 'ftrace_graph_max_depth=%d '\
  99. 'ftrace_graph_filter=%s' % \
  100. (bs, self.max_graph_depth, self.graph_filter)
  101. return cmdline
  102. def setGraphFilter(self, val):
  103. master = self.getBootFtraceFilterFunctions()
  104. fs = ''
  105. for i in val.split(','):
  106. func = i.strip()
  107. if func == '':
  108. doError('badly formatted filter function string')
  109. if '[' in func or ']' in func:
  110. doError('loadable module functions not allowed - "%s"' % func)
  111. if ' ' in func:
  112. doError('spaces found in filter functions - "%s"' % func)
  113. if func not in master:
  114. doError('function "%s" not available for ftrace' % func)
  115. if not fs:
  116. fs = func
  117. else:
  118. fs += ','+func
  119. if not fs:
  120. doError('badly formatted filter function string')
  121. self.graph_filter = fs
  122. def getBootFtraceFilterFunctions(self):
  123. self.rootCheck(True)
  124. fp = open(self.tpath+'available_filter_functions')
  125. fulllist = fp.read().split('\n')
  126. fp.close()
  127. list = []
  128. for i in fulllist:
  129. if not i or ' ' in i or '[' in i or ']' in i:
  130. continue
  131. list.append(i)
  132. return list
  133. def myCronJob(self, line):
  134. if '@reboot' not in line:
  135. return False
  136. if 'bootgraph' in line or 'analyze_boot.py' in line or '-cronjob' in line:
  137. return True
  138. return False
  139. def cronjobCmdString(self):
  140. cmdline = '%s -cronjob' % os.path.abspath(sys.argv[0])
  141. args = iter(sys.argv[1:])
  142. for arg in args:
  143. if arg in ['-h', '-v', '-cronjob', '-reboot', '-verbose']:
  144. continue
  145. elif arg in ['-o', '-dmesg', '-ftrace', '-func']:
  146. next(args)
  147. continue
  148. elif arg == '-result':
  149. cmdline += ' %s "%s"' % (arg, os.path.abspath(next(args)))
  150. continue
  151. elif arg == '-cgskip':
  152. file = self.configFile(next(args))
  153. cmdline += ' %s "%s"' % (arg, os.path.abspath(file))
  154. continue
  155. cmdline += ' '+arg
  156. if self.graph_filter != 'do_one_initcall':
  157. cmdline += ' -func "%s"' % self.graph_filter
  158. cmdline += ' -o "%s"' % os.path.abspath(self.testdir)
  159. return cmdline
  160. def manualRebootRequired(self):
  161. cmdline = self.kernelParams()
  162. pprint('To generate a new timeline manually, follow these steps:\n\n'\
  163. '1. Add the CMDLINE string to your kernel command line.\n'\
  164. '2. Reboot the system.\n'\
  165. '3. After reboot, re-run this tool with the same arguments but no command (w/o -reboot or -manual).\n\n'\
  166. 'CMDLINE="%s"' % cmdline)
  167. sys.exit()
  168. def blGrub(self):
  169. blcmd = ''
  170. for cmd in ['update-grub', 'grub-mkconfig', 'grub2-mkconfig']:
  171. if blcmd:
  172. break
  173. blcmd = self.getExec(cmd)
  174. if not blcmd:
  175. doError('[GRUB] missing update command')
  176. if not os.path.exists('/etc/default/grub'):
  177. doError('[GRUB] missing /etc/default/grub')
  178. if 'grub2' in blcmd:
  179. cfg = '/boot/grub2/grub.cfg'
  180. else:
  181. cfg = '/boot/grub/grub.cfg'
  182. if not os.path.exists(cfg):
  183. doError('[GRUB] missing %s' % cfg)
  184. if 'update-grub' in blcmd:
  185. self.blexec = [blcmd]
  186. else:
  187. self.blexec = [blcmd, '-o', cfg]
  188. def getBootLoader(self):
  189. if self.bootloader == 'grub':
  190. self.blGrub()
  191. else:
  192. doError('unknown boot loader: %s' % self.bootloader)
  193. def writeDatafileHeader(self, filename):
  194. self.kparams = open('/proc/cmdline', 'r').read().strip()
  195. fp = open(filename, 'w')
  196. fp.write(self.teststamp+'\n')
  197. fp.write(self.sysstamp+'\n')
  198. fp.write('# command | %s\n' % self.cmdline)
  199. fp.write('# kparams | %s\n' % self.kparams)
  200. fp.close()
  201. sysvals = SystemValues()
  202. # Class: Data
  203. # Description:
  204. # The primary container for test data.
  205. class Data(aslib.Data):
  206. dmesg = {} # root data structure
  207. start = 0.0 # test start
  208. end = 0.0 # test end
  209. dmesgtext = [] # dmesg text file in memory
  210. testnumber = 0
  211. idstr = ''
  212. html_device_id = 0
  213. valid = False
  214. tUserMode = 0.0
  215. boottime = ''
  216. phases = ['kernel', 'user']
  217. do_one_initcall = False
  218. def __init__(self, num):
  219. self.testnumber = num
  220. self.idstr = 'a'
  221. self.dmesgtext = []
  222. self.dmesg = {
  223. 'kernel': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0,
  224. 'order': 0, 'color': 'linear-gradient(to bottom, #fff, #bcf)'},
  225. 'user': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0,
  226. 'order': 1, 'color': '#fff'}
  227. }
  228. def deviceTopology(self):
  229. return ''
  230. def newAction(self, phase, name, pid, start, end, ret, ulen):
  231. # new device callback for a specific phase
  232. self.html_device_id += 1
  233. devid = '%s%d' % (self.idstr, self.html_device_id)
  234. list = self.dmesg[phase]['list']
  235. length = -1.0
  236. if(start >= 0 and end >= 0):
  237. length = end - start
  238. i = 2
  239. origname = name
  240. while(name in list):
  241. name = '%s[%d]' % (origname, i)
  242. i += 1
  243. list[name] = {'name': name, 'start': start, 'end': end,
  244. 'pid': pid, 'length': length, 'row': 0, 'id': devid,
  245. 'ret': ret, 'ulen': ulen }
  246. return name
  247. def deviceMatch(self, pid, cg):
  248. if cg.end - cg.start == 0:
  249. return ''
  250. for p in data.phases:
  251. list = self.dmesg[p]['list']
  252. for devname in list:
  253. dev = list[devname]
  254. if pid != dev['pid']:
  255. continue
  256. if cg.name == 'do_one_initcall':
  257. if(cg.start <= dev['start'] and cg.end >= dev['end'] and dev['length'] > 0):
  258. dev['ftrace'] = cg
  259. self.do_one_initcall = True
  260. return devname
  261. else:
  262. if(cg.start > dev['start'] and cg.end < dev['end']):
  263. if 'ftraces' not in dev:
  264. dev['ftraces'] = []
  265. dev['ftraces'].append(cg)
  266. return devname
  267. return ''
  268. def printDetails(self):
  269. sysvals.vprint('Timeline Details:')
  270. sysvals.vprint(' Host: %s' % sysvals.hostname)
  271. sysvals.vprint(' Kernel: %s' % sysvals.kernel)
  272. sysvals.vprint(' Test time: %s' % sysvals.testtime)
  273. sysvals.vprint(' Boot time: %s' % self.boottime)
  274. for phase in self.phases:
  275. dc = len(self.dmesg[phase]['list'])
  276. sysvals.vprint('%9s mode: %.3f - %.3f (%d initcalls)' % (phase,
  277. self.dmesg[phase]['start']*1000,
  278. self.dmesg[phase]['end']*1000, dc))
  279. # ----------------- FUNCTIONS --------------------
  280. # Function: parseKernelLog
  281. # Description:
  282. # parse a kernel log for boot data
  283. def parseKernelLog():
  284. sysvals.vprint('Analyzing the dmesg data (%s)...' % \
  285. os.path.basename(sysvals.dmesgfile))
  286. phase = 'kernel'
  287. data = Data(0)
  288. data.dmesg['kernel']['start'] = data.start = ktime = 0.0
  289. sysvals.stamp = {
  290. 'time': datetime.now().strftime('%B %d %Y, %I:%M:%S %p'),
  291. 'host': sysvals.hostname,
  292. 'mode': 'boot', 'kernel': ''}
  293. tp = aslib.TestProps()
  294. devtemp = dict()
  295. if(sysvals.dmesgfile):
  296. lf = open(sysvals.dmesgfile, 'rb')
  297. else:
  298. lf = Popen('dmesg', stdout=PIPE).stdout
  299. for line in lf:
  300. line = aslib.ascii(line).replace('\r\n', '')
  301. # grab the stamp and sysinfo
  302. if re.match(tp.stampfmt, line):
  303. tp.stamp = line
  304. continue
  305. elif re.match(tp.sysinfofmt, line):
  306. tp.sysinfo = line
  307. continue
  308. elif re.match(tp.cmdlinefmt, line):
  309. tp.cmdline = line
  310. continue
  311. elif re.match(tp.kparamsfmt, line):
  312. tp.kparams = line
  313. continue
  314. idx = line.find('[')
  315. if idx > 1:
  316. line = line[idx:]
  317. m = re.match(r'[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line)
  318. if(not m):
  319. continue
  320. ktime = float(m.group('ktime'))
  321. if(ktime > 120):
  322. break
  323. msg = m.group('msg')
  324. data.dmesgtext.append(line)
  325. if(ktime == 0.0 and re.match(r'^Linux version .*', msg)):
  326. if(not sysvals.stamp['kernel']):
  327. sysvals.stamp['kernel'] = sysvals.kernelVersion(msg)
  328. continue
  329. m = re.match(r'.* setting system clock to (?P<d>[0-9\-]*)[ A-Z](?P<t>[0-9:]*) UTC.*', msg)
  330. if(m):
  331. bt = datetime.strptime(m.group('d')+' '+m.group('t'), '%Y-%m-%d %H:%M:%S')
  332. bt = bt - timedelta(seconds=int(ktime))
  333. data.boottime = bt.strftime('%Y-%m-%d_%H:%M:%S')
  334. sysvals.stamp['time'] = bt.strftime('%B %d %Y, %I:%M:%S %p')
  335. continue
  336. m = re.match(r'^calling *(?P<f>.*)\+.* @ (?P<p>[0-9]*)', msg)
  337. if(m):
  338. func = m.group('f')
  339. pid = int(m.group('p'))
  340. devtemp[func] = (ktime, pid)
  341. continue
  342. m = re.match(r'^initcall *(?P<f>.*)\+.* returned (?P<r>.*) after (?P<t>.*) usecs', msg)
  343. if(m):
  344. data.valid = True
  345. data.end = ktime
  346. f, r, t = m.group('f', 'r', 't')
  347. if(f in devtemp):
  348. start, pid = devtemp[f]
  349. data.newAction(phase, f, pid, start, ktime, int(r), int(t))
  350. del devtemp[f]
  351. continue
  352. if(re.match(r'^Freeing unused kernel .*', msg)):
  353. data.tUserMode = ktime
  354. data.dmesg['kernel']['end'] = ktime
  355. data.dmesg['user']['start'] = ktime
  356. phase = 'user'
  357. if tp.stamp:
  358. sysvals.stamp = 0
  359. tp.parseStamp(data, sysvals)
  360. data.dmesg['user']['end'] = data.end
  361. lf.close()
  362. return data
  363. # Function: parseTraceLog
  364. # Description:
  365. # Check if trace is available and copy to a temp file
  366. def parseTraceLog(data):
  367. sysvals.vprint('Analyzing the ftrace data (%s)...' % \
  368. os.path.basename(sysvals.ftracefile))
  369. # if available, calculate cgfilter allowable ranges
  370. cgfilter = []
  371. if len(sysvals.cgfilter) > 0:
  372. for p in data.phases:
  373. list = data.dmesg[p]['list']
  374. for i in sysvals.cgfilter:
  375. if i in list:
  376. cgfilter.append([list[i]['start']-0.0001,
  377. list[i]['end']+0.0001])
  378. # parse the trace log
  379. ftemp = dict()
  380. tp = aslib.TestProps()
  381. tp.setTracerType('function_graph')
  382. tf = open(sysvals.ftracefile, 'r')
  383. for line in tf:
  384. if line[0] == '#':
  385. continue
  386. m = re.match(tp.ftrace_line_fmt, line.strip())
  387. if(not m):
  388. continue
  389. m_time, m_proc, m_pid, m_msg, m_dur = \
  390. m.group('time', 'proc', 'pid', 'msg', 'dur')
  391. t = float(m_time)
  392. if len(cgfilter) > 0:
  393. allow = False
  394. for r in cgfilter:
  395. if t >= r[0] and t < r[1]:
  396. allow = True
  397. break
  398. if not allow:
  399. continue
  400. if t > data.end:
  401. break
  402. if(m_time and m_pid and m_msg):
  403. t = aslib.FTraceLine(m_time, m_msg, m_dur)
  404. pid = int(m_pid)
  405. else:
  406. continue
  407. if t.fevent or t.fkprobe:
  408. continue
  409. key = (m_proc, pid)
  410. if(key not in ftemp):
  411. ftemp[key] = []
  412. ftemp[key].append(aslib.FTraceCallGraph(pid, sysvals))
  413. cg = ftemp[key][-1]
  414. res = cg.addLine(t)
  415. if(res != 0):
  416. ftemp[key].append(aslib.FTraceCallGraph(pid, sysvals))
  417. if(res == -1):
  418. ftemp[key][-1].addLine(t)
  419. tf.close()
  420. # add the callgraph data to the device hierarchy
  421. for key in ftemp:
  422. proc, pid = key
  423. for cg in ftemp[key]:
  424. if len(cg.list) < 1 or cg.invalid or (cg.end - cg.start == 0):
  425. continue
  426. if(not cg.postProcess()):
  427. pprint('Sanity check failed for %s-%d' % (proc, pid))
  428. continue
  429. # match cg data to devices
  430. devname = data.deviceMatch(pid, cg)
  431. if not devname:
  432. kind = 'Orphan'
  433. if cg.partial:
  434. kind = 'Partial'
  435. sysvals.vprint('%s callgraph found for %s %s-%d [%f - %f]' %\
  436. (kind, cg.name, proc, pid, cg.start, cg.end))
  437. elif len(cg.list) > 1000000:
  438. pprint('WARNING: the callgraph found for %s is massive! (%d lines)' %\
  439. (devname, len(cg.list)))
  440. # Function: retrieveLogs
  441. # Description:
  442. # Create copies of dmesg and/or ftrace for later processing
  443. def retrieveLogs():
  444. # check ftrace is configured first
  445. if sysvals.useftrace:
  446. tracer = sysvals.fgetVal('current_tracer').strip()
  447. if tracer != 'function_graph':
  448. doError('ftrace not configured for a boot callgraph')
  449. # create the folder and get dmesg
  450. sysvals.systemInfo(aslib.dmidecode(sysvals.mempath))
  451. sysvals.initTestOutput('boot')
  452. sysvals.writeDatafileHeader(sysvals.dmesgfile)
  453. call('dmesg >> '+sysvals.dmesgfile, shell=True)
  454. if not sysvals.useftrace:
  455. return
  456. # get ftrace
  457. sysvals.writeDatafileHeader(sysvals.ftracefile)
  458. call('cat '+sysvals.tpath+'trace >> '+sysvals.ftracefile, shell=True)
  459. # Function: colorForName
  460. # Description:
  461. # Generate a repeatable color from a list for a given name
  462. def colorForName(name):
  463. list = [
  464. ('c1', '#ec9999'),
  465. ('c2', '#ffc1a6'),
  466. ('c3', '#fff0a6'),
  467. ('c4', '#adf199'),
  468. ('c5', '#9fadea'),
  469. ('c6', '#a699c1'),
  470. ('c7', '#ad99b4'),
  471. ('c8', '#eaffea'),
  472. ('c9', '#dcecfb'),
  473. ('c10', '#ffffea')
  474. ]
  475. i = 0
  476. total = 0
  477. count = len(list)
  478. while i < len(name):
  479. total += ord(name[i])
  480. i += 1
  481. return list[total % count]
  482. def cgOverview(cg, minlen):
  483. stats = dict()
  484. large = []
  485. for l in cg.list:
  486. if l.fcall and l.depth == 1:
  487. if l.length >= minlen:
  488. large.append(l)
  489. if l.name not in stats:
  490. stats[l.name] = [0, 0.0]
  491. stats[l.name][0] += (l.length * 1000.0)
  492. stats[l.name][1] += 1
  493. return (large, stats)
  494. # Function: createBootGraph
  495. # Description:
  496. # Create the output html file from the resident test data
  497. # Arguments:
  498. # testruns: array of Data objects from parseKernelLog or parseTraceLog
  499. # Output:
  500. # True if the html file was created, false if it failed
  501. def createBootGraph(data):
  502. # html function templates
  503. html_srccall = '<div id={6} title="{5}" class="srccall" style="left:{1}%;top:{2}px;height:{3}px;width:{4}%;line-height:{3}px;">{0}</div>\n'
  504. html_timetotal = '<table class="time1">\n<tr>'\
  505. '<td class="blue">Init process starts @ <b>{0} ms</b></td>'\
  506. '<td class="blue">Last initcall ends @ <b>{1} ms</b></td>'\
  507. '</tr>\n</table>\n'
  508. # device timeline
  509. devtl = aslib.Timeline(100, 20)
  510. # write the test title and general info header
  511. devtl.createHeader(sysvals, sysvals.stamp)
  512. # Generate the header for this timeline
  513. t0 = data.start
  514. tMax = data.end
  515. tTotal = tMax - t0
  516. if(tTotal == 0):
  517. pprint('ERROR: No timeline data')
  518. return False
  519. user_mode = '%.0f'%(data.tUserMode*1000)
  520. last_init = '%.0f'%(tTotal*1000)
  521. devtl.html += html_timetotal.format(user_mode, last_init)
  522. # determine the maximum number of rows we need to draw
  523. devlist = []
  524. for p in data.phases:
  525. list = data.dmesg[p]['list']
  526. for devname in list:
  527. d = aslib.DevItem(0, p, list[devname])
  528. devlist.append(d)
  529. devtl.getPhaseRows(devlist, 0, 'start')
  530. devtl.calcTotalRows()
  531. # draw the timeline background
  532. devtl.createZoomBox()
  533. devtl.html += devtl.html_tblock.format('boot', '0', '100', devtl.scaleH)
  534. for p in data.phases:
  535. phase = data.dmesg[p]
  536. length = phase['end']-phase['start']
  537. left = '%.3f' % (((phase['start']-t0)*100.0)/tTotal)
  538. width = '%.3f' % ((length*100.0)/tTotal)
  539. devtl.html += devtl.html_phase.format(left, width, \
  540. '%.3f'%devtl.scaleH, '%.3f'%devtl.bodyH, \
  541. phase['color'], '')
  542. # draw the device timeline
  543. num = 0
  544. devstats = dict()
  545. for phase in data.phases:
  546. list = data.dmesg[phase]['list']
  547. for devname in sorted(list):
  548. cls, color = colorForName(devname)
  549. dev = list[devname]
  550. info = '@|%.3f|%.3f|%.3f|%d' % (dev['start']*1000.0, dev['end']*1000.0,
  551. dev['ulen']/1000.0, dev['ret'])
  552. devstats[dev['id']] = {'info':info}
  553. dev['color'] = color
  554. height = devtl.phaseRowHeight(0, phase, dev['row'])
  555. top = '%.6f' % ((dev['row']*height) + devtl.scaleH)
  556. left = '%.6f' % (((dev['start']-t0)*100)/tTotal)
  557. width = '%.6f' % (((dev['end']-dev['start'])*100)/tTotal)
  558. length = ' (%0.3f ms) ' % ((dev['end']-dev['start'])*1000)
  559. devtl.html += devtl.html_device.format(dev['id'],
  560. devname+length+phase+'_mode', left, top, '%.3f'%height,
  561. width, devname, ' '+cls, '')
  562. rowtop = devtl.phaseRowTop(0, phase, dev['row'])
  563. height = '%.6f' % (devtl.rowH / 2)
  564. top = '%.6f' % (rowtop + devtl.scaleH + (devtl.rowH / 2))
  565. if data.do_one_initcall:
  566. if('ftrace' not in dev):
  567. continue
  568. cg = dev['ftrace']
  569. large, stats = cgOverview(cg, 0.001)
  570. devstats[dev['id']]['fstat'] = stats
  571. for l in large:
  572. left = '%f' % (((l.time-t0)*100)/tTotal)
  573. width = '%f' % (l.length*100/tTotal)
  574. title = '%s (%0.3fms)' % (l.name, l.length * 1000.0)
  575. devtl.html += html_srccall.format(l.name, left,
  576. top, height, width, title, 'x%d'%num)
  577. num += 1
  578. continue
  579. if('ftraces' not in dev):
  580. continue
  581. for cg in dev['ftraces']:
  582. left = '%f' % (((cg.start-t0)*100)/tTotal)
  583. width = '%f' % ((cg.end-cg.start)*100/tTotal)
  584. cglen = (cg.end - cg.start) * 1000.0
  585. title = '%s (%0.3fms)' % (cg.name, cglen)
  586. cg.id = 'x%d' % num
  587. devtl.html += html_srccall.format(cg.name, left,
  588. top, height, width, title, dev['id']+cg.id)
  589. num += 1
  590. # draw the time scale, try to make the number of labels readable
  591. devtl.createTimeScale(t0, tMax, tTotal, 'boot')
  592. devtl.html += '</div>\n'
  593. # timeline is finished
  594. devtl.html += '</div>\n</div>\n'
  595. # draw a legend which describes the phases by color
  596. devtl.html += '<div class="legend">\n'
  597. pdelta = 20.0
  598. pmargin = 36.0
  599. for phase in data.phases:
  600. order = '%.2f' % ((data.dmesg[phase]['order'] * pdelta) + pmargin)
  601. devtl.html += devtl.html_legend.format(order, \
  602. data.dmesg[phase]['color'], phase+'_mode', phase[0])
  603. devtl.html += '</div>\n'
  604. hf = open(sysvals.htmlfile, 'w')
  605. # add the css
  606. extra = '\
  607. .c1 {background:rgba(209,0,0,0.4);}\n\
  608. .c2 {background:rgba(255,102,34,0.4);}\n\
  609. .c3 {background:rgba(255,218,33,0.4);}\n\
  610. .c4 {background:rgba(51,221,0,0.4);}\n\
  611. .c5 {background:rgba(17,51,204,0.4);}\n\
  612. .c6 {background:rgba(34,0,102,0.4);}\n\
  613. .c7 {background:rgba(51,0,68,0.4);}\n\
  614. .c8 {background:rgba(204,255,204,0.4);}\n\
  615. .c9 {background:rgba(169,208,245,0.4);}\n\
  616. .c10 {background:rgba(255,255,204,0.4);}\n\
  617. .vt {transform:rotate(-60deg);transform-origin:0 0;}\n\
  618. table.fstat {table-layout:fixed;padding:150px 15px 0 0;font-size:10px;column-width:30px;}\n\
  619. .fstat th {width:55px;}\n\
  620. .fstat td {text-align:left;width:35px;}\n\
  621. .srccall {position:absolute;font-size:10px;z-index:7;overflow:hidden;color:black;text-align:center;white-space:nowrap;border-radius:5px;border:1px solid black;background:linear-gradient(to bottom right,#CCC,#969696);}\n\
  622. .srccall:hover {color:white;font-weight:bold;border:1px solid white;}\n'
  623. aslib.addCSS(hf, sysvals, 1, False, extra)
  624. # write the device timeline
  625. hf.write(devtl.html)
  626. # add boot specific html
  627. statinfo = 'var devstats = {\n'
  628. for n in sorted(devstats):
  629. statinfo += '\t"%s": [\n\t\t"%s",\n' % (n, devstats[n]['info'])
  630. if 'fstat' in devstats[n]:
  631. funcs = devstats[n]['fstat']
  632. for f in sorted(funcs, key=lambda k:(funcs[k], k), reverse=True):
  633. if funcs[f][0] < 0.01 and len(funcs) > 10:
  634. break
  635. statinfo += '\t\t"%f|%s|%d",\n' % (funcs[f][0], f, funcs[f][1])
  636. statinfo += '\t],\n'
  637. statinfo += '};\n'
  638. html = \
  639. '<div id="devicedetailtitle"></div>\n'\
  640. '<div id="devicedetail" style="display:none;">\n'\
  641. '<div id="devicedetail0">\n'
  642. for p in data.phases:
  643. phase = data.dmesg[p]
  644. html += devtl.html_phaselet.format(p+'_mode', '0', '100', phase['color'])
  645. html += '</div>\n</div>\n'\
  646. '<script type="text/javascript">\n'+statinfo+\
  647. '</script>\n'
  648. hf.write(html)
  649. # add the callgraph html
  650. if(sysvals.usecallgraph):
  651. aslib.addCallgraphs(sysvals, hf, data)
  652. # add the test log as a hidden div
  653. if sysvals.testlog and sysvals.logmsg:
  654. hf.write('<div id="testlog" style="display:none;">\n'+sysvals.logmsg+'</div>\n')
  655. # add the dmesg log as a hidden div
  656. if sysvals.dmesglog:
  657. hf.write('<div id="dmesglog" style="display:none;">\n')
  658. for line in data.dmesgtext:
  659. line = line.replace('<', '&lt').replace('>', '&gt')
  660. hf.write(line)
  661. hf.write('</div>\n')
  662. # write the footer and close
  663. aslib.addScriptCode(hf, [data])
  664. hf.write('</body>\n</html>\n')
  665. hf.close()
  666. return True
  667. # Function: updateCron
  668. # Description:
  669. # (restore=False) Set the tool to run automatically on reboot
  670. # (restore=True) Restore the original crontab
  671. def updateCron(restore=False):
  672. if not restore:
  673. sysvals.rootUser(True)
  674. crondir = '/var/spool/cron/crontabs/'
  675. if not os.path.exists(crondir):
  676. crondir = '/var/spool/cron/'
  677. if not os.path.exists(crondir):
  678. doError('%s not found' % crondir)
  679. cronfile = crondir+'root'
  680. backfile = crondir+'root-analyze_boot-backup'
  681. cmd = sysvals.getExec('crontab')
  682. if not cmd:
  683. doError('crontab not found')
  684. # on restore: move the backup cron back into place
  685. if restore:
  686. if os.path.exists(backfile):
  687. shutil.move(backfile, cronfile)
  688. call([cmd, cronfile])
  689. return
  690. # backup current cron and install new one with reboot
  691. if os.path.exists(cronfile):
  692. shutil.move(cronfile, backfile)
  693. else:
  694. fp = open(backfile, 'w')
  695. fp.close()
  696. res = -1
  697. try:
  698. fp = open(backfile, 'r')
  699. op = open(cronfile, 'w')
  700. for line in fp:
  701. if not sysvals.myCronJob(line):
  702. op.write(line)
  703. continue
  704. fp.close()
  705. op.write('@reboot python %s\n' % sysvals.cronjobCmdString())
  706. op.close()
  707. res = call([cmd, cronfile])
  708. except Exception as e:
  709. pprint('Exception: %s' % str(e))
  710. shutil.move(backfile, cronfile)
  711. res = -1
  712. if res != 0:
  713. doError('crontab failed')
  714. # Function: updateGrub
  715. # Description:
  716. # update grub.cfg for all kernels with our parameters
  717. def updateGrub(restore=False):
  718. # call update-grub on restore
  719. if restore:
  720. try:
  721. call(sysvals.blexec, stderr=PIPE, stdout=PIPE,
  722. env={'PATH': '.:/sbin:/usr/sbin:/usr/bin:/sbin:/bin'})
  723. except Exception as e:
  724. pprint('Exception: %s\n' % str(e))
  725. return
  726. # extract the option and create a grub config without it
  727. sysvals.rootUser(True)
  728. tgtopt = 'GRUB_CMDLINE_LINUX_DEFAULT'
  729. cmdline = ''
  730. grubfile = '/etc/default/grub'
  731. tempfile = '/etc/default/grub.analyze_boot'
  732. shutil.move(grubfile, tempfile)
  733. res = -1
  734. try:
  735. fp = open(tempfile, 'r')
  736. op = open(grubfile, 'w')
  737. cont = False
  738. for line in fp:
  739. line = line.strip()
  740. if len(line) == 0 or line[0] == '#':
  741. continue
  742. opt = line.split('=')[0].strip()
  743. if opt == tgtopt:
  744. cmdline = line.split('=', 1)[1].strip('\\')
  745. if line[-1] == '\\':
  746. cont = True
  747. elif cont:
  748. cmdline += line.strip('\\')
  749. if line[-1] != '\\':
  750. cont = False
  751. else:
  752. op.write('%s\n' % line)
  753. fp.close()
  754. # if the target option value is in quotes, strip them
  755. sp = '"'
  756. val = cmdline.strip()
  757. if val and (val[0] == '\'' or val[0] == '"'):
  758. sp = val[0]
  759. val = val.strip(sp)
  760. cmdline = val
  761. # append our cmd line options
  762. if len(cmdline) > 0:
  763. cmdline += ' '
  764. cmdline += sysvals.kernelParams()
  765. # write out the updated target option
  766. op.write('\n%s=%s%s%s\n' % (tgtopt, sp, cmdline, sp))
  767. op.close()
  768. res = call(sysvals.blexec)
  769. os.remove(grubfile)
  770. except Exception as e:
  771. pprint('Exception: %s' % str(e))
  772. res = -1
  773. # cleanup
  774. shutil.move(tempfile, grubfile)
  775. if res != 0:
  776. doError('update grub failed')
  777. # Function: updateKernelParams
  778. # Description:
  779. # update boot conf for all kernels with our parameters
  780. def updateKernelParams(restore=False):
  781. # find the boot loader
  782. sysvals.getBootLoader()
  783. if sysvals.bootloader == 'grub':
  784. updateGrub(restore)
  785. # Function: doError Description:
  786. # generic error function for catastrphic failures
  787. # Arguments:
  788. # msg: the error message to print
  789. # help: True if printHelp should be called after, False otherwise
  790. def doError(msg, help=False):
  791. if help == True:
  792. printHelp()
  793. pprint('ERROR: %s\n' % msg)
  794. sysvals.outputResult({'error':msg})
  795. sys.exit()
  796. # Function: printHelp
  797. # Description:
  798. # print out the help text
  799. def printHelp():
  800. pprint('\n%s v%s\n'\
  801. 'Usage: bootgraph <options> <command>\n'\
  802. '\n'\
  803. 'Description:\n'\
  804. ' This tool reads in a dmesg log of linux kernel boot and\n'\
  805. ' creates an html representation of the boot timeline up to\n'\
  806. ' the start of the init process.\n'\
  807. '\n'\
  808. ' If no specific command is given the tool reads the current dmesg\n'\
  809. ' and/or ftrace log and creates a timeline\n'\
  810. '\n'\
  811. ' Generates output files in subdirectory: boot-yymmdd-HHMMSS\n'\
  812. ' HTML output: <hostname>_boot.html\n'\
  813. ' raw dmesg output: <hostname>_boot_dmesg.txt\n'\
  814. ' raw ftrace output: <hostname>_boot_ftrace.txt\n'\
  815. '\n'\
  816. 'Options:\n'\
  817. ' -h Print this help text\n'\
  818. ' -v Print the current tool version\n'\
  819. ' -verbose Print extra information during execution and analysis\n'\
  820. ' -addlogs Add the dmesg log to the html output\n'\
  821. ' -result fn Export a results table to a text file for parsing.\n'\
  822. ' -o name Overrides the output subdirectory name when running a new test\n'\
  823. ' default: boot-{date}-{time}\n'\
  824. ' [advanced]\n'\
  825. ' -fstat Use ftrace to add function detail and statistics (default: disabled)\n'\
  826. ' -f/-callgraph Add callgraph detail, can be very large (default: disabled)\n'\
  827. ' -maxdepth N limit the callgraph data to N call levels (default: 2)\n'\
  828. ' -mincg ms Discard all callgraphs shorter than ms milliseconds (e.g. 0.001 for us)\n'\
  829. ' -timeprec N Number of significant digits in timestamps (0:S, 3:ms, [6:us])\n'\
  830. ' -expandcg pre-expand the callgraph data in the html output (default: disabled)\n'\
  831. ' -func list Limit ftrace to comma-delimited list of functions (default: do_one_initcall)\n'\
  832. ' -cgfilter S Filter the callgraph output in the timeline\n'\
  833. ' -cgskip file Callgraph functions to skip, off to disable (default: cgskip.txt)\n'\
  834. ' -bl name Use the following boot loader for kernel params (default: grub)\n'\
  835. ' -reboot Reboot the machine automatically and generate a new timeline\n'\
  836. ' -manual Show the steps to generate a new timeline manually (used with -reboot)\n'\
  837. '\n'\
  838. 'Other commands:\n'\
  839. ' -flistall Print all functions capable of being captured in ftrace\n'\
  840. ' -sysinfo Print out system info extracted from BIOS\n'\
  841. ' -which exec Print an executable path, should function even without PATH\n'\
  842. ' [redo]\n'\
  843. ' -dmesg file Create HTML output using dmesg input (used with -ftrace)\n'\
  844. ' -ftrace file Create HTML output using ftrace input (used with -dmesg)\n'\
  845. '' % (sysvals.title, sysvals.version))
  846. return True
  847. # ----------------- MAIN --------------------
  848. # exec start (skipped if script is loaded as library)
  849. if __name__ == '__main__':
  850. # loop through the command line arguments
  851. cmd = ''
  852. testrun = True
  853. switchoff = ['disable', 'off', 'false', '0']
  854. simplecmds = ['-sysinfo', '-kpupdate', '-flistall', '-checkbl']
  855. cgskip = ''
  856. if '-f' in sys.argv:
  857. cgskip = sysvals.configFile('cgskip.txt')
  858. args = iter(sys.argv[1:])
  859. mdset = False
  860. for arg in args:
  861. if(arg == '-h'):
  862. printHelp()
  863. sys.exit()
  864. elif(arg == '-v'):
  865. pprint("Version %s" % sysvals.version)
  866. sys.exit()
  867. elif(arg == '-verbose'):
  868. sysvals.verbose = True
  869. elif(arg in simplecmds):
  870. cmd = arg[1:]
  871. elif(arg == '-fstat'):
  872. sysvals.useftrace = True
  873. elif(arg == '-callgraph' or arg == '-f'):
  874. sysvals.useftrace = True
  875. sysvals.usecallgraph = True
  876. elif(arg == '-cgdump'):
  877. sysvals.cgdump = True
  878. elif(arg == '-mincg'):
  879. sysvals.mincglen = aslib.getArgFloat('-mincg', args, 0.0, 10000.0)
  880. elif(arg == '-cgfilter'):
  881. try:
  882. val = next(args)
  883. except:
  884. doError('No callgraph functions supplied', True)
  885. sysvals.setCallgraphFilter(val)
  886. elif(arg == '-cgskip'):
  887. try:
  888. val = next(args)
  889. except:
  890. doError('No file supplied', True)
  891. if val.lower() in switchoff:
  892. cgskip = ''
  893. else:
  894. cgskip = sysvals.configFile(val)
  895. if(not cgskip):
  896. doError('%s does not exist' % cgskip)
  897. elif(arg == '-bl'):
  898. try:
  899. val = next(args)
  900. except:
  901. doError('No boot loader name supplied', True)
  902. if val.lower() not in ['grub']:
  903. doError('Unknown boot loader: %s' % val, True)
  904. sysvals.bootloader = val.lower()
  905. elif(arg == '-timeprec'):
  906. sysvals.setPrecision(aslib.getArgInt('-timeprec', args, 0, 6))
  907. elif(arg == '-maxdepth'):
  908. mdset = True
  909. sysvals.max_graph_depth = aslib.getArgInt('-maxdepth', args, 0, 1000)
  910. elif(arg == '-func'):
  911. try:
  912. val = next(args)
  913. except:
  914. doError('No filter functions supplied', True)
  915. sysvals.useftrace = True
  916. sysvals.usecallgraph = True
  917. sysvals.rootCheck(True)
  918. sysvals.setGraphFilter(val)
  919. elif(arg == '-ftrace'):
  920. try:
  921. val = next(args)
  922. except:
  923. doError('No ftrace file supplied', True)
  924. if(os.path.exists(val) == False):
  925. doError('%s does not exist' % val)
  926. testrun = False
  927. sysvals.ftracefile = val
  928. elif(arg == '-addlogs'):
  929. sysvals.dmesglog = True
  930. elif(arg == '-expandcg'):
  931. sysvals.cgexp = True
  932. elif(arg == '-dmesg'):
  933. try:
  934. val = next(args)
  935. except:
  936. doError('No dmesg file supplied', True)
  937. if(os.path.exists(val) == False):
  938. doError('%s does not exist' % val)
  939. testrun = False
  940. sysvals.dmesgfile = val
  941. elif(arg == '-o'):
  942. try:
  943. val = next(args)
  944. except:
  945. doError('No subdirectory name supplied', True)
  946. sysvals.testdir = sysvals.setOutputFolder(val)
  947. elif(arg == '-result'):
  948. try:
  949. val = next(args)
  950. except:
  951. doError('No result file supplied', True)
  952. sysvals.result = val
  953. elif(arg == '-reboot'):
  954. sysvals.reboot = True
  955. elif(arg == '-manual'):
  956. sysvals.reboot = True
  957. sysvals.manual = True
  958. # remaining options are only for cron job use
  959. elif(arg == '-cronjob'):
  960. sysvals.iscronjob = True
  961. elif(arg == '-which'):
  962. try:
  963. val = next(args)
  964. except:
  965. doError('No executable supplied', True)
  966. out = sysvals.getExec(val)
  967. if not out:
  968. print('%s not found' % val)
  969. sys.exit(1)
  970. print(out)
  971. sys.exit(0)
  972. else:
  973. doError('Invalid argument: '+arg, True)
  974. # compatibility errors and access checks
  975. if(sysvals.iscronjob and (sysvals.reboot or \
  976. sysvals.dmesgfile or sysvals.ftracefile or cmd)):
  977. doError('-cronjob is meant for batch purposes only')
  978. if(sysvals.reboot and (sysvals.dmesgfile or sysvals.ftracefile)):
  979. doError('-reboot and -dmesg/-ftrace are incompatible')
  980. if cmd or sysvals.reboot or sysvals.iscronjob or testrun:
  981. sysvals.rootCheck(True)
  982. if (testrun and sysvals.useftrace) or cmd == 'flistall':
  983. if not sysvals.verifyFtrace():
  984. doError('Ftrace is not properly enabled')
  985. # run utility commands
  986. sysvals.cpuInfo()
  987. if cmd != '':
  988. if cmd == 'kpupdate':
  989. updateKernelParams()
  990. elif cmd == 'flistall':
  991. for f in sysvals.getBootFtraceFilterFunctions():
  992. print(f)
  993. elif cmd == 'checkbl':
  994. sysvals.getBootLoader()
  995. pprint('Boot Loader: %s\n%s' % (sysvals.bootloader, sysvals.blexec))
  996. elif(cmd == 'sysinfo'):
  997. sysvals.printSystemInfo(True)
  998. sys.exit()
  999. # reboot: update grub, setup a cronjob, and reboot
  1000. if sysvals.reboot:
  1001. if (sysvals.useftrace or sysvals.usecallgraph) and \
  1002. not sysvals.checkFtraceKernelVersion():
  1003. doError('Ftrace functionality requires kernel v4.10 or newer')
  1004. if not sysvals.manual:
  1005. updateKernelParams()
  1006. updateCron()
  1007. call('reboot')
  1008. else:
  1009. sysvals.manualRebootRequired()
  1010. sys.exit()
  1011. if sysvals.usecallgraph and cgskip:
  1012. sysvals.vprint('Using cgskip file: %s' % cgskip)
  1013. sysvals.setCallgraphBlacklist(cgskip)
  1014. # cronjob: remove the cronjob, grub changes, and disable ftrace
  1015. if sysvals.iscronjob:
  1016. updateCron(True)
  1017. updateKernelParams(True)
  1018. try:
  1019. sysvals.fsetVal('0', 'tracing_on')
  1020. except:
  1021. pass
  1022. # testrun: generate copies of the logs
  1023. if testrun:
  1024. retrieveLogs()
  1025. else:
  1026. sysvals.setOutputFile()
  1027. # process the log data
  1028. if sysvals.dmesgfile:
  1029. if not mdset:
  1030. sysvals.max_graph_depth = 0
  1031. data = parseKernelLog()
  1032. if(not data.valid):
  1033. doError('No initcall data found in %s' % sysvals.dmesgfile)
  1034. if sysvals.useftrace and sysvals.ftracefile:
  1035. parseTraceLog(data)
  1036. if sysvals.cgdump:
  1037. data.debugPrint()
  1038. sys.exit()
  1039. else:
  1040. doError('dmesg file required')
  1041. sysvals.vprint('Creating the html timeline (%s)...' % sysvals.htmlfile)
  1042. sysvals.vprint('Command:\n %s' % sysvals.cmdline)
  1043. sysvals.vprint('Kernel parameters:\n %s' % sysvals.kparams)
  1044. data.printDetails()
  1045. createBootGraph(data)
  1046. # if running as root, change output dir owner to sudo_user
  1047. if testrun and os.path.isdir(sysvals.testdir) and \
  1048. os.getuid() == 0 and 'SUDO_USER' in os.environ:
  1049. cmd = 'chown -R {0}:{0} {1} > /dev/null 2>&1'
  1050. call(cmd.format(os.environ['SUDO_USER'], sysvals.testdir), shell=True)
  1051. sysvals.stamp['boot'] = (data.tUserMode - data.start) * 1000
  1052. sysvals.stamp['lastinit'] = data.end * 1000
  1053. sysvals.outputResult(sysvals.stamp)