blob: b153e8406d5d45c9ed5a8362f2de1ed3e2e92a62 [file] [log] [blame]
lmr95ef4f62009-09-29 17:30:43 +00001#!/usr/bin/python
2"""
3Simple crash handling application for autotest
4
5@copyright Red Hat Inc 2009
6@author Lucas Meneghel Rodrigues <lmr@redhat.com>
7"""
8import sys, os, commands, glob, tempfile, shutil, syslog
9
10
11def get_parent_pid(pid):
12 """
13 Returns the parent PID for a given PID, converted to an integer.
14
15 @param pid: Process ID.
16 """
17 try:
18 ppid = int(open('/proc/%s/stat' % pid).read().split()[3])
19 except:
20 # It is not possible to determine the parent because the process
21 # already left the process table.
22 ppid = 1
23
24 return ppid
25
26
27def write_to_file(file_path, contents):
28 """
29 Write contents to a given file path specified. If not specified, the file
30 will be created.
31
32 @param file_path: Path to a given file.
33 @param contents: File contents.
34 """
35 file_object = open(file_path, 'w')
36 file_object.write(contents)
37 file_object.close()
38
39
40def get_results_dir_list(pid, core_dir_basename):
41 """
42 Get all valid output directories for the core file and the report. It works
43 by inspecting files created by each test on /tmp and verifying if the
44 PID of the process that crashed is a child or grandchild of the autotest
45 test process. If it can't find any relationship (maybe a daemon that died
46 during a test execution), it will write the core file to the debug dirs
47 of all tests currently being executed. If there are no active autotest
48 tests at a particular moment, it will return a list with ['/tmp'].
49
50 @param pid: PID for the process that generated the core
51 @param core_dir_basename: Basename for the directory that will hold both
52 the core dump and the crash report.
53 """
54 pid_dir_dict = {}
55 for debugdir_file in glob.glob("/tmp/autotest_results_dir.*"):
56 a_pid = os.path.splitext(debugdir_file)[1]
57 results_dir = open(debugdir_file).read().strip()
58 pid_dir_dict[a_pid] = os.path.join(results_dir, core_dir_basename)
59
60 results_dir_list = []
61 while pid > 1:
62 if pid in pid_dir_dict:
63 results_dir_list.append(pid_dir_dict[pid])
64 pid = get_parent_pid(pid)
65
66 return (results_dir_list or
67 pid_dir_dict.values() or
68 [os.path.join("/tmp", core_dir_basename)])
69
70
71def get_info_from_core(path):
72 """
73 Reads a core file and extracts a dictionary with useful core information.
74 Right now, the only information extracted is the full executable name.
75
76 @param path: Path to core file.
77 """
78 # Here we are getting the executable full path in a very inelegant way :(
79 # Since the 'right' solution for it is to make a library to get information
80 # from core dump files, properly written, I'll leave this as it is for now.
81 full_exe_path = commands.getoutput('strings %s | grep "_="' %
82 path).strip("_=")
83 if full_exe_path.startswith("./"):
84 pwd = commands.getoutput('strings %s | grep "^PWD="' %
85 path).strip("PWD=")
86 full_exe_path = os.path.join(pwd, full_exe_path.strip("./"))
87
88 return {'core_file': path, 'full_exe_path': full_exe_path}
89
90
91if __name__ == "__main__":
92 syslog.openlog('AutotestCrashHandler', 0, syslog.LOG_DAEMON)
93 (crashed_pid, time, uid, signal, hostname, exe) = sys.argv[1:]
94 core_name = 'core'
95 report_name = 'report'
96 core_dir_name = 'crash.%s.%s' % (exe, crashed_pid)
97 core_tmp_dir = tempfile.mkdtemp(prefix='core_', dir='/tmp')
98 core_tmp_path = os.path.join(core_tmp_dir, core_name)
99 gdb_command_path = os.path.join(core_tmp_dir, 'gdb_command')
100
101 try:
102 # Get the filtered results dir list
103 current_results_dir_list = get_results_dir_list(crashed_pid,
104 core_dir_name)
105
106 # Write the core file to the appropriate directory
107 # (we are piping it to this script)
108 core_file = sys.stdin.read()
109 write_to_file(core_tmp_path, core_file)
110
111 # Write a command file for GDB
112 gdb_command = 'bt full\n'
113 write_to_file(gdb_command_path, gdb_command)
114
115 # Get full command path
116 exe_path = get_info_from_core(core_tmp_path)['full_exe_path']
117
118 # Take a backtrace from the running program
119 gdb_cmd = 'gdb -e %s -c %s -x %s -n -batch -quiet' % (exe_path,
120 core_tmp_path,
121 gdb_command_path)
122 backtrace = commands.getoutput(gdb_cmd)
123 # Sanitize output before passing it to the report
124 backtrace = backtrace.decode('utf-8', 'ignore')
125
126 # Composing the format_dict
127 format_dict = {}
128 format_dict['program'] = exe_path
129 format_dict['pid'] = crashed_pid
130 format_dict['signal'] = signal
131 format_dict['hostname'] = hostname
132 format_dict['time'] = time
133 format_dict['backtrace'] = backtrace
134
135 report = """Autotest crash report
136
137Program: %(program)s
138PID: %(pid)s
139Signal: %(signal)s
140Hostname: %(hostname)s
141Time of the crash: %(time)s
142Program backtrace:
143%(backtrace)s
144""" % format_dict
145
146 syslog.syslog(syslog.LOG_INFO,
147 "Application %s, PID %s crashed" %
148 (exe_path, crashed_pid))
149
150 # Now, for all results dir, let's create the directory if it doesn't
151 # exist, and write the core file and the report to it.
152 syslog.syslog(syslog.LOG_INFO,
153 "Writing core files and reports to %s" %
154 current_results_dir_list)
155 for result_dir in current_results_dir_list:
156 if not os.path.isdir(result_dir):
157 os.makedirs(result_dir)
158 core_path = os.path.join(result_dir, 'core')
159 write_to_file(core_path, core_file)
160 report_path = os.path.join(result_dir, 'report')
161 write_to_file(report_path, report)
162
163 finally:
164 # Cleanup temporary directories
165 shutil.rmtree(core_tmp_dir)
166