xref: /openbmc/qemu/tests/qemu-iotests/testenv.py (revision 2f44bea9)
1# TestEnv class to manage test environment variables.
2#
3# Copyright (c) 2020-2021 Virtuozzo International GmbH
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17#
18
19import os
20import sys
21import tempfile
22from pathlib import Path
23import shutil
24import collections
25import random
26import subprocess
27import glob
28from typing import List, Dict, Any, Optional, ContextManager
29
30DEF_GDB_OPTIONS = 'localhost:12345'
31
32def isxfile(path: str) -> bool:
33    return os.path.isfile(path) and os.access(path, os.X_OK)
34
35
36def get_default_machine(qemu_prog: str) -> str:
37    outp = subprocess.run([qemu_prog, '-machine', 'help'], check=True,
38                          universal_newlines=True,
39                          stdout=subprocess.PIPE).stdout
40
41    machines = outp.split('\n')
42    try:
43        default_machine = next(m for m in machines if m.endswith(' (default)'))
44    except StopIteration:
45        return ''
46    default_machine = default_machine.split(' ', 1)[0]
47
48    alias_suf = ' (alias of {})'.format(default_machine)
49    alias = next((m for m in machines if m.endswith(alias_suf)), None)
50    if alias is not None:
51        default_machine = alias.split(' ', 1)[0]
52
53    return default_machine
54
55
56class TestEnv(ContextManager['TestEnv']):
57    """
58    Manage system environment for running tests
59
60    The following variables are supported/provided. They are represented by
61    lower-cased TestEnv attributes.
62    """
63
64    # We store environment variables as instance attributes, and there are a
65    # lot of them. Silence pylint:
66    # pylint: disable=too-many-instance-attributes
67
68    env_variables = ['PYTHONPATH', 'TEST_DIR', 'SOCK_DIR', 'SAMPLE_IMG_DIR',
69                     'OUTPUT_DIR', 'PYTHON', 'QEMU_PROG', 'QEMU_IMG_PROG',
70                     'QEMU_IO_PROG', 'QEMU_NBD_PROG', 'QSD_PROG',
71                     'SOCKET_SCM_HELPER', 'QEMU_OPTIONS', 'QEMU_IMG_OPTIONS',
72                     'QEMU_IO_OPTIONS', 'QEMU_IO_OPTIONS_NO_FMT',
73                     'QEMU_NBD_OPTIONS', 'IMGOPTS', 'IMGFMT', 'IMGPROTO',
74                     'AIOMODE', 'CACHEMODE', 'VALGRIND_QEMU',
75                     'CACHEMODE_IS_DEFAULT', 'IMGFMT_GENERIC', 'IMGOPTSSYNTAX',
76                     'IMGKEYSECRET', 'QEMU_DEFAULT_MACHINE', 'MALLOC_PERTURB_',
77                     'GDB_OPTIONS', 'PRINT_QEMU']
78
79    def prepare_subprocess(self, args: List[str]) -> Dict[str, str]:
80        if self.debug:
81            args.append('-d')
82
83        with open(args[0], encoding="utf-8") as f:
84            try:
85                if f.readline().rstrip() == '#!/usr/bin/env python3':
86                    args.insert(0, self.python)
87            except UnicodeDecodeError:  # binary test? for future.
88                pass
89
90        os_env = os.environ.copy()
91        os_env.update(self.get_env())
92        return os_env
93
94    def get_env(self) -> Dict[str, str]:
95        env = {}
96        for v in self.env_variables:
97            val = getattr(self, v.lower(), None)
98            if val is not None:
99                env[v] = val
100
101        return env
102
103    def init_directories(self) -> None:
104        """Init directory variables:
105             PYTHONPATH
106             TEST_DIR
107             SOCK_DIR
108             SAMPLE_IMG_DIR
109             OUTPUT_DIR
110        """
111        self.pythonpath = os.getenv('PYTHONPATH')
112        if self.pythonpath:
113            self.pythonpath = self.source_iotests + os.pathsep + \
114                self.pythonpath
115        else:
116            self.pythonpath = self.source_iotests
117
118        self.test_dir = os.getenv('TEST_DIR',
119                                  os.path.join(os.getcwd(), 'scratch'))
120        Path(self.test_dir).mkdir(parents=True, exist_ok=True)
121
122        try:
123            self.sock_dir = os.environ['SOCK_DIR']
124            self.tmp_sock_dir = False
125            Path(self.sock_dir).mkdir(parents=True, exist_ok=True)
126        except KeyError:
127            self.sock_dir = tempfile.mkdtemp()
128            self.tmp_sock_dir = True
129
130        self.sample_img_dir = os.getenv('SAMPLE_IMG_DIR',
131                                        os.path.join(self.source_iotests,
132                                                     'sample_images'))
133
134        self.output_dir = os.getcwd()  # OUTPUT_DIR
135
136    def init_binaries(self) -> None:
137        """Init binary path variables:
138             PYTHON (for bash tests)
139             QEMU_PROG, QEMU_IMG_PROG, QEMU_IO_PROG, QEMU_NBD_PROG, QSD_PROG
140             SOCKET_SCM_HELPER
141        """
142        self.python = sys.executable
143
144        def root(*names: str) -> str:
145            return os.path.join(self.build_root, *names)
146
147        arch = os.uname().machine
148        if 'ppc64' in arch:
149            arch = 'ppc64'
150
151        self.qemu_prog = os.getenv('QEMU_PROG', root(f'qemu-system-{arch}'))
152        if not os.path.exists(self.qemu_prog):
153            pattern = root('qemu-system-*')
154            try:
155                progs = sorted(glob.iglob(pattern))
156                self.qemu_prog = next(p for p in progs if isxfile(p))
157            except StopIteration:
158                sys.exit("Not found any Qemu executable binary by pattern "
159                         f"'{pattern}'")
160
161        self.qemu_img_prog = os.getenv('QEMU_IMG_PROG', root('qemu-img'))
162        self.qemu_io_prog = os.getenv('QEMU_IO_PROG', root('qemu-io'))
163        self.qemu_nbd_prog = os.getenv('QEMU_NBD_PROG', root('qemu-nbd'))
164        self.qsd_prog = os.getenv('QSD_PROG', root('storage-daemon',
165                                                   'qemu-storage-daemon'))
166
167        for b in [self.qemu_img_prog, self.qemu_io_prog, self.qemu_nbd_prog,
168                  self.qemu_prog, self.qsd_prog]:
169            if not os.path.exists(b):
170                sys.exit('No such file: ' + b)
171            if not isxfile(b):
172                sys.exit('Not executable: ' + b)
173
174        helper_path = os.path.join(self.build_iotests, 'socket_scm_helper')
175        if isxfile(helper_path):
176            self.socket_scm_helper = helper_path  # SOCKET_SCM_HELPER
177
178    def __init__(self, imgfmt: str, imgproto: str, aiomode: str,
179                 cachemode: Optional[str] = None,
180                 imgopts: Optional[str] = None,
181                 misalign: bool = False,
182                 debug: bool = False,
183                 valgrind: bool = False,
184                 gdb: bool = False,
185                 qprint: bool = False) -> None:
186        self.imgfmt = imgfmt
187        self.imgproto = imgproto
188        self.aiomode = aiomode
189        self.imgopts = imgopts
190        self.misalign = misalign
191        self.debug = debug
192
193        if qprint:
194            self.print_qemu = 'y'
195
196        if gdb:
197            self.gdb_options = os.getenv('GDB_OPTIONS', DEF_GDB_OPTIONS)
198            if not self.gdb_options:
199                # cover the case 'export GDB_OPTIONS='
200                self.gdb_options = DEF_GDB_OPTIONS
201        elif 'GDB_OPTIONS' in os.environ:
202            # to not propagate it in prepare_subprocess()
203            del os.environ['GDB_OPTIONS']
204
205        if valgrind:
206            self.valgrind_qemu = 'y'
207
208        if cachemode is None:
209            self.cachemode_is_default = 'true'
210            self.cachemode = 'writeback'
211        else:
212            self.cachemode_is_default = 'false'
213            self.cachemode = cachemode
214
215        # Initialize generic paths: build_root, build_iotests, source_iotests,
216        # which are needed to initialize some environment variables. They are
217        # used by init_*() functions as well.
218
219        if os.path.islink(sys.argv[0]):
220            # called from the build tree
221            self.source_iotests = os.path.dirname(os.readlink(sys.argv[0]))
222            self.build_iotests = os.path.dirname(os.path.abspath(sys.argv[0]))
223        else:
224            # called from the source tree
225            self.source_iotests = os.getcwd()
226            self.build_iotests = self.source_iotests
227
228        self.build_root = os.path.join(self.build_iotests, '..', '..')
229
230        self.init_directories()
231        self.init_binaries()
232
233        self.malloc_perturb_ = os.getenv('MALLOC_PERTURB_',
234                                         str(random.randrange(1, 255)))
235
236        # QEMU_OPTIONS
237        self.qemu_options = '-nodefaults -display none -accel qtest'
238        machine_map = (
239            ('arm', 'virt'),
240            ('aarch64', 'virt'),
241            ('avr', 'mega2560'),
242            ('m68k', 'virt'),
243            ('rx', 'gdbsim-r5f562n8'),
244            ('tricore', 'tricore_testboard')
245        )
246        for suffix, machine in machine_map:
247            if self.qemu_prog.endswith(f'qemu-system-{suffix}'):
248                self.qemu_options += f' -machine {machine}'
249
250        # QEMU_DEFAULT_MACHINE
251        self.qemu_default_machine = get_default_machine(self.qemu_prog)
252
253        self.qemu_img_options = os.getenv('QEMU_IMG_OPTIONS')
254        self.qemu_nbd_options = os.getenv('QEMU_NBD_OPTIONS')
255
256        is_generic = self.imgfmt not in ['bochs', 'cloop', 'dmg']
257        self.imgfmt_generic = 'true' if is_generic else 'false'
258
259        self.qemu_io_options = f'--cache {self.cachemode} --aio {self.aiomode}'
260        if self.misalign:
261            self.qemu_io_options += ' --misalign'
262
263        self.qemu_io_options_no_fmt = self.qemu_io_options
264
265        if self.imgfmt == 'luks':
266            self.imgoptssyntax = 'true'
267            self.imgkeysecret = '123456'
268            if not self.imgopts:
269                self.imgopts = 'iter-time=10'
270            elif 'iter-time=' not in self.imgopts:
271                self.imgopts += ',iter-time=10'
272        else:
273            self.imgoptssyntax = 'false'
274            self.qemu_io_options += ' -f ' + self.imgfmt
275
276        if self.imgfmt == 'vmdk':
277            if not self.imgopts:
278                self.imgopts = 'zeroed_grain=on'
279            elif 'zeroed_grain=' not in self.imgopts:
280                self.imgopts += ',zeroed_grain=on'
281
282    def close(self) -> None:
283        if self.tmp_sock_dir:
284            shutil.rmtree(self.sock_dir)
285
286    def __enter__(self) -> 'TestEnv':
287        return self
288
289    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
290        self.close()
291
292    def print_env(self) -> None:
293        template = """\
294QEMU          -- "{QEMU_PROG}" {QEMU_OPTIONS}
295QEMU_IMG      -- "{QEMU_IMG_PROG}" {QEMU_IMG_OPTIONS}
296QEMU_IO       -- "{QEMU_IO_PROG}" {QEMU_IO_OPTIONS}
297QEMU_NBD      -- "{QEMU_NBD_PROG}" {QEMU_NBD_OPTIONS}
298IMGFMT        -- {IMGFMT}{imgopts}
299IMGPROTO      -- {IMGPROTO}
300PLATFORM      -- {platform}
301TEST_DIR      -- {TEST_DIR}
302SOCK_DIR      -- {SOCK_DIR}
303SOCKET_SCM_HELPER -- {SOCKET_SCM_HELPER}
304GDB_OPTIONS   -- {GDB_OPTIONS}
305VALGRIND_QEMU -- {VALGRIND_QEMU}
306PRINT_QEMU_OUTPUT -- {PRINT_QEMU}
307"""
308
309        args = collections.defaultdict(str, self.get_env())
310
311        if 'IMGOPTS' in args:
312            args['imgopts'] = f" ({args['IMGOPTS']})"
313
314        u = os.uname()
315        args['platform'] = f'{u.sysname}/{u.machine} {u.nodename} {u.release}'
316
317        print(template.format_map(args))
318