Best Python code snippet using autotest_python
crash_handler.py
Source:crash_handler.py  
...45        f.close()46    if report:47        gdb_report(filename)48    return filename49def get_results_dir_list(pid, core_dir_basename):50    """51    Get all valid output directories for the core file and the report. It works52    by inspecting files created by each test on /tmp and verifying if the53    PID of the process that crashed is a child or grandchild of the autotest54    test process. If it can't find any relationship (maybe a daemon that died55    during a test execution), it will write the core file to the debug dirs56    of all tests currently being executed. If there are no active autotest57    tests at a particular moment, it will return a list with ['/tmp'].58    @param pid: PID for the process that generated the core59    @param core_dir_basename: Basename for the directory that will hold both60            the core dump and the crash report.61    """62    pid_dir_dict = {}63    for debugdir_file in glob.glob("/tmp/autotest_results_dir.*"):64        a_pid = os.path.splitext(debugdir_file)[1]65        results_dir = open(debugdir_file).read().strip()66        pid_dir_dict[a_pid] = os.path.join(results_dir, core_dir_basename)67    results_dir_list = []68    # If a bug occurs and we can't grab the PID for the process that died, just69    # return all directories available and write to all of them.70    if pid is not None:71        while pid > 1:72            if pid in pid_dir_dict:73                results_dir_list.append(pid_dir_dict[pid])74            pid = get_parent_pid(pid)75    else:76        results_dir_list = pid_dir_dict.values()77    return (results_dir_list or78            pid_dir_dict.values() or79            [os.path.join("/tmp", core_dir_basename)])80def get_info_from_core(path):81    """82    Reads a core file and extracts a dictionary with useful core information.83    Right now, the only information extracted is the full executable name.84    @param path: Path to core file.85    """86    full_exe_path = None87    output = commands.getoutput('gdb -c %s batch' % path)88    path_pattern = re.compile("Core was generated by `([^\0]+)'", re.IGNORECASE)89    match = re.findall(path_pattern, output)90    for m in match:91        # Sometimes the command line args come with the core, so get rid of them92        m = m.split(" ")[0]93        if os.path.isfile(m):94            full_exe_path = m95            break96    if full_exe_path is None:97        syslog.syslog("Could not determine from which application core file %s "98                      "is from" % path)99    return {'full_exe_path': full_exe_path}100def gdb_report(path):101    """102    Use GDB to produce a report with information about a given core.103    @param path: Path to core file.104    """105    # Get full command path106    exe_path = get_info_from_core(path)['full_exe_path']107    basedir = os.path.dirname(path)108    gdb_command_path = os.path.join(basedir, 'gdb_cmd')109    if exe_path is not None:110        # Write a command file for GDB111        gdb_command = 'bt full\n'112        write_to_file(gdb_command_path, gdb_command)113        # Take a backtrace from the running program114        gdb_cmd = ('gdb -e %s -c %s -x %s -n -batch -quiet' %115                   (exe_path, path, gdb_command_path))116        backtrace = commands.getoutput(gdb_cmd)117        # Sanitize output before passing it to the report118        backtrace = backtrace.decode('utf-8', 'ignore')119    else:120        exe_path = "Unknown"121        backtrace = ("Could not determine backtrace for core file %s" % path)122    # Composing the format_dict123    report = "Program: %s\n" % exe_path124    if crashed_pid is not None:125        report += "PID: %s\n" % crashed_pid126    if signal is not None:127        report += "Signal: %s\n" % signal128    if hostname is not None:129        report += "Hostname: %s\n" % hostname130    if crash_time is not None:131        report += ("Time of the crash (according to kernel): %s\n" %132                   time.ctime(float(crash_time)))133    report += "Program backtrace:\n%s\n" % backtrace134    report_path = os.path.join(basedir, 'report')135    write_to_file(report_path, report)136def write_cores(core_data, dir_list):137    """138    Write core files to all directories, optionally providing reports.139    @param core_data: Contents of the core file.140    @param dir_list: List of directories the cores have to be written.141    @param report: Whether reports are to be generated for those core files.142    """143    syslog.syslog("Writing core files to %s" % dir_list)144    for result_dir in dir_list:145        if not os.path.isdir(result_dir):146            os.makedirs(result_dir)147        core_path = os.path.join(result_dir, 'core')148        core_path = write_to_file(core_path, core_file, report=True)149if __name__ == "__main__":150    syslog.openlog('AutotestCrashHandler', 0, syslog.LOG_DAEMON)151    global crashed_pid, crash_time, uid, signal, hostname, exe152    try:153        full_functionality = False154        try:155            crashed_pid, crash_time, uid, signal, hostname, exe = sys.argv[1:]156            full_functionality = True157        except ValueError, e:158            # Probably due a kernel bug, we can't exactly map the parameters159            # passed to this script. So we have to reduce the functionality160            # of the script (just write the core at a fixed place).161            syslog.syslog("Unable to unpack parameters passed to the "162                          "script. Operating with limited functionality.")163            crashed_pid, crash_time, uid, signal, hostname, exe = (None, None,164                                                                   None, None,165                                                                   None, None)166        if full_functionality:167            core_dir_name = 'crash.%s.%s' % (exe, crashed_pid)168        else:169            core_dir_name = 'core.%s' % generate_random_string(4)170        # Get the filtered results dir list171        results_dir_list = get_results_dir_list(crashed_pid, core_dir_name)172        # Write the core file to the appropriate directory173        # (we are piping it to this script)174        core_file = sys.stdin.read()175        if (exe is not None) and (crashed_pid is not None):176            syslog.syslog("Application %s, PID %s crashed" % (exe, crashed_pid))177        write_cores(core_file, results_dir_list)178    except Exception, e:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
