Debian Codegraph @

test/common/storagelib.py

raw
1 #
2 # Copyright (C) 2015 Red Hat, Inc.
3 # SPDX-License-Identifier: LGPL-2.1-or-later
4
5
6 import json
7 import os.path
8 import re
9 import textwrap
10 from collections.abc import Callable, Collection, Iterable, Mapping, Sequence
11 from functools import cached_property
12 from typing import Any
13
14 from machine.machine_core.machine_virtual import VirtMachine
15 from testlib import Error, JsonObject, MachineCase, wait
16
17
18 def from_udisks_ascii(codepoints: Sequence[int]) -> str:
19 return ''.join(map(chr, codepoints[:-1]))
20
21
22 class StorageHelpers(MachineCase):
23 """Mix-in class for using in tests that derive from something else than MachineCase or StorageCase"""
24
25 def inode(self, f: str) -> str:
26 return self.machine.execute("stat -L '%s' -c %%i" % f)
27
28 def retry(self, check: Callable[[], bool], setup: Callable[[], None] | None = None, teardown: Callable[[], None] | None = None) -> None:
29 def step() -> bool:
30 if setup:
31 setup()
32 if check():
33 return True
34 if teardown:
35 teardown()
36 return False
37
38 self.browser.wait(step)
39
40 def add_ram_disk(self, size: int = 50, delay: int | None = None) -> str:
41 """Add per-test RAM disk
42
43 The disk gets removed automatically when the test ends. This is safe for @nondestructive tests.
44
45 Optionally takes a delay in nanoseconds which delays IO responses, 100000000 equals ~ 40 kB/s.
46
47 Return the device name.
48 """
49 # sanity test: should not yet be loaded
50 self.machine.execute("test ! -e /sys/module/scsi_debug")
51 delay_option = f'ndelay={delay}' if delay else ''
52 # HACK: Don't set the vpd_use_hostno=0 on rhel-9, it is causing issues on c9s downstream release gating
53 vpd_use_hostno = "" if self.machine.image.startswith("rhel-9") else "vpd_use_hostno=0"
54 self.machine.execute(f"modprobe scsi_debug dev_size_mb={size} {vpd_use_hostno} {delay_option}")
55 dev = self.machine.execute('while true; do O=$(ls /sys/bus/pseudo/drivers/scsi_debug/adapter*/host*/target*/*:*/block 2>/dev/null || true); '
56 '[ -n "$O" ] && break || sleep 0.1; done; echo "/dev/$O"').strip()
57 # don't use addCleanup() here, this is often busy and needs to be cleaned up late; done in MachineCase.nonDestructiveSetup()
58
59 return dev
60
61 def add_loopback_disk(self, size: int = 50, name: str | None = None) -> str:
62 """Add per-test loopback disk
63
64 The disk gets removed automatically when the test ends. This is safe for @nondestructive tests.
65
66 Unlike add_ram_disk(), this can be called multiple times, and
67 is less size constrained. The backing file starts out sparse,
68 so this can be used to create massive block devices, as long
69 as you are careful to not actually use much of it.
70
71 However, loopback devices look quite special to the OS, so
72 they are not a very good simulation of a "real" disk.
73
74 Return the device name.
75
76 """
77 # HACK: https://bugzilla.redhat.com/show_bug.cgi?id=1969408
78 # It would be nicer to remove $F immediately after the call to
79 # losetup, but that will break some versions of lvm2.
80 backf = self.machine.execute("mktemp /var/tmp/loop.XXXX").strip()
81 dev = self.machine.execute(f"truncate --size={size}MB {backf}; "
82 f"losetup -P --show {name if name else '--find'} {backf}").strip()
83 # If this device had partitions in its last incarnation on this
84 # machine, they might come back for unknown reasons, in a
85 # non-functional state. Running partprobe will get rid of
86 # them.
87 self.machine.execute("partprobe '%s'" % dev)
88 # Clean up: remove any holders, detach loop device, verify it's gone
89 self.addCleanup(self.machine.execute, f"""
90 udevadm settle --timeout=10
91 for h in /sys/block/{os.path.basename(dev)}/holders/*; do
92 [ -e "$h" ] || break
93 if [ -f "$h/dm/name" ]; then
94 n=$(cat "$h/dm/name")
95 else
96 n=$(basename "$h")
97 fi
98 dmsetup remove --force "$n" || true
99 cryptsetup close "$n" || true
100 mdadm --stop --force "/dev/$n" || true
101 done
102 # Stop udisks to ensure it releases any references to the loop device
103 systemctl stop udisks2 || true
104 udevadm settle --timeout=5
105 # Actively wait for loop device to be detached (kernel may do it async after md/dm removal)
106 for retry in {{1..30}}; do
107 losetup -a | grep -qw {dev} || break
108 losetup -d {dev} && break
109 [ $retry -eq 10 ] && echo "Still waiting for {dev} to detach (retry $retry/30)..." >&2
110 sleep 0.5
111 done
112 if losetup -a | grep -qw {dev}; then
113 echo "ERROR: {dev} still attached after 30 retries!" >&2
114 losetup -a | grep {dev} >&2
115 ls -la /sys/block/{os.path.basename(dev)}/holders/ >&2 || true
116 fuser -v {dev} >&2 || true
117 exit 1
118 fi
119 rm -f {backf}
120 """, timeout=30)
121 self.addCleanup(self.machine.execute, f"findmnt -n -o TARGET {dev} | xargs --no-run-if-empty umount;")
122
123 return dev
124
125 def add_targetd_loopback_disk(self, index: str, size: int = 50) -> str:
126 """Add per-test loopback device that can be forcefully removed.
127 """
128
129 m = self.machine
130 model = f"disk{index}"
131 wwn = f"naa.5000{index:012x}"
132
133 m.execute(f"rm -f /var/tmp/targetd.{model}")
134 m.execute(f"targetcli /backstores/fileio create name={model} size={size}M file_or_dev=/var/tmp/targetd.{model}")
135 m.execute(f"targetcli /loopback create {wwn}")
136 m.execute(f"targetcli /loopback/{wwn}/luns create /backstores/fileio/{model}")
137
138 self.addCleanup(m.execute, f"targetcli /loopback delete {wwn}")
139 self.addCleanup(m.execute, f"targetcli /backstores/fileio delete {model}")
140 self.addCleanup(m.execute, f"rm -f /var/tmp/targetd.{model}")
141
142 dev = m.execute(f'for dev in /sys/block/*; do if [ -f $dev/device/model ] && [ "$(cat $dev/device/model | tr -d [:space:])" == "{model}" ]; then echo /dev/$(basename $dev); fi; done').strip()
143 if dev == "":
144 raise Error("Device not found")
145 return dev
146
147 def force_remove_disk(self, device: str) -> None:
148 """Act like the given device gets physically removed.
149
150 This circumvents all the normal EBUSY failures, and thus can be used for testing
151 the cleanup after a forceful removal.
152 """
153 self.machine.execute(f'echo 1 > /sys/block/{os.path.basename(device)}/device/delete')
154 # the removal trips up PCP and our usage graphs
155 self.allow_browser_errors("direct: instance name lookup failed.*")
156
157 def addCleanupVG(self, vgname: str) -> None:
158 """Ensure the given VG is removed after the test"""
159
160 self.addCleanup(self.machine.execute, f"if [ -d /dev/{vgname} ]; then vgremove --force {vgname}; fi")
161
162 def addCleanupMount(self, mount_point: str) -> None:
163 self.addCleanup(self.machine.execute,
164 f"if mountpoint -q {mount_point}; then umount {mount_point}; fi")
165
166 # Dialogs
167
168 def dialog_wait_open(self) -> None:
169 self.browser.wait_visible('#dialog')
170
171 def dialog_wait_alert(self, text1: str, text2: str | None = None) -> None:
172 def has_alert_title() -> bool:
173 t = self.browser.text('#dialog .pf-v6-c-alert__title')
174 return text1 in t or (text2 is not None and text2 in t)
175 self.browser.wait(has_alert_title)
176
177 def dialog_wait_title(self, text: str) -> None:
178 self.browser.wait_in_text('#dialog .pf-v6-c-modal-box__title', text)
179
180 def dialog_field(self, field: str) -> str:
181 return f'#dialog [data-field="{field}"]'
182
183 def dialog_val(self, field: str) -> Any:
184 sel = self.dialog_field(field)
185 ftype = self.browser.attr(sel, "data-field-type")
186 if ftype == "text-input-checked":
187 if self.browser.is_present(sel + " input[type=checkbox]:not(:checked)"):
188 return False
189 else:
190 return self.browser.val(sel + " input[type=text]")
191 elif ftype == "select":
192 return self.browser.attr(sel, "data-value")
193 else:
194 return self.browser.val(sel)
195
196 def dialog_set_val(self, field: str, val: str | bool | int | dict[str, bool]) -> None:
197 sel = self.dialog_field(field)
198 ftype = self.browser.attr(sel, "data-field-type")
199 if ftype == "checkbox":
200 assert isinstance(val, bool)
201 self.browser.set_checked(sel, val)
202 elif ftype == "select-spaces":
203 assert isinstance(val, dict)
204 for label, value in val.items():
205 self.browser.set_checked(f'{sel} [data-space-name="{label}"] input', value)
206 elif ftype == "size-slider":
207 self.browser.set_val(sel + " .size-unit select", "1000000")
208 self.browser.set_input_text(sel + " .size-text input", str(val))
209 elif ftype == "select":
210 self.browser._wait_present(sel + f" select option[value='{val}']:not([disabled])")
211 self.browser.set_val(sel + " select", val)
212 elif ftype == "select-radio":
213 self.browser.click(sel + f" input[data-data='{val}']")
214 elif ftype == "text-input":
215 assert isinstance(val, str)
216 self.browser.set_input_text(sel, val)
217 elif ftype == "text-input-checked":
218 if not val:
219 self.browser.set_checked(sel + " input[type=checkbox]", val=False)
220 else:
221 assert isinstance(val, str)
222 self.browser.set_checked(sel + " input[type=checkbox]", val=True)
223 self.browser.set_input_text(sel + " [type=text]", val)
224 elif ftype == "combobox":
225 self.browser.click(sel + " button.pf-v6-c-menu-toggle__button")
226 self.browser.click(f".pf-v6-c-menu li:contains('{val}') button")
227 else:
228 self.browser.set_val(sel, val)
229
230 def dialog_combobox_choices(self, field: str) -> Any:
231 return self.browser.call_js_func("""(function () {
232 var lis = ph_find('.pf-v6-c-menu').querySelectorAll('li');
233 var result = [];
234 for (i = 0; i < lis.length; ++i)
235 result.push(lis[i].textContent);
236 return result;
237 })""")
238
239 def dialog_is_present(self, field: str, label: str) -> bool:
240 return self.browser.is_present(f'{self.dialog_field(field)} :contains("{label}")')
241
242 def dialog_wait_val(self, field: str, val: str | bool, unit: str | None = None) -> None:
243 if unit is None:
244 unit = "1000000"
245
246 sel = self.dialog_field(field)
247 ftype = self.browser.attr(sel, "data-field-type")
248 if ftype == "size-slider":
249 self.browser.wait_val(sel + " .size-unit select", unit)
250 self.browser.wait_val(sel + " .size-text input", str(val))
251 elif ftype == "select":
252 self.browser.wait_attr(sel, "data-value", val)
253 elif ftype == "checkbox":
254 self.browser.wait_visible(sel + (":checked" if val else ":not(:checked)"))
255 else:
256 self.browser.wait_val(sel, val)
257
258 def dialog_wait_error(self, field: str, val: str) -> None:
259 # XXX - allow for more than one error
260 self.browser.wait_in_text('#dialog .pf-v6-c-form__helper-text .pf-m-error', val)
261
262 def dialog_wait_not_present(self, field: str) -> None:
263 self.browser.wait_not_present(self.dialog_field(field))
264
265 def dialog_wait_apply_enabled(self) -> None:
266 self.browser.wait_attr('#dialog button.apply:nth-of-type(1)', "disabled", None)
267
268 def dialog_wait_apply_disabled(self) -> None:
269 self.browser.wait_visible('#dialog button.apply:nth-of-type(1)[disabled]')
270
271 def dialog_apply(self) -> None:
272 self.browser.click('#dialog button.apply:nth-of-type(1)')
273
274 def dialog_apply_secondary(self) -> None:
275 self.browser.click('#dialog button.apply:nth-of-type(2)')
276
277 def dialog_cancel(self) -> None:
278 self.browser.click('#dialog button.cancel')
279
280 def dialog_wait_close(self) -> None:
281 # file system operations often take longer than 10s
282 with self.browser.wait_timeout(max(self.browser.timeout, 60)):
283 self.browser.wait_not_present('#dialog')
284
285 def dialog_check(self, expect: Mapping[str, Any]) -> bool:
286 for f in expect:
287 if not self.dialog_val(f) == expect[f]:
288 return False
289 return True
290
291 def dialog_set_vals(self, values: JsonObject) -> None:
292 # Sometimes a certain field needs to be set before other
293 # fields come into existence and thus the order matters that
294 # we set the fields in. The tests however just give us a
295 # unordered 'dict'. Instead of changing the tests, we figure
296 # out the right order dynamically here by just setting what we
297 # can and then starting over. As long as we make progress in
298 # each iteration, everything is good.
299 failed = {}
300 last_error = None
301 for f in values:
302 try:
303 self.dialog_set_val(f, values[f])
304 except Error as e:
305 failed[f] = values[f]
306 last_error = e
307 if failed:
308 if len(failed) < len(values):
309 self.dialog_set_vals(failed)
310 elif last_error is not None:
311 raise last_error
312
313 def dialog(self, values: JsonObject, expect: JsonObject | None = None, secondary: bool = False) -> None:
314 if expect is None:
315 expect = {}
316 self.dialog_wait_open()
317 for f in expect:
318 self.dialog_wait_val(f, expect[f])
319 self.dialog_set_vals(values)
320 if secondary:
321 self.dialog_apply_secondary()
322 else:
323 self.dialog_apply()
324 self.dialog_wait_close()
325
326 def confirm(self) -> None:
327 self.dialog({})
328
329 # There is some asynchronous activity in the storage stack. (It
330 # used to be much worse, but it has improved over the years, yay!)
331 #
332 # The tests deal with that by waiting for the right conditions,
333 # which sometimes means opening a dialog a couple of times until
334 # it has the right contents, or applying it a couple of times
335 # until it works.
336
337 def dialog_open_with_retry(self, trigger: Callable[[], None], expect: Mapping[str, Any] | Callable[[], bool]) -> None:
338 def setup() -> None:
339 trigger()
340 self.dialog_wait_open()
341
342 def check() -> bool:
343 if callable(expect):
344 return expect()
345 else:
346 return self.dialog_check(expect)
347
348 def teardown() -> None:
349 self.dialog_cancel()
350 self.dialog_wait_close()
351 self.retry(check, setup, teardown)
352
353 def dialog_apply_with_retry(self, expected_errors: Collection[str] | None = None) -> None:
354 def step() -> bool:
355 try:
356 self.dialog_apply()
357 self.dialog_wait_close()
358 except Error:
359 if expected_errors is None:
360 return False
361 err = self.browser.text('#dialog')
362 print(err)
363 for exp in expected_errors:
364 if exp in err:
365 return False
366 raise
367 return True
368 self.browser.wait(step)
369
370 def dialog_with_retry(self, trigger: Callable[[], None], values: Mapping[str, Any], expect: Callable[[], bool] | Mapping[str, Any]) -> None:
371 self.dialog_open_with_retry(trigger, expect)
372 if values:
373 for f in values:
374 self.dialog_set_val(f, values[f])
375 self.dialog_apply()
376 else:
377 self.dialog_cancel()
378 self.dialog_wait_close()
379
380 def dialog_with_error_retry(self, trigger: Callable[[], None], errors: Iterable[str], values: JsonObject | None = None,
381 first_setup: Callable[[], None] | None = None, retry_setup: Callable[[], None] | None = None,
382 setup: Callable[[], None] | None = None) -> None:
383 def doit() -> bool:
384 nonlocal first_setup
385 trigger()
386 self.dialog_wait_open()
387 if values:
388 self.dialog_set_vals(values)
389 if first_setup:
390 first_setup()
391 first_setup = None
392 elif retry_setup:
393 retry_setup()
394 elif setup:
395 setup()
396 self.dialog_apply()
397 try:
398 self.dialog_wait_close()
399 return True
400 except Exception:
401 dialog_text = self.browser.text('#dialog .pf-v6-c-alert__title')
402 for err in errors:
403 if err in dialog_text:
404 print("WARNING: retrying dialog")
405 self.dialog_cancel()
406 self.dialog_wait_close()
407 return False
408 raise
409 self.browser.wait(doit)
410
411 def udisks_objects(self) -> Any:
412 return json.loads(self.machine.execute(["python3", "-c", textwrap.dedent("""
413 import dbus, json
414 print(json.dumps(dbus.SystemBus().call_blocking(
415 "org.freedesktop.UDisks2",
416 "/org/freedesktop/UDisks2",
417 "org.freedesktop.DBus.ObjectManager",
418 "GetManagedObjects", "", [])))""")]))
419
420 def configuration_field(self, dev: str, tab: str, field: str) -> str:
421 managerObjects = self.udisks_objects()
422 for path in managerObjects:
423 if "org.freedesktop.UDisks2.Block" in managerObjects[path]:
424 iface = managerObjects[path]["org.freedesktop.UDisks2.Block"]
425 if from_udisks_ascii(iface["Device"]) == dev or from_udisks_ascii(iface["PreferredDevice"]) == dev:
426 for entry in iface["Configuration"]:
427 if entry[0] == tab:
428 if field in entry[1]:
429 print(f"{path}/{tab}/{field} = {from_udisks_ascii(entry[1][field])}")
430 return from_udisks_ascii(entry[1][field])
431 return ""
432
433 def assert_in_configuration(self, dev: str, tab: str, field: str, text: str) -> None:
434 self.assertIn(text, self.configuration_field(dev, tab, field))
435
436 def assert_not_in_configuration(self, dev: str, tab: str, field: str, text: str) -> None:
437 self.assertNotIn(text, self.configuration_field(dev, tab, field))
438
439 def child_configuration_field(self, dev: str, tab: str, field: str) -> str:
440 udisks_objects = self.udisks_objects()
441 for path in udisks_objects:
442 if "org.freedesktop.UDisks2.Encrypted" in udisks_objects[path]:
443 block_iface = udisks_objects[path]["org.freedesktop.UDisks2.Block"]
444 crypto_iface = udisks_objects[path]["org.freedesktop.UDisks2.Encrypted"]
445 if from_udisks_ascii(block_iface["Device"]) == dev or from_udisks_ascii(block_iface["PreferredDevice"]) == dev:
446 for entry in crypto_iface["ChildConfiguration"]:
447 if entry[0] == tab:
448 if field in entry[1]:
449 print(f"{path}/child/{tab}/{field} = {from_udisks_ascii(entry[1][field])}")
450 return from_udisks_ascii(entry[1][field])
451 return ""
452
453 def assert_in_child_configuration(self, dev: str, tab: str, field: str, text: str) -> None:
454 self.assertIn(text, self.child_configuration_field(dev, tab, field))
455
456 def lvol_child_configuration_field(self, lvol: str, tab: str, field: str) -> str:
457 udisk_objects = self.udisks_objects()
458 for path in udisk_objects:
459 if "org.freedesktop.UDisks2.LogicalVolume" in udisk_objects[path]:
460 iface = udisk_objects[path]["org.freedesktop.UDisks2.LogicalVolume"]
461 if iface["Name"] == lvol:
462 for entry in iface["ChildConfiguration"]:
463 if entry[0] == tab:
464 if field in entry[1]:
465 print(f"{path}/child/{tab}/{field} = {from_udisks_ascii(entry[1][field])}")
466 return from_udisks_ascii(entry[1][field])
467 return ""
468
469 def assert_in_lvol_child_configuration(self, lvol: str, tab: str, field: str, text: str) -> None:
470 self.assertIn(text, self.lvol_child_configuration_field(lvol, tab, field))
471
472 def setup_systemd_password_agent(self, password: str) -> None:
473 # This sets up a systemd password agent that replies to all
474 # queries with the given password.
475
476 self.write_file("/usr/local/bin/test-password-agent",
477 f"""#!/bin/sh
478 # Sleep a bit to avoid starting this agent too quickly over and over,
479 # and so that other agents get a chance as well.
480 sleep 10
481
482 for s in $(grep -h ^Socket= /run/systemd/ask-password/ask.* | sed 's/^Socket=//'); do
483 printf '%s' '{password}' | /usr/lib/systemd/systemd-reply-password 1 $s
484 done
485 """, perm="0755")
486
487 self.write_file("/etc/systemd/system/test-password-agent.service",
488 """
489 [Unit]
490 Description=Test Password Agent
491 DefaultDependencies=no
492 Conflicts=shutdown.target emergency.service
493 Before=shutdown.target
494 [Service]
495 ExecStart=/usr/local/bin/test-password-agent
496 """)
497
498 self.write_file("/etc/systemd/system/test-password-agent.path",
499 """
500 [Unit]
501 Description=Test Password Agent Directory Watch
502 DefaultDependencies=no
503 Conflicts=shutdown.target emergency.service
504 Before=paths.target shutdown.target cryptsetup.target
505 [Path]
506 DirectoryNotEmpty=/run/systemd/ask-password
507 MakeDirectory=yes
508 """)
509 self.machine.execute("ln -s ../test-password-agent.path /etc/systemd/system/sysinit.target.wants/")
510
511 def modify_rootfs(self, vgname: str = "root", lvname: str = "root",
512 passphrase: str | None = None) -> None:
513 m = self.machine
514
515 # Set up a password agent in the old root and then arrange for
516 # it to be included in the initrd. This will unlock the new
517 # encrypted root during boot.
518 #
519 # The password agent and its initrd configuration will be
520 # copied to the new root, so it will stay in place also when
521 # the initrd is regenerated again from within the new root.
522
523 if passphrase:
524 self.setup_systemd_password_agent(passphrase)
525 install_items = [
526 '/etc/systemd/system/sysinit.target.wants/test-password-agent.path',
527 '/etc/systemd/system/test-password-agent.path',
528 '/etc/systemd/system/test-password-agent.service',
529 '/usr/local/bin/test-password-agent',
530 ]
531 m.write("/etc/dracut.conf.d/01-askpass.conf",
532 f'install_items+=" {" ".join(install_items)} "')
533
534 # The first step is to move /boot to a new unencrypted
535 # partition on the new disk but keep it mounted at /boot.
536 # This helps when running grub2-install and grub2-mkconfig,
537 # which will look at /boot and do the right thing.
538 #
539 # Then we copy (most of) the old root to the new disk, into a
540 # logical volume, maybe sitting on top of a LUKS container.
541 #
542 # The kernel command line is changed to use the new root
543 # filesystem, and grub is installed on the new disk. The boot
544 # configuration of the VM has been changed to boot from the
545 # new disk.
546 #
547 # At that point the new root can be booted by the existing
548 # initrd, but the initrd will prompt for the passphrase (as
549 # expected). Thus, the initrd is regenerated to include the
550 # password agent from above.
551 #
552 # Before the reboot, we destroy the original disk to make
553 # really sure that it won't be used anymore.
554
555 # Assert this is a destructive test which always is a VirtMachine.
556 assert isinstance(m, VirtMachine)
557 info = m.add_disk("6G", serial="NEWROOT", boot_disk=True)
558 dev = "/dev/" + info["dev"]
559 wait(lambda: m.execute(f"test -b {dev} && echo present").strip() == "present")
560 m.execute(f"""
561 set -x
562 parted -s {dev} mktable msdos
563 parted -s {dev} mkpart primary ext4 1M 1000M
564 parted -s {dev} mkpart primary ext4 1000M 100%
565 if [ "{passphrase}" != "None" ]; then
566 echo {passphrase} | cryptsetup luksFormat --pbkdf-memory=300 {dev}2
567 luks_uuid=$(blkid -p {dev}2 -s UUID -o value)
568 echo {passphrase} | cryptsetup luksOpen --pbkdf-memory=300 {dev}2 luks-$luks_uuid
569 vgcreate {vgname} /dev/mapper/luks-$luks_uuid
570 luks_karg=rd.luks.uuid=$luks_uuid
571 else
572 vgcreate {vgname} {dev}2
573 fi
574 lvcreate {vgname} -n {lvname} -l100%VG
575 mkfs.ext4 /dev/{vgname}/{lvname}
576 mkdir /new-root
577 mount /dev/{vgname}/{lvname} /new-root
578 mkfs.ext4 {dev}1
579 # don't move the EFI partition
580 if mountpoint /boot/efi; then umount /boot/efi; fi
581 mkdir /new-root/boot
582 mount {dev}1 /new-root/boot
583 tar --selinux --one-file-system -cf - --exclude /boot --exclude='/var/tmp/*' --exclude='/var/cache/*' \
584 --exclude='/var/lib/mock/*' --exclude='/var/lib/containers/*' --exclude='/new-root/*' \
585 / | tar --selinux -C /new-root -xf -
586 # latest Fedora have /var on a separate subvolume
587 if mountpoint /var; then
588 tar -C /var --selinux --one-file-system -cf - --exclude='tmp/*' --exclude='cache/*' \
589 --exclude='lib/mock/*' --exclude='lib/containers/*' \
590 . | tar --selinux -C /new-root/var -xf -
591 fi
592 tar --one-file-system -C /boot -cf - . | tar -C /new-root/boot -xf -
593 umount /new-root/boot
594 mount {dev}1 /boot
595 echo "(hd0) {dev}" >/boot/grub2/device.map
596 sed -i -e 's,/boot/,/,' /boot/loader/entries/*
597 uuid=$(blkid -p /dev/{vgname}/{lvname} -s UUID -o value)
598 buuid=$(blkid -p {dev}1 -s UUID -o value)
599 echo "UUID=$uuid / auto defaults 0 0" >/new-root/etc/fstab
600 echo "UUID=$buuid /boot auto defaults 0 0" >>/new-root/etc/fstab
601 if [ "{passphrase}" != "None" ]; then dracut --regenerate-all --force; fi
602 grub2-install {dev}
603 ( # HACK - grub2-mkconfig messes with /boot/loader/entries/ and /etc/kernel/cmdline
604 mv /boot/loader/entries /boot/loader/entries.stowed
605 ! test -f /etc/kernel/cmdline || mv /etc/kernel/cmdline /etc/kernel/cmdline.stowed
606 grub2-mkconfig -o /boot/grub2/grub.cfg
607 mv /boot/loader/entries.stowed /boot/loader/entries
608 ! test -f /etc/kernel/cmdline.stowed || mv /etc/kernel/cmdline.stowed /etc/kernel/cmdline
609 )
610 grubby --update-kernel=ALL --args="root=UUID=$uuid rootflags=defaults $luks_karg rd.lvm.lv={vgname}/{lvname}"
611 ! test -f /etc/kernel/cmdline || cp /etc/kernel/cmdline /new-root/etc/kernel/cmdline
612 """, timeout=300)
613 # destroy bootability of the current root partition, just to make sure
614 m.execute("rm -rf /etc/*")
615 m.reboot()
616 self.assertEqual(m.execute("findmnt -n -o SOURCE /").strip(), f"/dev/mapper/{vgname}-{lvname}")
617
618 # Cards and tables
619
620 def card(self, title: str) -> str:
621 return f"[data-test-card-title='{title}']"
622
623 def card_parent_link(self) -> str:
624 return ".pf-v6-c-breadcrumb__item:nth-last-child(2) > a"
625
626 def card_header(self, title: str) -> str:
627 return self.card(title) + " .pf-v6-c-card__header"
628
629 def card_row(self, title: str, index: int | None = None, name: str | None = None, location: str | None = None, table_index: int = 1) -> str:
630 pfx = self.card(title) + f" table:nth-of-type({table_index})"
631 if index is not None:
632 return pfx + f" tbody tr:nth-child({index})"
633 elif name is not None:
634 name = name.replace("/dev/", "")
635 return pfx + f" tbody [data-test-row-name='{name}']"
636 else:
637 return pfx + f" tbody [data-test-row-location='{location}']"
638
639 def click_card_row(self, title: str, index: int | None = None, name: str | None = None, location: str | None = None, table_index: int = 1) -> None:
640 self.browser.click_button("id-link", self.card_row(title, index, name, location, table_index))
641
642 def card_row_col(self, title: str, row_index: int | None = None, col_index: int | None = None,
643 row_name: str | None = None, row_location: str | None = None, table_index: int = 1) -> str:
644 return self.card_row(title, row_index, row_name, row_location, table_index) + f" td:nth-child({col_index})"
645
646 def card_desc(self, card_title: str, desc_title: str) -> str:
647 return self.card(card_title) + f" [data-test-desc-title='{desc_title}'] [data-test-value=true]"
648
649 def card_desc_action(self, card_title: str, desc_title: str) -> str:
650 return self.card(card_title) + f" [data-test-desc-title='{desc_title}'] [data-test-action=true] button"
651
652 def card_button(self, card_title: str, button_title: str) -> str:
653 return self.card(card_title) + f" button:contains('{button_title}')"
654
655 def dropdown_toggle(self, parent: str) -> str:
656 return parent + " .pf-v6-c-menu-toggle"
657
658 def dropdown_action(self, title: str) -> str:
659 return f".pf-v6-c-menu button:contains('{title}')"
660
661 def click_dropdown(self, parent: str, title: str) -> None:
662 self.browser.click(self.dropdown_toggle(parent))
663 self.browser.click(self.dropdown_action(title))
664
665 def click_card_dropdown(self, card_title: str, button_title: str) -> None:
666 self.click_dropdown(self.card_header(card_title), button_title)
667
668 def click_devices_dropdown(self, title: str) -> None:
669 self.click_card_dropdown("Storage", title)
670
671 def check_dropdown_action_disabled(self, parent: str, title: str, expected_text: str) -> None:
672 self.browser.click(self.dropdown_toggle(parent))
673 self.browser.wait_visible(self.dropdown_action(title) + "[disabled]")
674 self.browser.wait_in_text(self.dropdown_action(title) + "[disabled]", expected_text)
675 self.browser.click(self.dropdown_toggle(parent))
676
677 def wait_mounted(self, card_title: str) -> None:
678 with self.browser.wait_timeout(30):
679 self.browser.wait_not_in_text(self.card_desc(card_title, "Mount point"),
680 "The filesystem is not mounted.")
681
682 def wait_not_mounted(self, card_title: str) -> None:
683 with self.browser.wait_timeout(30):
684 self.browser.wait_in_text(self.card_desc(card_title, "Mount point"),
685 "The filesystem is not mounted.")
686
687 def wait_card_button_disabled(self, card_title: str, button_title: str) -> None:
688 with self.browser.wait_timeout(30):
689 self.browser.wait_visible(self.card_button(card_title, button_title) + ":disabled")
690
691
692 class StorageCase(StorageHelpers):
693
694 def setUp(self) -> None:
695
696 if self.image == "fedora-coreos":
697 self.skipTest("No udisks/cockpit-storaged on OSTree images")
698
699 super().setUp()
700
701 # OSTree friendly, automatically unmounted and cleaned up
702 self.mnt_dir = os.path.join(self.vm_tmpdir, "mnt")
703 self.machine.execute(f"mkdir -p {self.mnt_dir}")
704
705 if self.image.startswith("rhel-8"):
706 # HACK: missing /etc/crypttab file upsets udisks: https://github.com/storaged-project/udisks/pull/835
707 self.machine.write("/etc/crypttab", "")
708
709 # starting out with empty PCP logs and pmlogger not running causes these metrics channel messages
710 self.allow_journal_messages("pcp-archive: no such metric: disk.*")
711
712 # UDisks2 invalidates the Size property and cockpit-bridge
713 # gets it immediately. But sometimes the interface is already
714 # gone.
715 self.allow_journal_messages("org.freedesktop.UDisks2: couldn't get property org.freedesktop.UDisks2.Filesystem Size .* No such interface.*")
716
717 @cached_property
718 def storaged_version(self) -> list[int]:
719 ver = self.machine.execute("busctl --system get-property org.freedesktop.UDisks2 /org/freedesktop/UDisks2/Manager org.freedesktop.UDisks2.Manager Version || true")
720 m = re.match(r's "(.*)"', ver)
721 if m:
722 return list(map(int, m.group(1).split(".")))
723 else:
724 return [0]
725
726 @cached_property
727 def default_crypto_type(self) -> str:
728 crypto_types = self.machine.execute("busctl --system get-property org.freedesktop.UDisks2 /org/freedesktop/UDisks2/Manager org.freedesktop.UDisks2.Manager SupportedEncryptionTypes || true")
729 return "luks2" if "luks2" in crypto_types else "luks1"
730
731
732 class StorageSmartCase(StorageCase):
733 provision = {
734 "0": {
735 "disk_bus": "sata",
736 "disk_dev": "sda",
737 }
738 }