Acceptance tests: clarify ssh connection failure reason
[qemu/ar7.git] / tests / acceptance / virtiofs_submounts.py
blob949ca87a83726aa913f0158cc277d8ae0f3c5dda
1 import logging
2 import re
3 import os
4 import subprocess
5 import time
7 from avocado import skipUnless
8 from avocado_qemu import Test, BUILD_DIR
9 from avocado_qemu import wait_for_console_pattern
10 from avocado.utils import ssh
12 from qemu.accel import kvm_available
14 from boot_linux import BootLinux
17 def run_cmd(args):
18 subp = subprocess.Popen(args,
19 stdout=subprocess.PIPE,
20 stderr=subprocess.PIPE,
21 universal_newlines=True)
22 stdout, stderr = subp.communicate()
23 ret = subp.returncode
25 return (stdout, stderr, ret)
27 def has_cmd(name, args=None):
28 """
29 This function is for use in a @avocado.skipUnless decorator, e.g.:
31 @skipUnless(*has_cmd('sudo -n', ('sudo', '-n', 'true')))
32 def test_something_that_needs_sudo(self):
33 ...
34 """
36 if args is None:
37 args = ('which', name)
39 try:
40 _, stderr, exitcode = run_cmd(args)
41 except Exception as e:
42 exitcode = -1
43 stderr = str(e)
45 if exitcode != 0:
46 cmd_line = ' '.join(args)
47 err = f'{name} required, but "{cmd_line}" failed: {stderr.strip()}'
48 return (False, err)
49 else:
50 return (True, '')
52 def has_cmds(*cmds):
53 """
54 This function is for use in a @avocado.skipUnless decorator and
55 allows checking for the availability of multiple commands, e.g.:
57 @skipUnless(*has_cmds(('cmd1', ('cmd1', '--some-parameter')),
58 'cmd2', 'cmd3'))
59 def test_something_that_needs_cmd1_and_cmd2(self):
60 ...
61 """
63 for cmd in cmds:
64 if isinstance(cmd, str):
65 cmd = (cmd,)
67 ok, errstr = has_cmd(*cmd)
68 if not ok:
69 return (False, errstr)
71 return (True, '')
74 class VirtiofsSubmountsTest(BootLinux):
75 """
76 :avocado: tags=arch:x86_64
77 """
79 def get_portfwd(self):
80 port = None
82 res = self.vm.command('human-monitor-command',
83 command_line='info usernet')
84 for line in res.split('\r\n'):
85 match = \
86 re.search(r'TCP.HOST_FORWARD.*127\.0\.0\.1\s+(\d+)\s+10\.',
87 line)
88 if match is not None:
89 port = int(match[1])
90 break
92 self.assertIsNotNone(port)
93 self.assertGreater(port, 0)
94 self.log.debug('sshd listening on port: %d', port)
95 return port
97 def ssh_connect(self, username, keyfile):
98 self.ssh_logger = logging.getLogger('ssh')
99 port = self.get_portfwd()
100 self.ssh_session = ssh.Session('127.0.0.1', port=port,
101 user=username, key=keyfile)
102 for i in range(10):
103 try:
104 self.ssh_session.connect()
105 return
106 except:
107 time.sleep(4)
108 pass
109 self.fail('ssh connection timeout')
111 def ssh_command(self, command):
112 self.ssh_logger.info(command)
113 result = self.ssh_session.cmd(command)
114 stdout_lines = [line.rstrip() for line
115 in result.stdout_text.splitlines()]
116 for line in stdout_lines:
117 self.ssh_logger.info(line)
118 stderr_lines = [line.rstrip() for line
119 in result.stderr_text.splitlines()]
120 for line in stderr_lines:
121 self.ssh_logger.warning(line)
123 self.assertEqual(result.exit_status, 0,
124 f'Guest command failed: {command}')
125 return stdout_lines, stderr_lines
127 def run(self, args, ignore_error=False):
128 stdout, stderr, ret = run_cmd(args)
130 if ret != 0:
131 cmdline = ' '.join(args)
132 if not ignore_error:
133 self.fail(f'{cmdline}: Returned {ret}: {stderr}')
134 else:
135 self.log.warn(f'{cmdline}: Returned {ret}: {stderr}')
137 return (stdout, stderr, ret)
139 def set_up_shared_dir(self):
140 self.shared_dir = os.path.join(self.workdir, 'virtiofs-shared')
142 os.mkdir(self.shared_dir)
144 self.run(('cp', self.get_data('guest.sh'),
145 os.path.join(self.shared_dir, 'check.sh')))
147 self.run(('cp', self.get_data('guest-cleanup.sh'),
148 os.path.join(self.shared_dir, 'cleanup.sh')))
150 def set_up_virtiofs(self):
151 attmp = os.getenv('AVOCADO_TESTS_COMMON_TMPDIR')
152 self.vfsdsock = os.path.join(attmp, 'vfsdsock')
154 self.run(('sudo', '-n', 'rm', '-f', self.vfsdsock), ignore_error=True)
156 self.virtiofsd = \
157 subprocess.Popen(('sudo', '-n',
158 'tools/virtiofsd/virtiofsd',
159 f'--socket-path={self.vfsdsock}',
160 '-o', f'source={self.shared_dir}',
161 '-o', 'cache=always',
162 '-o', 'xattr',
163 '-o', 'announce_submounts',
164 '-f'),
165 stdout=subprocess.DEVNULL,
166 stderr=subprocess.PIPE,
167 universal_newlines=True)
169 while not os.path.exists(self.vfsdsock):
170 if self.virtiofsd.poll() is not None:
171 self.fail('virtiofsd exited prematurely: ' +
172 self.virtiofsd.communicate()[1])
173 time.sleep(0.1)
175 self.run(('sudo', '-n', 'chmod', 'go+rw', self.vfsdsock))
177 self.vm.add_args('-chardev',
178 f'socket,id=vfsdsock,path={self.vfsdsock}',
179 '-device',
180 'vhost-user-fs-pci,queue-size=1024,chardev=vfsdsock' \
181 ',tag=host',
182 '-object',
183 'memory-backend-file,id=mem,size=1G,' \
184 'mem-path=/dev/shm,share=on',
185 '-numa',
186 'node,memdev=mem')
188 def launch_vm(self):
189 self.launch_and_wait()
190 self.ssh_connect('root', self.ssh_key)
192 def set_up_nested_mounts(self):
193 scratch_dir = os.path.join(self.shared_dir, 'scratch')
194 try:
195 os.mkdir(scratch_dir)
196 except FileExistsError:
197 pass
199 args = ['bash', self.get_data('host.sh'), scratch_dir]
200 if self.seed:
201 args += [self.seed]
203 out, _, _ = self.run(args)
204 seed = re.search(r'^Seed: \d+', out)
205 self.log.info(seed[0])
207 def mount_in_guest(self):
208 self.ssh_command('mkdir -p /mnt/host')
209 self.ssh_command('mount -t virtiofs host /mnt/host')
211 def check_in_guest(self):
212 self.ssh_command('bash /mnt/host/check.sh /mnt/host/scratch/share')
214 def live_cleanup(self):
215 self.ssh_command('bash /mnt/host/cleanup.sh /mnt/host/scratch')
217 # It would be nice if the above was sufficient to make virtiofsd clear
218 # all references to the mounted directories (so they can be unmounted
219 # on the host), but unfortunately it is not. To do so, we have to
220 # resort to a remount.
221 self.ssh_command('mount -o remount /mnt/host')
223 scratch_dir = os.path.join(self.shared_dir, 'scratch')
224 self.run(('bash', self.get_data('cleanup.sh'), scratch_dir))
226 @skipUnless(*has_cmds(('sudo -n', ('sudo', '-n', 'true')),
227 'ssh-keygen', 'bash', 'losetup', 'mkfs.xfs', 'mount'))
228 def setUp(self):
229 vmlinuz = self.params.get('vmlinuz')
230 if vmlinuz is None:
231 self.cancel('vmlinuz parameter not set; you must point it to a '
232 'Linux kernel binary to test (to run this test with ' \
233 'the on-image kernel, set it to an empty string)')
235 self.seed = self.params.get('seed')
237 self.ssh_key = os.path.join(self.workdir, 'id_ed25519')
239 self.run(('ssh-keygen', '-N', '', '-t', 'ed25519', '-f', self.ssh_key))
241 pubkey = open(self.ssh_key + '.pub').read()
243 super(VirtiofsSubmountsTest, self).setUp(pubkey)
245 if len(vmlinuz) > 0:
246 self.vm.add_args('-kernel', vmlinuz,
247 '-append', 'console=ttyS0 root=/dev/sda1')
249 # Allow us to connect to SSH
250 self.vm.add_args('-netdev', 'user,id=vnet,hostfwd=:127.0.0.1:0-:22',
251 '-device', 'virtio-net,netdev=vnet')
253 if not kvm_available(self.arch, self.qemu_bin):
254 self.cancel(KVM_NOT_AVAILABLE)
255 self.vm.add_args('-accel', 'kvm')
257 def tearDown(self):
258 try:
259 self.vm.shutdown()
260 except:
261 pass
263 scratch_dir = os.path.join(self.shared_dir, 'scratch')
264 self.run(('bash', self.get_data('cleanup.sh'), scratch_dir),
265 ignore_error=True)
267 def test_pre_virtiofsd_set_up(self):
268 self.set_up_shared_dir()
270 self.set_up_nested_mounts()
272 self.set_up_virtiofs()
273 self.launch_vm()
274 self.mount_in_guest()
275 self.check_in_guest()
277 def test_pre_launch_set_up(self):
278 self.set_up_shared_dir()
279 self.set_up_virtiofs()
281 self.set_up_nested_mounts()
283 self.launch_vm()
284 self.mount_in_guest()
285 self.check_in_guest()
287 def test_post_launch_set_up(self):
288 self.set_up_shared_dir()
289 self.set_up_virtiofs()
290 self.launch_vm()
292 self.set_up_nested_mounts()
294 self.mount_in_guest()
295 self.check_in_guest()
297 def test_post_mount_set_up(self):
298 self.set_up_shared_dir()
299 self.set_up_virtiofs()
300 self.launch_vm()
301 self.mount_in_guest()
303 self.set_up_nested_mounts()
305 self.check_in_guest()
307 def test_two_runs(self):
308 self.set_up_shared_dir()
310 self.set_up_nested_mounts()
312 self.set_up_virtiofs()
313 self.launch_vm()
314 self.mount_in_guest()
315 self.check_in_guest()
317 self.live_cleanup()
318 self.set_up_nested_mounts()
320 self.check_in_guest()