| 1 | #!/usr/bin/env python3 |
| 2 | """VM library and trust-boundary regressions, without a hypervisor.""" |
| 3 | import importlib |
| 4 | import importlib.util |
| 5 | import json |
| 6 | import os |
| 7 | import pty |
| 8 | import select |
| 9 | from pathlib import Path |
| 10 | import socket |
| 11 | import struct |
| 12 | import tempfile |
| 13 | import threading |
| 14 | import unittest |
| 15 | from unittest.mock import patch |
| 16 | import sys |
| 17 | from types import SimpleNamespace |
| 18 | sys.path.insert(0, str(Path(__file__).parent)) |
| 19 | import vms |
| 20 | spec = importlib.util.spec_from_file_location('vm_host', Path(__file__).with_name('dashboard-host.py')) |
| 21 | host = importlib.util.module_from_spec(spec) |
| 22 | spec.loader.exec_module(host) |
| 23 | |
| 24 | |
| 25 | class VMTests(unittest.TestCase): |
| 26 | def test_media_replaces_a_guest_locked_cd_and_persists_until_ejected(self): |
| 27 | with tempfile.TemporaryDirectory() as temporary: |
| 28 | directory = Path(temporary).resolve() |
| 29 | installer = directory / 'installer.iso' |
| 30 | installer.write_bytes(b'installer') |
| 31 | vm = directory / 'fixture' |
| 32 | vm.mkdir() |
| 33 | seed = vm / 'seed.iso' |
| 34 | seed.write_bytes(b'setup') |
| 35 | definition = f'''<domain><os><type arch="x86_64" machine="q35"/></os> |
| 36 | <devices><disk type="file" device="cdrom"><driver name="qemu" type="raw"/> |
| 37 | <source file="{seed}"/><target dev="sdb" bus="sata"/><readonly/> |
| 38 | </disk></devices></domain>''' |
| 39 | |
| 40 | def virsh(action, *args): |
| 41 | nonlocal definition |
| 42 | if action == 'dumpxml': |
| 43 | return definition |
| 44 | if action == 'domstate': |
| 45 | return 'running' |
| 46 | self.assertEqual(action, 'update-device') |
| 47 | self.assertIn('--live', args) |
| 48 | self.assertIn('--config', args) |
| 49 | if '--force' not in args: |
| 50 | raise vms.subprocess.CalledProcessError(1, action, stderr='tray locked') |
| 51 | cd = vms.ET.parse(args[1]).getroot() |
| 52 | self.assertIsNotNone(cd.find('readonly')) |
| 53 | definition = '<domain><devices>' + vms.ET.tostring(cd, encoding='unicode') + '</devices></domain>' |
| 54 | return '' |
| 55 | |
| 56 | with patch.object(vms, 'DISKS', directory), patch.object(vms, 'resolve_image', return_value=installer), \ |
| 57 | patch.object(vms, 'virsh', side_effect=virsh): |
| 58 | vms.change_media({'name': 'fixture', 'image': 'installer.iso'}) |
| 59 | attached = Path(vms.ET.fromstring(definition).find('./devices/disk/source').get('file')) |
| 60 | self.assertEqual(attached.read_bytes(), installer.read_bytes()) |
| 61 | self.assertFalse(seed.exists()) |
| 62 | vms.change_media({'name': 'fixture', 'image': ''}) |
| 63 | self.assertIsNone(vms.ET.fromstring(definition).find('./devices/disk/source')) |
| 64 | self.assertFalse(attached.exists()) |
| 65 | self.assertTrue(installer.exists()) |
| 66 | |
| 67 | def test_secure_preset_retains_efi_state_but_generates_new_login(self): |
| 68 | with tempfile.TemporaryDirectory() as temporary: |
| 69 | root = Path(temporary).resolve() |
| 70 | disks = root / 'vms' |
| 71 | source = disks / 'template' |
| 72 | source.mkdir(parents=True) |
| 73 | (source / 'disk.qcow2').write_bytes(b'prepared disk') |
| 74 | (source / 'nvram.fd').write_bytes(b'prepared signed EFI variables') |
| 75 | code = root / 'code.fd' |
| 76 | code.write_bytes(b'firmware') |
| 77 | defaults = root / 'vars.fd' |
| 78 | defaults.write_bytes(b'fresh EFI variables') |
| 79 | xml = f'''<domain><metadata><vm xmlns="{vms.NS[1:-1]}"> |
| 80 | <platform>windows</platform><hardwareProfile>windows-aarch64-nvme</hardwareProfile> |
| 81 | </vm></metadata><memory>8388608</memory><vcpu>4</vcpu> |
| 82 | <os><type arch="aarch64">hvm</type><loader>{code}</loader><nvram>{source / 'nvram.fd'}</nvram></os> |
| 83 | <devices><disk device="disk"><source file="{source / 'disk.qcow2'}"/></disk></devices></domain>''' |
| 84 | def command(*args, **kwargs): |
| 85 | if args[0] == 'cp': |
| 86 | with os.fdopen(os.dup(int(args[-2].split('/')[-1])), 'rb') as incoming: |
| 87 | Path(args[-1]).write_bytes(incoming.read()) |
| 88 | elif args[:2] == ('qemu-img', 'convert'): |
| 89 | Path(args[-1]).write_bytes(Path(args[-2]).read_bytes()) |
| 90 | return json.dumps({'format': 'qcow2', 'virtual-size': 1024, 'format-specific': {'data': {}}}) |
| 91 | def virsh(*args, **kwargs): |
| 92 | return {'domstate': 'shut off', 'dumpxml': xml, 'pool-list': 'vms', 'pool-info': 'State: active'}.get(args[0], '') |
| 93 | with patch.object(vms, 'DISKS', disks), patch.object(vms, 'PRESETS', root / 'presets'), \ |
| 94 | patch.object(vms, 'command', side_effect=command), patch.object(vms, 'virsh', side_effect=virsh), \ |
| 95 | patch.object(vms, 'secure_firmware', return_value=(code, defaults)), \ |
| 96 | patch.dict(os.environ, {'SNOWGLOBE_VM_WINDOWS_ARM_EMULATOR': '/qemu-system-aarch64'}): |
| 97 | vms.save_preset({'name': 'template', 'id': 'prepared', 'os': 'Windows 11 Pro ARM64', |
| 98 | 'description': '', 'setup': 'windows-v4'}) |
| 99 | for name in ['first', 'second']: |
| 100 | vms.create({'name': name, 'description': '', 'image': 'prepared', 'mode': 'preset', |
| 101 | 'owner': 'fixture', 'username': name, 'vcpus': 4, 'memory': 8 * 2**30, |
| 102 | 'disk': 1024, 'start': False, 'autostart': False}) |
| 103 | self.assertEqual((disks / name / 'nvram.fd').read_bytes(), (source / 'nvram.fd').read_bytes()) |
| 104 | first = json.loads((disks / 'first' / 'access.json').read_text()) |
| 105 | second = json.loads((disks / 'second' / 'access.json').read_text()) |
| 106 | self.assertNotEqual(first['password'], second['password']) |
| 107 | self.assertEqual(first['username'], 'first') |
| 108 | self.assertEqual(second['username'], 'second') |
| 109 | |
| 110 | def test_windows_setup_closes_milestone_files(self): |
| 111 | for stage in ['ready', 'failed', 'restarting', 'personalizing']: |
| 112 | def reply(action, name, payload, *args): |
| 113 | command = json.loads(payload) |
| 114 | if command['execute'] == 'guest-file-close': |
| 115 | self.assertEqual(command['arguments']['handle'], 7) |
| 116 | return '{"return": {}}' |
| 117 | if command['arguments']['path'].endswith('\\' + stage): |
| 118 | return '{"return": 7}' |
| 119 | raise vms.subprocess.CalledProcessError(1, 'virsh') |
| 120 | with self.subTest(stage=stage), patch.object(vms, 'virsh', side_effect=reply) as call: |
| 121 | self.assertEqual(vms.windows_setup('fixture'), stage) |
| 122 | self.assertEqual(json.loads(call.call_args.args[2])['execute'], 'guest-file-close') |
| 123 | with patch.object(vms, 'virsh', side_effect=vms.subprocess.CalledProcessError(1, 'virsh')): |
| 124 | self.assertEqual(vms.windows_setup('fixture'), 'starting') |
| 125 | |
| 126 | def test_guest_channel_uses_libvirts_truncated_domain_name(self): |
| 127 | name = 'window-stream-win11-test' |
| 128 | path = f'/run/libvirt/qemu/channel/175-{name[:20]}/{vms.GUEST_CHANNEL}' |
| 129 | xml = f'<domain id="175"><devices><channel type="unix"><source mode="bind" path="{path}"/><target name="{vms.GUEST_CHANNEL}"/></channel></devices></domain>' |
| 130 | with patch.object(sys, 'argv', ['vms.py', 'guest', json.dumps({'name': name})]), \ |
| 131 | patch.object(vms, 'virsh', side_effect=lambda action, *_: xml if action == 'dumpxml' else 'running'): |
| 132 | self.assertEqual(vms.main(), {'path': path}) |
| 133 | for invalid in ['/tmp/display.sock', path.replace('175-', '176-'), path.replace(name[:20], name)]: |
| 134 | with self.subTest(path=invalid), patch.object(vms, 'virsh', side_effect=lambda action, *_: xml.replace(path, invalid) if action == 'dumpxml' else 'running'): |
| 135 | with self.assertRaises(ValueError): |
| 136 | vms.main() |
| 137 | |
| 138 | def test_nested_installers_are_separate_from_prepared_guests(self): |
| 139 | with tempfile.TemporaryDirectory() as temporary: |
| 140 | root = Path(temporary).resolve() |
| 141 | installers = root / 'Install Disks' |
| 142 | installers.mkdir() |
| 143 | (installers / 'ubuntu-amd64.ISO').write_bytes(b'installer') |
| 144 | (installers / 'ubuntu-arm64.iso').write_bytes(b'installer') |
| 145 | (installers / 'not-a-preset.qcow2').write_bytes(b'disk') |
| 146 | (root / 'restore.ipsw').write_bytes(b'restore') |
| 147 | (installers / 'escaped.iso').symlink_to(root / 'restore.ipsw') |
| 148 | presets = root / 'Presets' |
| 149 | presets.mkdir() |
| 150 | (presets / 'ignored.iso').write_bytes(b'not an installer') |
| 151 | with patch.multiple(vms, IMAGES=root, UPLOADS=installers, PRESETS=presets): |
| 152 | library = vms.library() |
| 153 | self.assertEqual(len(library['installers']), 2) |
| 154 | self.assertEqual(library['presets'], []) |
| 155 | self.assertEqual({item['arch'] for item in library['installers']}, {'x86_64', 'aarch64'}) |
| 156 | self.assertTrue(all(item['volume'].startswith('media:Install Disks/') for item in library['installers'])) |
| 157 | |
| 158 | def test_image_ids_and_parent_symlinks_cannot_escape(self): |
| 159 | for identity in ['../secret.iso', 'media:Install Disks/../../secret.iso', '/etc/shadow', 'upload:/secret.iso']: |
| 160 | with self.subTest(identity=identity), self.assertRaises(ValueError): |
| 161 | vms.validate_image_id(identity) |
| 162 | with tempfile.TemporaryDirectory() as temporary: |
| 163 | root = Path(temporary).resolve() |
| 164 | (root / 'outside').mkdir() |
| 165 | (root / 'outside' / 'secret.iso').write_bytes(b'secret') |
| 166 | (root / 'inside').symlink_to(root / 'outside', target_is_directory=True) |
| 167 | with self.assertRaises(OSError): |
| 168 | vms.open_regular(root / 'inside' / 'secret.iso') |
| 169 | |
| 170 | def test_modern_create_rejects_incomplete_or_arbitrary_hardware(self): |
| 171 | payload = {'name': 'ubuntu', 'owner': 'fixture-user', 'username': 'fixture', 'description': '', 'image': 'media:Install Disks/ubuntu.iso', |
| 172 | 'mode': 'iso', 'firmware': 'uefi', 'platform': 'linux', 'vcpus': 2, |
| 173 | 'memory': 2**30, 'disk': 20 * 2**30, 'autostart': False, 'start': False} |
| 174 | with patch.object(vms, 'node', return_value={'cpus': 8, 'memory': 16 * 2**30}): |
| 175 | vms.validate('create', payload) |
| 176 | for changes in [{'mode': 'xml'}, {'firmware': '/etc/shadow'}, {'vcpus': True}, {'image': '../escape'}, {'argv': ['sh']}]: |
| 177 | with self.subTest(changes=changes), self.assertRaises(ValueError): |
| 178 | vms.validate('create', {**payload, **changes}) |
| 179 | with self.assertRaises(ValueError): |
| 180 | vms.validate('create', {'name': 'ubuntu'}) |
| 181 | |
| 182 | def test_known_installers_choose_their_tested_hardware(self): |
| 183 | linux = {'platform': 'linux', 'firmware': 'uefi'} |
| 184 | windows = {'platform': 'windows', 'firmware': 'uefi'} |
| 185 | cases = { |
| 186 | 'Windows XP Professional SP3 x86.iso': 'windows-legacy-ide', |
| 187 | 'Windows Vista SP2 x64.iso': 'windows-legacy-ide', |
| 188 | 'Windows 7 Professional.ISO': 'windows-legacy-ide', |
| 189 | 'Windows 8 RTM x64.iso': 'windows-q35-bios', |
| 190 | 'Windows 10 22H2 English x64.iso': 'windows-q35-uefi', |
| 191 | 'Windows 11 26H2 English x64.iso': 'windows-q35-secure', |
| 192 | 'Windows 11 26H2 English arm64.iso': 'windows-aarch64-nvme', |
| 193 | 'Fedora-Workstation-Live-44-1.7.aarch64.iso': 'linux-aarch64-virtio', |
| 194 | } |
| 195 | for name, expected in cases.items(): |
| 196 | with self.subTest(name=name): |
| 197 | spec = windows if name.startswith('Windows') else linux |
| 198 | self.assertEqual(vms.installer_profile(Path(name), spec), expected) |
| 199 | self.assertEqual(vms.profile('linux-aarch64-virtio')['video'], 'virtio') |
| 200 | self.assertEqual(vms.profile('linux-aarch64-virtio')['keyboard'], 'usb') |
| 201 | self.assertEqual(vms.profile('linux-aarch64-virtio')['serial'], 'ttyAMA0') |
| 202 | self.assertEqual(vms.profile('windows-q35-secure')['cpu_mode'], 'host-passthrough') |
| 203 | self.assertEqual(vms.profile('windows-q35-secure')['clock'], 'utc') |
| 204 | |
| 205 | def test_existing_presets_receive_a_safe_profile(self): |
| 206 | with tempfile.TemporaryDirectory() as temporary: |
| 207 | presets = Path(temporary).resolve() |
| 208 | directory = presets / 'ubuntu' |
| 209 | directory.mkdir() |
| 210 | (directory / 'preset.json').write_text(json.dumps({ |
| 211 | 'id': 'ubuntu', 'os': 'Ubuntu', 'description': '', 'firmware': 'uefi', |
| 212 | 'platform': 'linux', 'createdAt': 0, 'recommended': {'vcpus': 2, 'memory': 1, 'disk': 1}, |
| 213 | })) |
| 214 | (directory / 'disk.qcow2').write_bytes(b'fixture') |
| 215 | details = {'format': 'qcow2', 'virtual-size': 123, 'format-specific': {'data': {}}} |
| 216 | with patch.object(vms, 'PRESETS', presets), patch.object(vms, 'command', return_value=json.dumps(details)): |
| 217 | preset = vms.read_preset('ubuntu') |
| 218 | self.assertEqual(preset['hardwareProfile'], 'linux-x86-virtio') |
| 219 | self.assertEqual(preset['arch'], 'x86_64') |
| 220 | |
| 221 | def test_windows_seed_has_only_validated_clone_identity(self): |
| 222 | with tempfile.TemporaryDirectory() as temporary: |
| 223 | directory = Path(temporary) |
| 224 | calls = [] |
| 225 | with patch.object(vms, 'command', side_effect=lambda *args, **kwargs: calls.append(args) or ''), \ |
| 226 | patch.object(vms.secrets, 'token_urlsafe', return_value='generated-password'), \ |
| 227 | patch.object(vms.secrets, 'token_hex', return_value='1234abcd'): |
| 228 | vms.windows_seed(directory, 'snow') |
| 229 | self.assertEqual(json.loads((directory / 'access.json').read_text()), { |
| 230 | 'username': 'snow', 'password': 'generated-password', 'hostname': 'sgvm-1234abcd', |
| 231 | }) |
| 232 | self.assertEqual(oct((directory / 'access.json').stat().st_mode & 0o777), '0o600') |
| 233 | self.assertEqual(calls[0][0:7], ('genisoimage', '-quiet', '-output', str(directory / 'seed.iso'), '-volid', 'SNOWGLOBE', '-joliet')) |
| 234 | self.assertEqual(Path(calls[0][-1]).name, 'SNOWGLOB.INI') |
| 235 | with self.assertRaisesRegex(ValueError, 'Windows'): |
| 236 | vms.windows_seed(directory, 'bad\\nname') |
| 237 | |
| 238 | def test_one_boot_windows_seed_does_not_claim_a_new_computer_name(self): |
| 239 | with tempfile.TemporaryDirectory() as temporary: |
| 240 | directory = Path(temporary) |
| 241 | seeds = [] |
| 242 | with patch.object(vms, 'command', side_effect=lambda *args, **kwargs: seeds.append(Path(args[-1]).read_text()) or ''): |
| 243 | vms.windows_seed(directory, 'fixture', rename=False) |
| 244 | self.assertNotIn('HOSTNAME=', seeds[0]) |
| 245 | access = json.loads((directory / 'access.json').read_text()) |
| 246 | self.assertEqual(access['hostname'], '') |
| 247 | self.assertEqual(access['username'], 'fixture') |
| 248 | self.assertGreaterEqual(len(access['password']), 12) |
| 249 | |
| 250 | def test_nixos_seed_uses_mutable_gdm_path_and_native_sshd(self): |
| 251 | with tempfile.TemporaryDirectory() as temporary: |
| 252 | directory = Path(temporary) |
| 253 | captured = {} |
| 254 | def image(*args, **kwargs): |
| 255 | captured['config'] = json.loads(Path(args[-2]).read_text().removeprefix('#cloud-config\n')) |
| 256 | return '' |
| 257 | with patch.object(vms, 'command', side_effect=image), \ |
| 258 | patch.object(vms.subprocess, 'run', return_value=SimpleNamespace(stdout='$6$hash\n')), \ |
| 259 | patch.object(vms.secrets, 'token_urlsafe', return_value='generated-password'), \ |
| 260 | patch.object(vms.secrets, 'token_hex', side_effect=['1234abcd', 'instance']): |
| 261 | vms.linux_seed(directory, 'snow', 'NixOS', 'ttyAMA0') |
| 262 | config = captured['config'] |
| 263 | self.assertEqual(config['bootcmd'][0], ['rm', '-f', '/etc/gdm/custom.conf']) |
| 264 | self.assertIn('/run/current-system/sw/bin/getent', config['bootcmd'][1][-1]) |
| 265 | self.assertEqual(config['write_files'][:2], [{ |
| 266 | 'path': '/etc/gdm/custom.conf', 'content': '[daemon]\nAutomaticLoginEnable=true\nAutomaticLogin=snow\n', |
| 267 | }, { |
| 268 | 'path': '/var/lib/snowglobe/hostname', |
| 269 | 'content': 'snowglobe-vm-1234abcd\n', |
| 270 | }]) |
| 271 | self.assertEqual(config['runcmd'][0][-1], 'sshd') |
| 272 | self.assertEqual(config['runcmd'][1][-1], 'serial-getty@ttyAMA0.service') |
| 273 | |
| 274 | def test_console_cannot_choose_an_arbitrary_network_target(self): |
| 275 | xml = "<domain><uuid>fixture-vm</uuid><devices><graphics type='vnc' listen='127.0.0.1' port='5901'/></devices></domain>" |
| 276 | def virsh(*args, **kwargs): |
| 277 | return 'running' if args[0] == 'domstate' else xml |
| 278 | with patch.object(vms, 'virsh', side_effect=virsh): |
| 279 | self.assertEqual(vms.console_target('ubuntu'), {'port': 5901, 'uuid': 'fixture-vm'}) |
| 280 | for address in ['0.0.0.0', '192.168.0.1', 'localhost']: |
| 281 | xml = xml.replace('127.0.0.1', address) |
| 282 | with self.assertRaises(ValueError): |
| 283 | vms.console_target('ubuntu') |
| 284 | xml = xml.replace(address, '127.0.0.1') |
| 285 | xml = xml.replace('5901', '22') |
| 286 | with self.assertRaises(ValueError): |
| 287 | vms.console_target('ubuntu') |
| 288 | |
| 289 | def test_running_guests_cannot_be_published_as_presets(self): |
| 290 | with patch.object(vms, 'virsh', return_value='running'): |
| 291 | with self.assertRaisesRegex(ValueError, 'Shut down'): |
| 292 | vms.save_preset({'name': 'ubuntu'}) |
| 293 | |
| 294 | def test_screen_waits_for_startup_without_following_a_replacement_vm(self): |
| 295 | with socket.socket() as reservation: |
| 296 | reservation.bind(('127.0.0.1', 0)) |
| 297 | port = reservation.getsockname()[1] |
| 298 | with socket.socket() as display: |
| 299 | retry, listening = threading.Event(), threading.Event() |
| 300 | errors = [] |
| 301 | class StartingHost: |
| 302 | calls = 0 |
| 303 | def handle(self, request): |
| 304 | self.calls += 1 |
| 305 | if self.calls == 2: |
| 306 | retry.set() |
| 307 | if not listening.wait(2): |
| 308 | raise TimeoutError('Display did not start') |
| 309 | return {'port': port, 'uuid': 'original-vm'} |
| 310 | target = StartingHost() |
| 311 | client, server = socket.socketpair() |
| 312 | client.settimeout(2) |
| 313 | def run(): |
| 314 | with server: |
| 315 | try: |
| 316 | host.stream_console(server, target, {'operation': 'vm.console'}) |
| 317 | except Exception as error: |
| 318 | errors.append(error) |
| 319 | worker = threading.Thread(target=run) |
| 320 | worker.start() |
| 321 | try: |
| 322 | self.assertTrue(retry.wait(2)) |
| 323 | display.bind(('127.0.0.1', port)) |
| 324 | display.listen() |
| 325 | display.settimeout(2) |
| 326 | listening.set() |
| 327 | with display.accept()[0] as guest: |
| 328 | length = struct.unpack('!I', client.recv(4))[0] |
| 329 | self.assertEqual(json.loads(client.recv(length)), {'value': None}) |
| 330 | guest.sendall(b'RFB 003.008\n') |
| 331 | self.assertEqual(client.recv(12), b'RFB 003.008\n') |
| 332 | finally: |
| 333 | listening.set() |
| 334 | client.close() |
| 335 | worker.join(2) |
| 336 | self.assertFalse(worker.is_alive()) |
| 337 | self.assertEqual(errors, []) |
| 338 | with patch.object(host.socket, 'create_connection', side_effect=ConnectionRefusedError) as connect: |
| 339 | target = StartingHost() |
| 340 | with patch.object(target, 'handle', side_effect=[{'port': port, 'uuid': 'original-vm'}, {'port': port, 'uuid': 'replacement-vm'}]): |
| 341 | with self.assertRaisesRegex(host.Rejected, 'VM changed'): |
| 342 | host.stream_console(None, target, {'operation': 'vm.console'}) |
| 343 | self.assertEqual(connect.call_count, 1) |
| 344 | |
| 345 | def test_serial_target_cannot_choose_a_host_file(self): |
| 346 | xml = "<domain><devices><console type='pty'><source path='/dev/pts/3'/><target type='serial'/></console></devices></domain>" |
| 347 | def virsh(*args, **kwargs): |
| 348 | return 'running' if args[0] == 'domstate' else xml |
| 349 | with patch.object(sys, 'argv', ['vms.py', 'serial', json.dumps({'name': 'ubuntu'})]), patch.object(vms, 'virsh', side_effect=virsh): |
| 350 | self.assertEqual(vms.main(), {'path': '/dev/pts/3'}) |
| 351 | for path in ['/etc/shadow', '/dev/null', '/dev/pts/../tty', '/dev/pts/3/link']: |
| 352 | xml = xml.replace('/dev/pts/3', path) |
| 353 | with self.assertRaises(ValueError): |
| 354 | vms.main() |
| 355 | xml = xml.replace(path, '/dev/pts/3') |
| 356 | |
| 357 | def test_serial_transport_preserves_control_c_in_both_directions(self): |
| 358 | master, slave = pty.openpty() |
| 359 | client, server = socket.socketpair() |
| 360 | client.settimeout(2) |
| 361 | errors = [] |
| 362 | class SerialHost: |
| 363 | def handle(self, request): |
| 364 | return {'path': os.ttyname(slave)} |
| 365 | def run(): |
| 366 | with server: |
| 367 | try: |
| 368 | host.stream_console(server, SerialHost(), {'operation': 'vm.serial'}) |
| 369 | except Exception as error: |
| 370 | errors.append(error) |
| 371 | worker = threading.Thread(target=run) |
| 372 | worker.start() |
| 373 | try: |
| 374 | length = struct.unpack('!I', client.recv(4))[0] |
| 375 | self.assertEqual(json.loads(client.recv(length)), {'value': None}) |
| 376 | other_client, other_server = socket.socketpair() |
| 377 | with other_client, other_server, self.assertRaisesRegex(host.Rejected, 'already open'): |
| 378 | host.stream_console(other_server, SerialHost(), {'operation': 'vm.serial'}) |
| 379 | client.sendall(b'\x03') |
| 380 | self.assertTrue(select.select([master], [], [], 2)[0]) |
| 381 | self.assertEqual(os.read(master, 100), b'\x03') |
| 382 | os.write(master, b'guest prompt> ') |
| 383 | self.assertEqual(client.recv(100), b'guest prompt> ') |
| 384 | finally: |
| 385 | client.close() |
| 386 | worker.join(2) |
| 387 | os.close(master) |
| 388 | os.close(slave) |
| 389 | self.assertFalse(worker.is_alive()) |
| 390 | self.assertEqual(errors, []) |
| 391 | |
| 392 | def test_upload_stream_is_bounded_atomic_and_cleans_interruption(self): |
| 393 | def response(sock): |
| 394 | length = struct.unpack('!I', sock.recv(4))[0] |
| 395 | data = bytearray() |
| 396 | while len(data) < length: |
| 397 | data.extend(sock.recv(length - len(data))) |
| 398 | return json.loads(data) |
| 399 | with tempfile.TemporaryDirectory() as temporary, patch.object(vms, 'UPLOADS', Path(temporary).resolve()): |
| 400 | for complete in [False, True]: |
| 401 | client, server = socket.socketpair() |
| 402 | errors = [] |
| 403 | def run(): |
| 404 | with server: |
| 405 | try: |
| 406 | host.stream_upload(server, {'operation': 'vm.upload', 'payload': {'volume': 'ubuntu.iso', 'size': 32768}}) |
| 407 | except Exception as error: |
| 408 | errors.append(error) |
| 409 | worker = threading.Thread(target=run) |
| 410 | worker.start() |
| 411 | with client: |
| 412 | self.assertEqual(response(client), {'value': None}) |
| 413 | client.sendall(b'I' * (32768 if complete else 100)) |
| 414 | client.shutdown(socket.SHUT_WR) |
| 415 | if complete: |
| 416 | self.assertEqual(response(client)['value']['volume'], 'upload:ubuntu.iso') |
| 417 | worker.join(2) |
| 418 | self.assertFalse(worker.is_alive()) |
| 419 | if complete: |
| 420 | self.assertEqual((Path(temporary).resolve() / 'ubuntu.iso').read_bytes(), b'I' * 32768) |
| 421 | else: |
| 422 | self.assertTrue(errors) |
| 423 | self.assertEqual(list(Path(temporary).resolve().iterdir()), []) |
| 424 | with self.assertRaises(host.Rejected): |
| 425 | host.stream_upload(None, {'operation': 'vm.upload', 'payload': {'volume': 'ubuntu.iso', 'size': 32768}}) |
| 426 | for filename in ['../ubuntu.iso', '/etc/shadow.iso', 'ubuntu.img']: |
| 427 | with self.assertRaises(ValueError): |
| 428 | vms.validate('upload', {'volume': filename, 'size': 32768}) |
| 429 | |
| 430 | |
| 431 | class PowerControls(unittest.TestCase): |
| 432 | def setUp(self): |
| 433 | temporary = tempfile.TemporaryDirectory() |
| 434 | self.addCleanup(temporary.cleanup) |
| 435 | self.root = Path(temporary.name) |
| 436 | (self.root / 'fixture').mkdir() |
| 437 | patcher = patch.object(vms, 'DISKS', self.root) |
| 438 | patcher.start() |
| 439 | self.addCleanup(patcher.stop) |
| 440 | |
| 441 | def test_force_controls_cancel_the_active_call_without_waiting_for_it(self): |
| 442 | for action in ['reset', 'destroy']: |
| 443 | with self.subTest(action=action), vms.computer_lock('fixture', 'exec') as active: |
| 444 | with patch.object(vms.sys, 'argv', ['vms.py','act',json.dumps({'name':'fixture','action':action})]), patch.object(vms, 'virsh', return_value='') as virsh: |
| 445 | self.assertIsNone(vms.main()) |
| 446 | virsh.assert_called_once_with(action, 'fixture', timeout=15) |
| 447 | with vms.computer_control('fixture') as control: |
| 448 | self.assertEqual(control.read(), active['id']) |
| 449 | self.assertEqual(vms.computer_activity('fixture')['id'], active['id']) |
| 450 | |
| 451 | def test_failed_force_request_keeps_the_cancellation_intent(self): |
| 452 | with vms.computer_lock('fixture', 'exec') as active: |
| 453 | with patch.object(vms.sys, 'argv', ['vms.py','act',json.dumps({'name':'fixture','action':'reset'})]), \ |
| 454 | patch.object(vms, 'virsh', side_effect=vms.subprocess.CalledProcessError(1, 'virsh', stderr='Connection lost')): |
| 455 | with self.assertRaises(vms.subprocess.CalledProcessError): |
| 456 | vms.main() |
| 457 | with vms.computer_control('fixture') as control: |
| 458 | self.assertEqual(control.read(), active['id']) |
| 459 | |
| 460 | def test_graceful_actions_preserve_the_active_command_guard(self): |
| 461 | with vms.computer_lock('fixture', 'exec'), patch.object(vms, 'virsh') as virsh: |
| 462 | for action in ['start', 'shutdown', 'reboot', 'suspend', 'resume']: |
| 463 | with patch.object(vms.sys, 'argv', ['vms.py','act',json.dumps({'name':'fixture','action':action})]): |
| 464 | with self.assertRaises(BlockingIOError): |
| 465 | vms.main() |
| 466 | virsh.assert_not_called() |
| 467 | |
| 468 | class DisposableStorage(unittest.TestCase): |
| 469 | def setUp(self): |
| 470 | temporary = tempfile.TemporaryDirectory() |
| 471 | self.addCleanup(temporary.cleanup) |
| 472 | self.root = Path(temporary.name) |
| 473 | self.metadata = self.root / 'metadata' |
| 474 | self.storage = self.root / 'ssd' |
| 475 | self.metadata.mkdir() |
| 476 | self.storage.mkdir() |
| 477 | for item in [patch.object(vms, 'DISKS', self.metadata), patch.object(vms, 'AI_DISKS', self.storage), |
| 478 | patch.object(Path, 'is_mount', return_value=True)]: |
| 479 | item.start() |
| 480 | self.addCleanup(item.stop) |
| 481 | |
| 482 | def test_failed_creation_never_overwrites_an_existing_ssd_disk(self): |
| 483 | drive = self.storage / 'ai-fixture.qcow2' |
| 484 | drive.write_bytes(b'existing') |
| 485 | spec = {'name': 'ai-fixture', 'image': 'blank', 'mode': 'iso', 'platform': 'linux', |
| 486 | 'firmware': 'bios', 'disk': 2**30} |
| 487 | with patch.object(vms, 'virsh', return_value=''), patch.object(vms, 'command') as command: |
| 488 | with self.assertRaises(FileExistsError): |
| 489 | vms.create(spec, ai=True) |
| 490 | command.assert_not_called() |
| 491 | self.assertEqual(drive.read_bytes(), b'existing') |
| 492 | self.assertFalse((self.metadata / spec['name']).exists()) |
| 493 | |
| 494 | def test_failed_image_creation_removes_only_its_new_ssd_disk(self): |
| 495 | spec = {'name': 'ai-fixture', 'image': 'blank', 'mode': 'iso', 'platform': 'linux', |
| 496 | 'firmware': 'bios', 'disk': 2**30} |
| 497 | foreign = self.storage / 'foreign.qcow2' |
| 498 | foreign.write_bytes(b'preserve') |
| 499 | with patch.object(vms, 'virsh', return_value=''), patch.object(vms, 'command', side_effect=OSError('Disk full')): |
| 500 | with self.assertRaisesRegex(OSError, 'Disk full'): |
| 501 | vms.create(spec, ai=True) |
| 502 | self.assertEqual(foreign.read_bytes(), b'preserve') |
| 503 | self.assertFalse((self.storage / 'ai-fixture.qcow2').exists()) |
| 504 | self.assertEqual(list(self.metadata.iterdir()), []) |
| 505 | |
| 506 | def test_failed_expiry_write_does_not_leave_a_guest_directory_or_ssd_disk(self): |
| 507 | spec = {'name': 'ai-fixture', 'image': 'blank', 'mode': 'iso', 'platform': 'linux', |
| 508 | 'firmware': 'bios', 'disk': 2**30} |
| 509 | with patch.object(vms, 'virsh', return_value=''), patch.object(Path, 'write_text', side_effect=OSError('Disk full')): |
| 510 | with self.assertRaisesRegex(OSError, 'Disk full'): |
| 511 | vms.create(spec, ai=True) |
| 512 | self.assertEqual(list(self.metadata.iterdir()), []) |
| 513 | self.assertEqual(list(self.storage.iterdir()), []) |
| 514 | |
| 515 | def test_uncertain_definition_preserves_the_ssd_disk_and_recovery_metadata(self): |
| 516 | defined = False |
| 517 | def virsh(action, *args): |
| 518 | nonlocal defined |
| 519 | if action == 'list': |
| 520 | return 'ai-fixture' if defined else '' |
| 521 | if action == 'define': |
| 522 | defined = True |
| 523 | raise TimeoutError('Definition response lost') |
| 524 | return '' |
| 525 | spec = {'name': 'ai-fixture', 'description': '', 'image': 'blank', 'mode': 'iso', |
| 526 | 'platform': 'linux', 'firmware': 'bios', 'disk': 2**30, 'memory': 2**29, |
| 527 | 'vcpus': 1, 'owner': 'fixture', 'autostart': False, 'start': False} |
| 528 | with patch.object(vms, 'virsh', side_effect=virsh), patch.object(vms, 'command', return_value=''): |
| 529 | with self.assertRaisesRegex(TimeoutError, 'response lost'): |
| 530 | vms.create(spec, ai=True) |
| 531 | self.assertTrue((self.storage / 'ai-fixture.qcow2').exists()) |
| 532 | self.assertTrue((self.metadata / 'ai-fixture' / 'ai.json').exists()) |
| 533 | source = vms.ET.parse(self.metadata / 'ai-fixture' / 'domain.xml').find('./devices/disk/source') |
| 534 | self.assertEqual(source.get('file'), str(self.storage / 'ai-fixture.qcow2')) |
| 535 | |
| 536 | def test_remove_preserves_disks_when_undefine_is_uncertain(self): |
| 537 | directory = self.metadata / 'ai-fixture' |
| 538 | directory.mkdir() |
| 539 | (directory / 'ai.json').write_text('{"expiresAt":1}') |
| 540 | drive = self.storage / 'ai-fixture.qcow2' |
| 541 | drive.write_bytes(b'guest') |
| 542 | def virsh(action, *args): |
| 543 | if action == 'undefine': |
| 544 | raise TimeoutError('Undefine response lost') |
| 545 | return {'list': 'ai-fixture', 'domstate': 'shut off', |
| 546 | 'dumpxml': f'<domain><devices><disk device="disk"><source file="{drive}"/></disk></devices></domain>'}[action] |
| 547 | with patch.object(vms, 'virsh', side_effect=virsh): |
| 548 | with self.assertRaises(TimeoutError): |
| 549 | vms.remove({'name': 'ai-fixture', 'disks': True}) |
| 550 | self.assertEqual(drive.read_bytes(), b'guest') |
| 551 | self.assertTrue(directory.is_dir()) |
| 552 | with patch.object(vms, 'virsh', side_effect=lambda action, *args: '' if action == 'undefine' else virsh(action, *args)): |
| 553 | vms.remove({'name': 'ai-fixture', 'disks': True}) |
| 554 | self.assertFalse(directory.exists()) |
| 555 | self.assertFalse(drive.exists()) |
| 556 | |
| 557 | def test_legacy_guest_deletion_does_not_touch_a_same_named_ssd_file(self): |
| 558 | directory = self.metadata / 'ai-fixture' |
| 559 | directory.mkdir() |
| 560 | (directory / 'ai.json').write_text('{"expiresAt":1}') |
| 561 | (directory / 'disk.qcow2').write_bytes(b'legacy') |
| 562 | foreign = self.storage / 'ai-fixture.qcow2' |
| 563 | foreign.write_bytes(b'foreign') |
| 564 | replies = {'list': 'ai-fixture', 'domstate': 'shut off', 'undefine': '', |
| 565 | 'dumpxml': f'<domain><devices><disk device="disk"><source file="{directory / "disk.qcow2"}"/></disk></devices></domain>'} |
| 566 | with patch.object(vms, 'virsh', side_effect=lambda action, *args: replies[action]), patch.object(Path, 'is_mount', return_value=False): |
| 567 | vms.remove({'name': 'ai-fixture', 'disks': True}) |
| 568 | self.assertEqual(foreign.read_bytes(), b'foreign') |
| 569 | self.assertFalse(directory.exists()) |
| 570 | |
| 571 | def test_missing_ssd_mount_fails_before_create_or_delete_mutations(self): |
| 572 | directory = self.metadata / 'ai-fixture' |
| 573 | with patch.object(Path, 'is_mount', return_value=False), patch.object(vms, 'virsh', return_value='') as virsh: |
| 574 | with self.assertRaisesRegex(ValueError, 'storage is unavailable'): |
| 575 | vms.create({'name': 'ai-fixture', 'image': 'blank', 'mode': 'iso', 'platform': 'linux', |
| 576 | 'firmware': 'bios', 'disk': 2**30}, ai=True) |
| 577 | self.assertFalse(directory.exists()) |
| 578 | directory.mkdir() |
| 579 | (directory / 'ai.json').write_text('{"expiresAt":1}') |
| 580 | with self.assertRaisesRegex(ValueError, 'storage is unavailable'): |
| 581 | vms.remove({'name': 'ai-fixture', 'disks': True}, missing_ok=True) |
| 582 | self.assertTrue(directory.is_dir()) |
| 583 | self.assertTrue(all(call.args[0] == 'list' for call in virsh.call_args_list)) |
| 584 | |
| 585 | |
| 586 | GPU_GUEST = """<domain><devices> |
| 587 | <hostdev mode="subsystem" type="pci" managed="yes"><source><address domain="0x0000" bus="0x09" slot="0x00" function="0x1"/></source></hostdev> |
| 588 | <hostdev mode="subsystem" type="pci" managed="yes"><source><address domain="0x0000" bus="0x09" slot="0x00" function="0x0"/></source></hostdev> |
| 589 | </devices></domain>""" |
| 590 | |
| 591 | |
| 592 | class GpuSwitch(unittest.TestCase): |
| 593 | """The switch against a fake libvirt, Nomad and sysfs, so the real GPU never moves.""" |
| 594 | |
| 595 | def setUp(self): |
| 596 | temporary = tempfile.TemporaryDirectory() |
| 597 | self.addCleanup(temporary.cleanup) |
| 598 | root = Path(temporary.name) |
| 599 | for address, vendor, kind in [('0000:09:00.0', '0x10de', '0x030000'), ('0000:09:00.1', '0x10de', '0x040300'), |
| 600 | ('0000:0a:00.0', '0x1002', '0x030000')]: |
| 601 | (root / 'pci' / address).mkdir(parents=True) |
| 602 | (root / 'pci' / address / 'vendor').write_text(vendor + '\n') |
| 603 | (root / 'pci' / address / 'class').write_text(kind + '\n') |
| 604 | (root / 'nomad.token').write_text('token\n') |
| 605 | self.domains = {'testbox': '<domain><devices/></domain>', 'win11-gaming': GPU_GUEST} |
| 606 | self.state, self.start_fails, self.shuts_down = 'shut off', False, True |
| 607 | gpu_job = lambda stopped: {'Stop': stopped, 'TaskGroups': [{'Tasks': [{'Config': {'devices': ['/dev/nvidia0', '/dev/nvidiactl']}}]}]} |
| 608 | self.jobs = {'local-ai': gpu_job(False), 'fusion': gpu_job(True), |
| 609 | 'jellyfin': {'Stop': False, 'TaskGroups': [{'Tasks': [{'Config': {'image': 'jellyfin'}}, {'Config': None}]}]}} |
| 610 | self.polls = {} |
| 611 | self.calls = [] |
| 612 | |
| 613 | def virsh(*args, timeout=None): |
| 614 | self.calls.append(('virsh', *args)) |
| 615 | if args[0] == 'list': |
| 616 | return '\n'.join(self.domains) + '\n' |
| 617 | if args[0] == 'dumpxml': |
| 618 | return self.domains[args[-1]] |
| 619 | if args[0] == 'domstate': |
| 620 | return self.state |
| 621 | if args[0] == 'start': |
| 622 | if self.start_fails: |
| 623 | raise vms.subprocess.CalledProcessError(1, 'virsh', stderr='device is busy') |
| 624 | self.state = 'running' |
| 625 | if args[0] == 'shutdown' and self.shuts_down: |
| 626 | self.state = 'shut off' |
| 627 | return '' |
| 628 | |
| 629 | def run(args, **kwargs): |
| 630 | self.calls.append(tuple(args)) |
| 631 | output = '' |
| 632 | if args[0] == 'nomad': |
| 633 | self.assertEqual(kwargs['env']['NOMAD_TOKEN'], 'token') |
| 634 | verb, job = args[2], args[-1] |
| 635 | if verb == 'status': |
| 636 | output = json.dumps([{'Summary': {'JobID': name}} for name in self.jobs]) |
| 637 | elif verb == 'inspect': |
| 638 | output = json.dumps(self.jobs[job]) |
| 639 | elif verb == 'stop': |
| 640 | self.jobs[job]['Stop'] = True |
| 641 | elif verb == 'allocs': |
| 642 | # A stopped job's allocation keeps running for one more poll. |
| 643 | self.polls[job] = self.polls.get(job, 0) + 1 |
| 644 | stopped = self.jobs[job]['Stop'] and self.polls[job] > 1 |
| 645 | output = json.dumps([{'ClientStatus': 'complete'}, {'ClientStatus': 'complete' if stopped else 'running'}]) |
| 646 | return SimpleNamespace(stdout=output, returncode=0) |
| 647 | |
| 648 | release = SimpleNamespace(STATE=root, current_release=lambda: 'a' * 16, check_release=lambda version: root / version) |
| 649 | clock = iter(range(0, 10**6, 50)) |
| 650 | for context in [patch.object(vms, 'PCI', root / 'pci'), patch.object(vms, 'virsh', side_effect=virsh), |
| 651 | patch.object(vms.subprocess, 'run', side_effect=run), patch.object(vms.time, 'sleep'), |
| 652 | patch.object(vms.time, 'monotonic', side_effect=lambda: next(clock)), |
| 653 | patch.object(vms, 'import_module', side_effect=lambda name: release if name == 'release' else importlib.import_module(name))]: |
| 654 | context.start() |
| 655 | self.addCleanup(context.stop) |
| 656 | self.deploy = lambda job: (vms.sys.executable, str(root / ('a' * 16) / 'tools/snowglobe.py'), 'deploy', job) |
| 657 | |
| 658 | def test_the_gpu_guest_is_the_one_passing_through_an_nvidia_display(self): |
| 659 | self.assertTrue(vms.passes_gpu(vms.ET.fromstring(GPU_GUEST))) |
| 660 | for function, bus in [('0x1', '0x09'), ('0x0', '0x0a'), ('0x0', '0x0b')]: |
| 661 | other = GPU_GUEST.split('<hostdev', 2)[0] + f'<hostdev type="pci"><source><address domain="0x0000" bus="{bus}" slot="0x00" function="{function}"/></source></hostdev></devices></domain>' |
| 662 | with self.subTest(bus=bus, function=function): |
| 663 | self.assertFalse(vms.passes_gpu(vms.ET.fromstring(other))) |
| 664 | self.assertEqual(vms.gpu_guest(), 'win11-gaming') |
| 665 | del self.domains['win11-gaming'] |
| 666 | self.assertIsNone(vms.gpu_guest()) |
| 667 | |
| 668 | def test_games_stops_only_gpu_jobs_and_waits_for_them_before_starting_the_guest(self): |
| 669 | vms.switch_gpu('games') |
| 670 | self.assertEqual(self.state, 'running') |
| 671 | stop = self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai')) |
| 672 | start = self.calls.index(('virsh', 'start', 'win11-gaming')) |
| 673 | self.assertLess(stop, start) |
| 674 | self.assertEqual(self.polls['local-ai'], 2) |
| 675 | self.assertNotIn(('nomad', 'job', 'stop', '-yes', 'jellyfin'), self.calls) |
| 676 | self.assertNotIn(('nomad', 'job', 'stop', '-yes', 'fusion'), self.calls) |
| 677 | self.assertFalse(any(call[0] == vms.sys.executable for call in self.calls)) |
| 678 | |
| 679 | def test_a_guest_that_cannot_take_the_gpu_gives_it_back_to_the_service_that_had_it(self): |
| 680 | self.start_fails = True |
| 681 | with self.assertRaisesRegex(ValueError, "win11-gaming couldn't take the GPU. local-ai has it again."): |
| 682 | vms.switch_gpu('games') |
| 683 | self.assertLess(self.calls.index(('virsh', 'start', 'win11-gaming')), self.calls.index(self.deploy('local-ai'))) |
| 684 | self.assertNotIn(self.deploy('fusion'), self.calls) |
| 685 | |
| 686 | def test_a_service_takes_the_gpu_from_another_service(self): |
| 687 | vms.switch_gpu('fusion') |
| 688 | self.assertLess(self.calls.index(('nomad', 'job', 'stop', '-yes', 'local-ai')), self.calls.index(self.deploy('fusion'))) |
| 689 | self.assertEqual(self.polls['local-ai'], 2) |
| 690 | self.assertNotIn(('virsh', 'shutdown', 'win11-gaming'), self.calls) |
| 691 | |
| 692 | def test_a_service_shuts_the_guest_down_before_deploying(self): |
| 693 | self.state = 'running' |
| 694 | self.jobs['local-ai']['Stop'] = True |
| 695 | vms.switch_gpu('local-ai') |
| 696 | self.assertLess(self.calls.index(('virsh', 'shutdown', 'win11-gaming')), self.calls.index(self.deploy('local-ai'))) |
| 697 | self.assertFalse(any(call[:3] == ('nomad', 'job', 'stop') for call in self.calls)) |
| 698 | |
| 699 | def test_a_guest_that_wont_shut_down_keeps_the_gpu(self): |
| 700 | self.state, self.shuts_down = 'running', False |
| 701 | self.jobs['local-ai']['Stop'] = True |
| 702 | with self.assertRaisesRegex(ValueError, "didn't shut down"): |
| 703 | vms.switch_gpu('fusion') |
| 704 | self.assertFalse(any(call[0] == vms.sys.executable for call in self.calls)) |
| 705 | |
| 706 | def test_only_gpu_sides_switch_and_only_away_from_the_holder(self): |
| 707 | for side, message in [('jellyfin', "jellyfin doesn't use the GPU"), ('local-ai', 'local-ai already has the GPU')]: |
| 708 | with self.subTest(side=side), self.assertRaisesRegex(ValueError, message): |
| 709 | vms.switch_gpu(side) |
| 710 | self.state = 'running' |
| 711 | self.jobs['local-ai']['Stop'] = True |
| 712 | with self.assertRaisesRegex(ValueError, 'win11-gaming already has the GPU'): |
| 713 | vms.switch_gpu('games') |
| 714 | del self.domains['win11-gaming'] |
| 715 | with self.assertRaisesRegex(ValueError, 'No VM uses the GPU'): |
| 716 | vms.switch_gpu('games') |
| 717 | self.assertFalse(any(call[0] in {vms.sys.executable} or call[:3] == ('nomad', 'job', 'stop') or call[:2] == ('virsh', 'start') |
| 718 | for call in self.calls)) |
| 719 | |
| 720 | def test_the_holder_is_the_running_guest_else_the_running_gpu_job(self): |
| 721 | import snowglobe |
| 722 | services = [{'containers': {'app': {'devices': ['/dev/nvidia0']}}}, {'containers': {'app': {'devices': []}}}] |
| 723 | self.assertEqual([snowglobe.gpu(item) for item in services], [True, False]) |
| 724 | self.assertEqual(snowglobe.gpu_holder(services), 'local-ai') |
| 725 | self.jobs['local-ai']['Stop'] = True |
| 726 | self.assertIsNone(snowglobe.gpu_holder(services)) |
| 727 | self.state = 'running' |
| 728 | self.assertEqual(snowglobe.gpu_holder(services), 'win11-gaming') |
| 729 | self.calls.clear() |
| 730 | self.assertIsNone(snowglobe.gpu_holder(services[1:])) |
| 731 | self.assertEqual(self.calls, []) |
| 732 | |
| 733 | def test_a_stopped_registration_parses_the_job_and_submits_it_stopped(self): |
| 734 | import snowglobe |
| 735 | submitted = [] |
| 736 | |
| 737 | def command(*args, capture=False): |
| 738 | if '-output' in args: |
| 739 | return SimpleNamespace(stdout=json.dumps({'Job': {'ID': 'fusion'}})) |
| 740 | submitted.append((args, json.loads(Path(args[-1]).read_text()))) |
| 741 | |
| 742 | with patch.object(snowglobe, 'render', return_value='job "fusion" {}'), patch.object(snowglobe, 'command', side_effect=command): |
| 743 | snowglobe.submit({'containers': {'app': {}}}, 'run', {}, stopped=True) |
| 744 | self.assertEqual([(args[:5], job) for args, job in submitted], |
| 745 | [(('nomad', 'job', 'run', '-detach', '-json'), {'Job': {'ID': 'fusion', 'Stop': True}})]) |
| 746 | |
| 747 | if __name__ == '__main__': |
| 748 | unittest.main() |