You can not select more than 25 topics
			Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
		
		
		
		
			
				
					177 lines
				
				4.8 KiB
			
		
		
			
		
	
	
					177 lines
				
				4.8 KiB
			| 
											6 years ago
										 | #!/usr/bin/env python3
 | ||
| 
											5 years ago
										 | import datetime
 | ||
| 
											6 years ago
										 | import os
 | ||
| 
											5 years ago
										 | import re
 | ||
|  | import shutil
 | ||
|  | import signal
 | ||
|  | import subprocess
 | ||
| 
											6 years ago
										 | import time
 | ||
| 
											5 years ago
										 | import glob
 | ||
| 
											4 years ago
										 | from typing import NoReturn
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											1 year ago
										 | import openpilot.system.sentry as sentry
 | ||
| 
											2 years ago
										 | from openpilot.system.hardware.hw import Paths
 | ||
| 
											2 years ago
										 | from openpilot.common.swaglog import cloudlog
 | ||
| 
											2 years ago
										 | from openpilot.system.version import get_build_metadata
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											3 years ago
										 | MAX_SIZE = 1_000_000 * 100  # allow up to 100M
 | ||
| 
											5 years ago
										 | MAX_TOMBSTONE_FN_LEN = 62  # 85 - 23 ("<dongle id>/crash/")
 | ||
| 
											5 years ago
										 | 
 | ||
|  | TOMBSTONE_DIR = "/data/tombstones/"
 | ||
|  | APPORT_DIR = "/var/crash/"
 | ||
|  | 
 | ||
|  | 
 | ||
|  | def safe_fn(s):
 | ||
|  |   extra = ['_']
 | ||
|  |   return "".join(c for c in s if c.isalnum() or c in extra).rstrip()
 | ||
|  | 
 | ||
|  | 
 | ||
|  | def clear_apport_folder():
 | ||
|  |   for f in glob.glob(APPORT_DIR + '*'):
 | ||
|  |     try:
 | ||
|  |       os.remove(f)
 | ||
|  |     except Exception:
 | ||
|  |       pass
 | ||
|  | 
 | ||
|  | 
 | ||
|  | def get_apport_stacktrace(fn):
 | ||
|  |   try:
 | ||
|  |     cmd = f'apport-retrace -s <(cat <(echo "Package: openpilot") "{fn}")'
 | ||
| 
											2 years ago
										 |     return subprocess.check_output(cmd, shell=True, encoding='utf8', timeout=30, executable='/bin/bash')
 | ||
| 
											5 years ago
										 |   except subprocess.CalledProcessError:
 | ||
|  |     return "Error getting stacktrace"
 | ||
|  |   except subprocess.TimeoutExpired:
 | ||
|  |     return "Timeout getting stacktrace"
 | ||
|  | 
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											6 years ago
										 | def get_tombstones():
 | ||
| 
											2 years ago
										 |   """Returns list of (filename, ctime) for all crashlogs"""
 | ||
| 
											5 years ago
										 |   files = []
 | ||
| 
											2 years ago
										 |   if os.path.exists(APPORT_DIR):
 | ||
|  |     with os.scandir(APPORT_DIR) as d:
 | ||
|  |       # Loop over first 1000 directory entries
 | ||
|  |       for _, f in zip(range(1000), d, strict=False):
 | ||
|  |         if f.name.startswith("tombstone"):
 | ||
|  |           files.append((f.path, int(f.stat().st_ctime)))
 | ||
|  |         elif f.name.endswith(".crash") and f.stat().st_mode == 0o100640:
 | ||
|  |           files.append((f.path, int(f.stat().st_ctime)))
 | ||
| 
											5 years ago
										 |   return files
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											5 years ago
										 | def report_tombstone_apport(fn):
 | ||
| 
											5 years ago
										 |   f_size = os.path.getsize(fn)
 | ||
|  |   if f_size > MAX_SIZE:
 | ||
|  |     cloudlog.error(f"Tombstone {fn} too big, {f_size}. Skipping...")
 | ||
|  |     return
 | ||
|  | 
 | ||
|  |   message = ""  # One line description of the crash
 | ||
|  |   contents = ""  # Full file contents without coredump
 | ||
|  |   path = ""  # File path relative to openpilot directory
 | ||
|  | 
 | ||
|  |   proc_maps = False
 | ||
|  | 
 | ||
|  |   with open(fn) as f:
 | ||
|  |     for line in f:
 | ||
|  |       if "CoreDump" in line:
 | ||
|  |         break
 | ||
|  |       elif "ProcMaps" in line:
 | ||
|  |         proc_maps = True
 | ||
|  |       elif "ProcStatus" in line:
 | ||
|  |         proc_maps = False
 | ||
|  | 
 | ||
|  |       if not proc_maps:
 | ||
|  |         contents += line
 | ||
|  | 
 | ||
|  |       if "ExecutablePath" in line:
 | ||
|  |         path = line.strip().split(': ')[-1]
 | ||
|  |         path = path.replace('/data/openpilot/', '')
 | ||
|  |         message += path
 | ||
|  |       elif "Signal" in line:
 | ||
|  |         message += " - " + line.strip()
 | ||
|  | 
 | ||
|  |         try:
 | ||
|  |           sig_num = int(line.strip().split(': ')[-1])
 | ||
| 
											2 years ago
										 |           message += " (" + signal.Signals(sig_num).name + ")"
 | ||
| 
											5 years ago
										 |         except ValueError:
 | ||
|  |           pass
 | ||
|  | 
 | ||
|  |   stacktrace = get_apport_stacktrace(fn)
 | ||
|  |   stacktrace_s = stacktrace.split('\n')
 | ||
|  |   crash_function = "No stacktrace"
 | ||
|  | 
 | ||
|  |   if len(stacktrace_s) > 2:
 | ||
|  |     found = False
 | ||
|  | 
 | ||
|  |     # Try to find first entry in openpilot, fall back to first line
 | ||
|  |     for line in stacktrace_s:
 | ||
|  |       if "at selfdrive/" in line:
 | ||
| 
											4 years ago
										 |         crash_function = line
 | ||
|  |         found = True
 | ||
|  |         break
 | ||
| 
											5 years ago
										 | 
 | ||
|  |     if not found:
 | ||
|  |       crash_function = stacktrace_s[1]
 | ||
|  | 
 | ||
|  |     # Remove arguments that can contain pointers to make sentry one-liner unique
 | ||
| 
											5 years ago
										 |     crash_function = " ".join(x for x in crash_function.split(' ')[1:] if not x.startswith('0x'))
 | ||
| 
											5 years ago
										 |     crash_function = re.sub(r'\(.*?\)', '', crash_function)
 | ||
|  | 
 | ||
|  |   contents = stacktrace + "\n\n" + contents
 | ||
|  |   message = message + " - " + crash_function
 | ||
| 
											4 years ago
										 |   sentry.report_tombstone(fn, message, contents)
 | ||
| 
											5 years ago
										 | 
 | ||
|  |   # Copy crashlog to upload folder
 | ||
|  |   clean_path = path.replace('/', '_')
 | ||
|  |   date = datetime.datetime.now().strftime("%Y-%m-%d--%H-%M-%S")
 | ||
|  | 
 | ||
| 
											2 years ago
										 |   build_metadata = get_build_metadata()
 | ||
|  | 
 | ||
|  |   new_fn = f"{date}_{(build_metadata.openpilot.git_commit or 'nocommit')[:8]}_{safe_fn(clean_path)}"[:MAX_TOMBSTONE_FN_LEN]
 | ||
| 
											5 years ago
										 | 
 | ||
| 
											2 years ago
										 |   crashlog_dir = os.path.join(Paths.log_root(), "crash")
 | ||
| 
											2 years ago
										 |   os.makedirs(crashlog_dir, exist_ok=True)
 | ||
| 
											5 years ago
										 | 
 | ||
|  |   # Files could be on different filesystems, copy, then delete
 | ||
|  |   shutil.copy(fn, os.path.join(crashlog_dir, new_fn))
 | ||
| 
											5 years ago
										 | 
 | ||
|  |   try:
 | ||
|  |     os.remove(fn)
 | ||
|  |   except PermissionError:
 | ||
|  |     pass
 | ||
| 
											6 years ago
										 | 
 | ||
|  | 
 | ||
| 
											4 years ago
										 | def main() -> NoReturn:
 | ||
| 
											2 years ago
										 |   should_report = sentry.init(sentry.SentryProject.SELFDRIVE_NATIVE)
 | ||
| 
											5 years ago
										 | 
 | ||
| 
											4 years ago
										 |   # Clear apport folder on start, otherwise duplicate crashes won't register
 | ||
|  |   clear_apport_folder()
 | ||
|  |   initial_tombstones = set(get_tombstones())
 | ||
| 
											6 years ago
										 | 
 | ||
|  |   while True:
 | ||
|  |     now_tombstones = set(get_tombstones())
 | ||
|  | 
 | ||
| 
											5 years ago
										 |     for fn, _ in (now_tombstones - initial_tombstones):
 | ||
| 
											2 years ago
										 |       # clear logs if we're not interested in them
 | ||
|  |       if not should_report:
 | ||
|  |         try:
 | ||
|  |           os.remove(fn)
 | ||
|  |         except Exception:
 | ||
|  |           pass
 | ||
|  |         continue
 | ||
|  | 
 | ||
| 
											6 years ago
										 |       try:
 | ||
|  |         cloudlog.info(f"reporting new tombstone {fn}")
 | ||
| 
											5 years ago
										 |         if fn.endswith(".crash"):
 | ||
| 
											5 years ago
										 |           report_tombstone_apport(fn)
 | ||
| 
											5 years ago
										 |         else:
 | ||
| 
											3 years ago
										 |           cloudlog.error(f"unknown crash type: {fn}")
 | ||
| 
											6 years ago
										 |       except Exception:
 | ||
|  |         cloudlog.exception(f"Error reporting tombstone {fn}")
 | ||
| 
											6 years ago
										 | 
 | ||
|  |     initial_tombstones = now_tombstones
 | ||
|  |     time.sleep(5)
 | ||
|  | 
 | ||
| 
											6 years ago
										 | 
 | ||
| 
											6 years ago
										 | if __name__ == "__main__":
 | ||
|  |   main()
 |