xref: /openbmc/openbmc/poky/meta/lib/oeqa/utils/dump.py (revision ac13d5f3)
1#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: MIT
5#
6
7import os
8import sys
9import json
10import errno
11import datetime
12import itertools
13from .commands import runCmd
14
15class BaseDumper(object):
16    """ Base class to dump commands from host/target """
17
18    def __init__(self, cmds, parent_dir):
19        self.cmds = []
20        # Some testing doesn't inherit testimage, so it is needed
21        # to set some defaults.
22        self.parent_dir = parent_dir
23        self.dump_dir = parent_dir
24        dft_cmds = """  top -bn1
25                        iostat -x -z -N -d -p ALL 20 2
26                        ps -ef
27                        free
28                        df
29                        memstat
30                        dmesg
31                        ip -s link
32                        netstat -an"""
33        if not cmds:
34            cmds = dft_cmds
35        for cmd in cmds.split('\n'):
36            cmd = cmd.lstrip()
37            if not cmd or cmd[0] == '#':
38                continue
39            self.cmds.append(cmd)
40
41    def create_dir(self, dir_suffix):
42        dump_subdir = ("%s_%s" % (
43                datetime.datetime.now().strftime('%Y%m%d%H%M'),
44                dir_suffix))
45        dump_dir = os.path.join(self.parent_dir, dump_subdir)
46        try:
47            os.makedirs(dump_dir)
48        except OSError as err:
49            if err.errno != errno.EEXIST:
50                raise err
51        self.dump_dir = dump_dir
52
53    def _construct_filename(self, command):
54        if isinstance(self, TargetDumper):
55            prefix = "target"
56        elif isinstance(self, MonitorDumper):
57            prefix = "qmp"
58        else:
59            prefix = "unknown"
60        for i in itertools.count():
61            filename = "%s_%02d_%s" % (prefix, i, command)
62            fullname = os.path.join(self.dump_dir, filename)
63            if not os.path.exists(fullname):
64                break
65        return fullname
66
67    def _write_dump(self, command, output):
68        fullname = self._construct_filename(command)
69        os.makedirs(os.path.dirname(fullname), exist_ok=True)
70        if isinstance(self, MonitorDumper):
71            with open(fullname, 'w') as json_file:
72                json.dump(output, json_file, indent=4)
73        else:
74            with open(fullname, 'w') as dump_file:
75                dump_file.write(output)
76
77class TargetDumper(BaseDumper):
78    """ Class to get dumps from target, it only works with QemuRunner.
79        Will give up permanently after 5 errors from running commands over
80        serial console. This helps to end testing when target is really dead, hanging
81        or unresponsive.
82    """
83
84    def __init__(self, cmds, parent_dir, runner):
85        super(TargetDumper, self).__init__(cmds, parent_dir)
86        self.runner = runner
87        self.errors = 0
88
89    def dump_target(self, dump_dir=""):
90        if self.errors >= 5:
91                print("Too many errors when dumping data from target, assuming it is dead! Will not dump data anymore!")
92                return
93        if dump_dir:
94            self.dump_dir = dump_dir
95        for cmd in self.cmds:
96            # We can continue with the testing if serial commands fail
97            try:
98                (status, output) = self.runner.run_serial(cmd)
99                if status == 0:
100                    self.errors = self.errors + 1
101                self._write_dump(cmd.split()[0], output)
102            except:
103                self.errors = self.errors + 1
104                print("Tried to dump info from target but "
105                        "serial console failed")
106                print("Failed CMD: %s" % (cmd))
107
108class MonitorDumper(BaseDumper):
109    """ Class to get dumps via the Qemu Monitor, it only works with QemuRunner
110        Will stop completely if there are more than 5 errors when dumping monitor data.
111        This helps to end testing when target is really dead, hanging or unresponsive.
112    """
113
114    def __init__(self, cmds, parent_dir, runner):
115        super(MonitorDumper, self).__init__(cmds, parent_dir)
116        self.runner = runner
117        self.errors = 0
118
119    def dump_monitor(self, dump_dir=""):
120        if self.runner is None:
121            return
122        if dump_dir:
123            self.dump_dir = dump_dir
124        if self.errors >= 5:
125                print("Too many errors when dumping data from qemu monitor, assuming it is dead! Will not dump data anymore!")
126                return
127        for cmd in self.cmds:
128            cmd_name = cmd.split()[0]
129            try:
130                if len(cmd.split()) > 1:
131                    cmd_args = cmd.split()[1]
132                    if "%s" in cmd_args:
133                        filename = self._construct_filename(cmd_name)
134                    cmd_data = json.loads(cmd_args % (filename))
135                    output = self.runner.run_monitor(cmd_name, cmd_data)
136                else:
137                    output = self.runner.run_monitor(cmd_name)
138                self._write_dump(cmd_name, output)
139            except Exception as e:
140                self.errors = self.errors + 1
141                print("Failed to dump QMP CMD: %s with\nException: %s" % (cmd_name, e))
142