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