-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.py
1310 lines (1040 loc) · 40.3 KB
/
update.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import abc
import argparse
import contextlib
from dataclasses import dataclass
import datetime
import errno
import fcntl
import glob
import json
import logging
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import xml.etree.ElementTree as ET
def log_and_call(cmdline, method=subprocess.check_call, **kwargs):
logging.debug('Running %s', cmdline)
return method(cmdline, **kwargs)
def log_and_output(cmdline, **kwargs):
return log_and_call(cmdline, method=subprocess.check_output, text=True,
**kwargs)
def ssh(host, command, output=False, options=None, **kwargs):
cmdline = ['ssh']
if options is not None:
cmdline.extend(options)
cmdline.extend([host, command])
if output:
return log_and_output(cmdline, **kwargs)
else:
return log_and_call(cmdline, method=subprocess.call, **kwargs)
class Timeout(Exception):
pass
def wait_for(condition, timeout, step):
start_time = time.time()
while time.time() - start_time < timeout:
if condition():
return True
time.sleep(step)
raise Timeout(f'Failed to wait {timeout} seconds for {condition}')
@contextlib.contextmanager
def transact(prepare=None, final=None, commit=None, rollback=None):
assert final is None or (commit is None and rollback is None), (
'final action must only be present with no commit and rollback'
)
rv = None
if prepare is not None:
prepare_msg, prepare_fn = prepare
if prepare_msg is not None:
logging.info(prepare_msg)
rv = prepare_fn()
try:
yield rv
except BaseException as e:
if any((final, rollback)):
rollback_msg, rollback_fn = next(filter(None, (final, rollback)))
if rollback_msg:
logging.warning(rollback_msg)
try:
rollback_fn((rv, e))
except Exception:
logging.exception('Exception while %s', rollback_msg)
raise
else:
if any((final, commit)):
commit_msg, commit_fn = next(filter(None, (final, commit)))
if commit_msg:
logging.info(commit_msg)
try:
commit_fn((rv, None))
except Exception:
logging.exception('Exception while %s', commit_msg)
def no_dpkg_locks(host):
return ssh(host, '! fuser /var/lib/dpkg/lock') == 0
def shutdown(host):
logging.info('Waiting for no dpkg locks on %s', host)
wait_for(lambda: no_dpkg_locks(host), timeout=900, step=10)
logging.info('Shutting down %s', host)
ssh(host, 'shutdown now')
def reboot(host):
logging.info('Rebooting %s', host)
ssh(host, 'reboot')
def is_accessible(host):
logging.info('Checking if %s is accessible', host)
return ssh(host, 'id', options=('-o', 'ConnectTimeout=1'),
stdout=subprocess.PIPE) == 0
@dataclass(frozen=True)
class DiskConfiguration:
path: str
size: str
transport: str
logical_sector_size: int
physical_sector_size: int
partition_table_type: str
model: str
@dataclass(frozen=True)
class PartitionConfiguration:
number: int
begin: str
end: str
size: str
filesystem_type: str
name: str
kpartx_name: str
flags_set: str
@dataclass(frozen=True)
class DiskInformation:
type: str
configuration: DiskConfiguration
partitions: list
class DiskConfigError(Exception):
def __init__(self, message, device, real_device, parted_output):
super().__init__(
f'{message} for device {device} (real device {real_device}). '
f'Parted output was: {parted_output}'
)
def cleanup_kpartx(device):
cmdline = ['kpartx', '-d', '-v', device]
for delay in (0.1, 0.3, 0.5, 1, 2, 3, None):
result = log_and_call(cmdline, method=subprocess.run, text=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if result.returncode == 0:
return
if 'is in use' in result.stdout:
logging.warning('Some partitions of %s are still in use: ', device)
logging.warning(result.stdout)
if delay is not None:
logging.info('waiting for %.01f seconds', delay)
time.sleep(delay)
else:
raise RuntimeError('Unexpected error from kpartx: '
f'{result.stdout}')
raise RuntimeError(f'Failed to cleanup partitions for {device} '
'with kpartx')
def get_kpartx_names(device):
cmdline = ['kpartx', '-l', '-s', device]
logging.debug('Running %s', cmdline)
try:
output = log_and_output(cmdline)
result = {}
for index, line in enumerate(output.splitlines()):
name = line.split(' ', 1)[0]
result[int(index + 1)] = f'/dev/mapper/{name}'
return result
finally:
try:
cleanup_kpartx(device)
except Exception:
logging.exception('Exception while cleaning up partitions '
'for device %s', device)
@contextlib.contextmanager
def partitions_exposed(device):
with transact(
prepare=(
f'Exposing kpartx partitions for {device}',
lambda: log_and_call(['kpartx', '-a', '-s', device])
),
final=(
f'cleaning up partitions for device {device}',
lambda _: cleanup_kpartx(device)
)
):
yield
def parse_partitions(device, lines):
kpartx_names = get_kpartx_names(device)
for line in lines:
assert line.endswith(';')
number, begin, end, size, fs, name, flags = line[:-1].split(':')
yield PartitionConfiguration(
number=int(number),
begin=begin,
end=end,
size=size,
filesystem_type=fs,
name=name,
kpartx_name=kpartx_names[int(number)],
flags_set=flags,
)
def get_disk_information(device):
real_device = os.path.realpath(device)
output = log_and_output(['parted', '-s', '-m', real_device, 'print'])
lines = list(line.strip() for line in output.splitlines())
if len(lines) < 2:
raise DiskConfigError(
'Expected at least two lines in parted output',
device, real_device, output
)
BYTES = 'BYT'
if lines[0] != f'{BYTES};':
raise DiskConfigError(
'Only "Bytes" units are supported',
device, real_device, output
)
path, size, transport, lss, pss, ptt, model, end = lines[1].split(':')
if path != real_device:
raise DiskConfigError(
'Expected device spec as second line of parted output',
device, real_device, output
)
disk_config = DiskConfiguration(
path=path,
size=size,
transport=transport,
logical_sector_size=int(lss),
physical_sector_size=int(pss),
partition_table_type=ptt,
model=model,
)
return DiskInformation(
type=BYTES,
configuration=disk_config,
partitions=list(parse_partitions(device, lines[2:])),
)
def get_partition(device, disk_info, name):
parts = list(part for part in disk_info.partitions if part.name == name)
if len(parts) != 1:
raise RuntimeError(f'Expected exactly one partition with name {name} '
f'on device {device}, got {disk_info.partitions}')
return parts[0]
def set_partition_name(device, number, name):
logging.info('Setting partition name to %s for partition number %d on %s',
name, number, device)
log_and_call(['parted', '-s', device, 'name', str(number), name])
def generate_timestamp():
return datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
def non_volatile_pv(cache_config):
return (cache_config.non_volatile_pv if cache_config else None)
LVM_SNAPSHOT_SUFFIX = '-snapshot'
def lvm_snapshot_name(origin, timestamp):
return f'{os.path.basename(origin)}-at-{timestamp}'
def vm_snapshot_name(lvm_snapshot_name):
return f'{lvm_snapshot_name}-snapshot'
def snapshot_copy_name(vm_snapshot_name):
return f'{vm_snapshot_name}-copy'
def lv_path(vg, lv):
return f'/dev/{vg}/{lv}'
def cache_lv_name(vm_snapshot_name):
return f'{vm_snapshot_name}-cache'
def snapshot_glob(origin):
return f'{origin}-at-*-snapshot'
def is_lv_open(name):
logging.info('Checking if LV %s is open', name)
cmdline = ['lvs', '-o', 'lv_attr', '--noheadings', name]
output = log_and_output(cmdline).strip()
flag = output[5]
if flag == '-':
return False
elif flag == 'o':
return True
else:
raise RuntimeError(f'Cannot parse LV attributes "{output}"')
def create_lvm_snapshot(origin, name, non_volatile_pv, size=None,
extents=None):
cmdline = ['lvcreate', '-y', '-s', '-n', name]
if size:
cmdline.extend(('-L', size))
else:
assert extents
cmdline.extend(('-l', extents))
cmdline.append(origin)
if non_volatile_pv is not None:
cmdline.append(non_volatile_pv)
log_and_call(cmdline)
def remove_lv(name):
log_and_call(['lvremove', '-f', name])
def umount(mountpoint):
log_and_call(['umount', mountpoint])
@contextlib.contextmanager
def mounted(device, mountpoint, type_=None, options=None):
assert os.path.exists(mountpoint), f'{mountpoint} does not exist'
mount_cmdline = ['mount']
if type_ is not None:
mount_cmdline.extend(['-t', type_])
if options is not None:
mount_cmdline.extend(options)
mount_cmdline.append('none' if device is None else device)
mount_cmdline.append(mountpoint)
logging.info('Mounting %s to %s', device, mountpoint)
log_and_call(mount_cmdline)
with transact(final=(f'unmouning {mountpoint}',
lambda _: log_and_call(['umount', mountpoint]))):
yield
@contextlib.contextmanager
def chroot(partition):
with contextlib.ExitStack() as stack:
root = stack.enter_context(
tempfile.TemporaryDirectory(prefix='snapshot_root_')
)
stack.enter_context(mounted(partition, root))
stack.enter_context(mounted(None, os.path.join(root, 'proc'),
type_='proc'))
stack.enter_context(mounted(None, os.path.join(root, 'sys'),
type_='sysfs'))
stack.enter_context(mounted('/dev', os.path.join(root, 'dev'),
options=('--bind',)))
stack.enter_context(mounted('/dev/pts',
os.path.join(root, 'dev', 'pts'),
options=('--bind',)))
yield root
def get_disk(vmm, vm):
disks = list(vmm.get_disks(vm))
if len(disks) != 1:
raise RuntimeError('Need exactly one disk for vm, got {disks}')
return disks[0]
def create_vm_disk_snapshot(vmm, vm, host, timestamp, size, non_volatile_pv):
origin = None
name = None
with vm_shut_down(vmm, vm, host):
lv = get_disk(vmm, vm)
wait_for(lambda: not is_lv_open(lv), timeout=30, step=1)
origin = lv
name = lvm_snapshot_name(origin, timestamp)
create_lvm_snapshot(origin, name, non_volatile_pv, size=size)
return os.path.join(os.path.dirname(origin), name)
def create_lvm_volume(name, size, vg, pv=None):
create_cmdline = ['lvcreate', '-y', '-L', f'{size}B', '-n', name, vg]
if pv is not None:
create_cmdline.append(pv)
log_and_call(create_cmdline)
return name
def create_volume_copy(src, dst, non_volatile_pv):
size = log_and_output(['blockdev', '--getsize64', src]).strip()
vg = os.path.basename(os.path.dirname(src))
return os.path.join(
os.path.dirname(src),
create_lvm_volume(dst, size, vg, non_volatile_pv)
)
@contextlib.contextmanager
def volume_copy(src, dst, non_volatile_pv):
with transact(
prepare=(
f'copying LVM {src} to {dst}',
lambda: create_volume_copy(src, dst, non_volatile_pv)
),
rollback=(
'cleaning up LVM copy',
lambda result: remove_lv(result[0])
)
) as copy_name:
yield copy_name
def copy_data(src, dst, block_size='128M'):
logging.info('Copying data from %s to %s', src, dst)
log_and_call(['dd', f'if={src}', f'of={dst}', f'bs={block_size}'])
def move_link(src, dst):
new_dst = f'{dst}.new'
if os.path.exists(new_dst):
logging.waring('%s already exists, removing', new_dst)
os.unlink(new_dst)
os.symlink(src, new_dst)
os.rename(new_dst, dst)
@contextlib.contextmanager
def link_snapshot_copy(origin, copy_to, non_volatile_pv):
copy_name = snapshot_copy_name(origin)
with contextlib.ExitStack() as stack:
copy = stack.enter_context(
volume_copy(origin, copy_name, non_volatile_pv)
)
copy_data(origin, copy)
stack.enter_context(transact(
commit=(
f'linking snapshot copy {copy_name} to {copy_to}',
lambda _: move_link(copy, copy_to)
),
))
yield
def create_cache_volume(non_cached_name, config):
name = cache_lv_name(non_cached_name)
logging.info('Adding cache volume %s for %s', non_cached_name, name)
return create_lvm_volume(name, config.cache_volume_size,
config.volume_group, config.cache_pv)
@contextlib.contextmanager
def cache_volume(non_cached_name, config):
with transact(
prepare=(
None,
lambda: create_cache_volume(non_cached_name, config)
),
rollback=(
f'removing cache volume for {non_cached_name}',
lambda result: remove_lv(result[0])
)
) as cached_name:
yield cached_name
def cache_record_file(config, volume):
return os.path.join(config.cached_volumes_path, os.path.basename(volume))
def create_cache_record(config, volume):
record_file = cache_record_file(config, volume)
os.makedirs(os.path.dirname(record_file), exist_ok=True)
with open(record_file, 'w'):
pass
def delete_cache_record(config, volume):
record_file = cache_record_file(config, volume)
try:
os.remove(record_file)
except FileNotFoundError:
logging.warning('Cache record file %s does not exist', record_file)
def list_cache_records(config):
return os.listdir(config.cached_volumes_path)
@contextlib.contextmanager
def cache_record(name, config):
with transact(
prepare=(
f'Adding cache record for {name}',
lambda: create_cache_record(config, name)
),
rollback=(
f'Deleting cache record for {name}',
lambda _: delete_cache_record(config, name)
)
):
yield
def configure_caching(non_cached_volume, config):
if config is None:
logging.info('Caching is not configured, skipping cache for %s',
non_cached_volume)
return non_cached_volume
try:
with contextlib.ExitStack() as stack:
cache_volume_name = stack.enter_context(
cache_volume(non_cached_volume, config)
)
stack.enter_context(cache_record(non_cached_volume, config))
enable_cmdline = [
'lvconvert', '-y', '--type', 'cache',
'--cachevol', cache_volume_name,
'--cachemode', 'writethrough', non_cached_volume
]
logging.info('Enabling cache for %s on %s', non_cached_volume,
cache_volume_name)
log_and_call(enable_cmdline)
cached_volume = non_cached_volume
return cached_volume
except Exception:
logging.exception('Failed to enable caching for %s', non_cached_volume)
return non_cached_volume
@contextlib.contextmanager
def vm_disk_snapshot(vmm, ref_vm, ref_host, timestamp, size, cache_config):
nvpv = non_volatile_pv(cache_config)
with contextlib.ExitStack() as stack:
with transact(
prepare=(
f'Creating disk snapshot of {ref_vm}',
lambda: create_vm_disk_snapshot(vmm, ref_vm, ref_host,
timestamp, size, nvpv)
),
final=(
'cleaning up disk snapshot',
lambda result: remove_lv(result[0])
)
) as lvm_snapshot:
assert os.path.exists(lvm_snapshot)
vm_snapshot = stack.enter_context(volume_copy(
lvm_snapshot, vm_snapshot_name(os.path.basename(lvm_snapshot)),
nvpv
))
assert os.path.exists(vm_snapshot)
copy_data(lvm_snapshot, vm_snapshot)
yield vm_snapshot
class VirtualMachineManager(abc.ABC):
def is_vm_running(self, name):
pass
def start(self, name):
pass
def reset(self, name):
pass
def get_disks(self, name):
pass
class Virsh(VirtualMachineManager):
def is_vm_running(self, name):
logging.info('Checking if %s is running', name)
cmdline = ['virsh', 'list', '--state-running', '--name']
list_output = log_and_output(cmdline)
domains = set(d.strip() for d in list_output.splitlines() if d)
logging.info('Running domains: %s', domains)
return name in domains
def start(self, name):
log_and_call(['virsh', 'start', name])
def reset(self, name):
logging.warning('Resetting %s', name)
log_and_call(['virsh', 'reset', name])
def get_disks(self, name):
xml = log_and_output(['virsh', 'dumpxml', name])
root = ET.fromstring(xml)
for disk in root.findall('./devices/disk/source'):
yield disk.get('dev')
@contextlib.contextmanager
def vm_shut_down(vmm, name, host):
shutdown(host)
wait_for(lambda: not vmm.is_vm_running(name), timeout=180, step=3)
try:
yield
finally:
vmm.start(name)
try:
wait_for(lambda: is_accessible(host), 300, 5)
except Timeout:
logging.exception('Timed out waiting for %s to become accessbile '
'with ssh', host)
raise
@dataclass(frozen=True)
class CowPartitionsConfig:
base: str
network: str
local: str
cow: str
conf: str
sign: str
keyimage: str
place: str
@dataclass(frozen=True)
class CacheConfig:
volume_group: str
non_volatile_pv: str
cache_pv: str
cache_volume_size: str
cached_volumes_path: str
def check_preconditions(vmm, ref_vm, ref_host):
if not vmm.is_vm_running(ref_vm):
raise RuntimeError(f'Reference vm {ref_vm} is not running')
if not is_accessible(ref_host):
raise RuntimeError(f'Reference host {ref_host} is not accessible '
'with ssh')
def copy_files(root, to_copy):
def relpath(top, dirpath, path):
return os.path.relpath(os.path.join(dirpath, path), top)
for dir_ in to_copy:
logging.info('Copying contents of %s to %s', dir_, root)
assert os.path.isdir(dir_)
for dirpath, dirnames, filenames in os.walk(dir_):
for dirname in dirnames:
dst = os.path.join(root, relpath(dir_, dirpath, dirname))
os.makedirs(dst, exist_ok=True)
for filename in filenames:
src = os.path.join(dirpath, filename)
dst = os.path.join(root, relpath(dir_, dirpath, filename))
if os.path.exists(dst):
logging.debug('Overwriting %s with %s', dst, src)
else:
logging.debug('Copying %s to %s', src, dst)
shutil.copy2(src, dst)
def write_timestamp(root, timestamp):
with open(os.path.join(root, 'etc', 'timestamp'), 'w') as timestamp_out:
print(timestamp, file=timestamp_out)
def write_cow_config(args, root):
config_path = os.path.join(root, 'etc', 'cow.conf')
logging.info('Writing cow config to %s', config_path)
with open(config_path, 'w') as config_output:
PARTITION_NAMES = 'PARTITION_NAMES'
config_output.write(f'declare -A {PARTITION_NAMES}\n')
for key, value in vars(args.partitions_config).items():
config_output.write(f'{PARTITION_NAMES}[{key}]={value}\n')
def run_chroot_script(root, script):
if script is not None:
logging.info('Running chroot script %s in %s', script, root)
log_and_call(['chroot', root, script])
def snapshot_artifacts_path(output, snapshot_disk):
return os.path.join(output, os.path.basename(snapshot_disk))
@contextlib.contextmanager
def snapshot_artifacts(output, snapshot_disk):
path = snapshot_artifacts_path(output, snapshot_disk)
assert not os.path.exists(path)
logging.info('Creating snapshot artifacts directory %s', path)
os.makedirs(path)
try:
yield path
except Exception:
logging.error('Exception while using artifacts directory %s, '
'clening up', path)
shutil.rmtree(path)
raise
def publish_kernel_images(root, artifacts):
logging.info('Publishing kernel images to %s', artifacts)
return tuple(
shutil.copy2(os.path.join(root, file_), artifacts)
for file_ in ('vmlinuz', 'initrd.img')
)
def remove_iscsi_backstore(name):
logging.info('Removing iSCSI backstore %s', name)
log_and_call(['targetcli', '/backstores/block', 'delete', name])
def get_iscsi_backstore_name(device):
return os.path.basename(device)
@contextlib.contextmanager
def create_iscsi_backstore(device):
name = get_iscsi_backstore_name(device)
cmdline = ['targetcli', '/backstores/block', 'create',
f'dev={device}', f'name={name}', 'readonly=True']
logging.info('Adding iSCSI backstore %s', name)
log_and_call(cmdline)
with transact(
rollback=(
f'cleaning up iSCSI backstore {name}',
lambda _: remove_iscsi_backstore(name)
)
):
yield name
def remove_iscsi_target(name):
logging.info('Removing iSCSI target %s', name)
log_and_call(['targetcli', '/iscsi', 'delete', name])
def attach_backstore_to_iscsi_target(target_name, backstore_name):
logging.info('Adding iSCSI LUN to %s from %s', target_name, backstore_name)
cmdline = ['targetcli', f'/iscsi/{target_name}/tpg1/luns', 'create',
f'/backstores/block/{backstore_name}']
log_and_call(cmdline)
def get_iscsi_target_name(backstore_name):
return f'iqn.2013-07.cow.{backstore_name}'
@contextlib.contextmanager
def create_iscsi_target(backstore_name):
target_name = get_iscsi_target_name(backstore_name)
logging.info('Adding iSCSI target %s', target_name)
log_and_call(['targetcli', '/iscsi', 'create', target_name])
with transact(
rollback=(
f'cleaning up iSCSI target {target_name}',
lambda _: remove_iscsi_target(target_name)
)
):
attach_backstore_to_iscsi_target(target_name, backstore_name)
yield target_name
def configure_authentication(target_name):
cmdline = ['targetcli', f'/iscsi/{target_name}/tpg1', 'set', 'attribute',
'generate_node_acls=1']
logging.info('Configuring iSCSI authentication')
log_and_call(cmdline)
def save_iscsi_config():
logging.info('Saving iSCSI configuration')
log_and_call(['targetcli', 'saveconfig'])
@contextlib.contextmanager
def publish_to_iscsi(device):
with transact(
rollback=('saving iSCSI config', lambda _: save_iscsi_config())
), contextlib.ExitStack() as stack:
backstore_name = stack.enter_context(create_iscsi_backstore(device))
target_name = stack.enter_context(create_iscsi_target(backstore_name))
configure_authentication(target_name)
save_iscsi_config()
yield target_name
def ipxe_config_filename(output, iscsi_target_name):
return os.path.join(output, f'{iscsi_target_name}.ipxe')
@contextlib.contextmanager
def generate_ipxe_config(output, iscsi_target_name, kernel, initrd):
kernel_path = os.path.relpath(kernel, output)
initrd_path = os.path.relpath(initrd, output)
config_path = ipxe_config_filename(output, iscsi_target_name)
with open(config_path, 'w') as config_output:
config_output.write(f'''#!ipxe
set iti {socket.getfqdn()}
set itn {iscsi_target_name}
set iscsi_params iscsi_target_ip=${{iti}} iscsi_target_name=${{itn}}
set cow_params cowsrc=network cowtype=${{cowtype}} root=/dev/mapper/root
set params ${{iscsi_params}} ${{cow_params}}
kernel {kernel_path} BOOTIF=01-${{netX/mac}} ${{params}} quiet
initrd {initrd_path}
boot
''')
with transact(
rollback=(
f'cleaning up iSCSI config {config_path}',
lambda _: os.remove(config_path)
)
):
yield config_path
@contextlib.contextmanager
def saved_config(path):
old_path = f'{path}.old'
if os.path.exists(old_path):
logging.warning('Old config %s exists, removing', old_path)
os.remove(old_path)
if not os.path.exists(path):
logging.warning('%s does not exist', path)
else:
os.rename(path, old_path)
try:
yield old_path
except Exception:
logging.warning('Restoring config %s from %s', path, old_path)
if os.path.exists(old_path):
os.rename(old_path, path)
raise
else:
os.remove(old_path)
@contextlib.contextmanager
def published_ipxe_config(output, config, testing=False):
path = os.path.join(output, 'boot-test.ipxe' if testing else 'boot.ipxe')
logging.info(f'Publishing{" testing" if testing else ""} iPXE config '
'to %s', path)
with contextlib.ExitStack() as stack:
stack.enter_context(saved_config(path))
stack.enter_context(transact(
rollback=(f'removing {path}', lambda _: os.remove(path))
))
os.symlink(config, path)
yield path
@contextlib.contextmanager
def reset_back_on_failure(vmm, vm):
with transact(rollback=(None, lambda _: vmm.reset(vm))):
yield
def reboot_and_check_test_vm(vmm, vm, host, timestamp):
def booted_properly(host):
if not is_accessible(host):
return False
try:
cmdline = ['ssh', host, 'cat', '/etc/timestamp']
output = log_and_output(cmdline).strip()
if output != timestamp:
logging.warning('Actual timestamp %s is not expected %s',
output, timestamp)
return True
except Exception:
logging.exception('Failed to get timestamp from %s', host)
if is_accessible(host):
reboot(host)
else:
logging.warning('%s is not accessble', host)
vmm.reset(vm)
wait_for(lambda: booted_properly(host), timeout=180, step=10)
def try_reboot_if_idle(host):
logging.info('Checking if host %s is idle', host)
try:
who = ssh(host, 'who', output=True,
options=('-o', 'ConnectTimeout=1')).strip()
except Exception:
logging.exception('Failed to check if host %s is idle', host)
return
if who:
logging.info('Host %s is busy, skipping reboot', host)
else:
try:
reboot(host)
except Exception:
logging.exception('Failed to reboot host %s', host)
def reboot_inactive_clients(vmm, args):
snapshots = get_snapshots(vmm, args.ref_vm)
for snapshot in snapshots:
backstore_name = get_iscsi_backstore_name(snapshot)
target_name = get_iscsi_target_name(backstore_name)
sessions = get_dynamic_iscsi_sessions(target_name)
for session in sessions:
try:
host = get_hostname(session)
except Exception:
logging.exception('Failed to get hostname from %s', session)
continue
logging.debug('Snapshot %s is used on %s in session %s',
snapshot, host, session)
if host != args.test_host:
try_reboot_if_idle(host)
def add_snapshot(args):
vmm = Virsh()
check_preconditions(vmm, args.ref_vm, args.ref_host)
timestamp = generate_timestamp()
with contextlib.ExitStack() as snapshot_stack:
snapshot_disk = snapshot_stack.enter_context(vm_disk_snapshot(
vmm, args.ref_vm, args.ref_host, timestamp, args.snapshot_size,
args.cache_config
))
artifacts = snapshot_stack.enter_context(
snapshot_artifacts(args.output, snapshot_disk)
)
logging.info('Snapshot disk is %s', snapshot_disk)
disk_info = get_disk_information(snapshot_disk)
assert disk_info.configuration.partition_table_type == 'gpt', (
'VMs must have disk with GPT partitoin table'
)
base_partition = get_partition(snapshot_disk, disk_info,
args.partitions_config.base)
set_partition_name(snapshot_disk, base_partition.number,
args.partitions_config.network)
disk_info = get_disk_information(snapshot_disk)
net_partition = get_partition(snapshot_disk, disk_info,
args.partitions_config.network)
with contextlib.ExitStack() as fs_stack:
fs_stack.enter_context(partitions_exposed(snapshot_disk))
root = fs_stack.enter_context(chroot(net_partition.kpartx_name))
copy_files(root, args.to_copy)
write_timestamp(root, timestamp)
write_cow_config(args, root)
run_chroot_script(root, args.chroot_script)
kernel, initrd = publish_kernel_images(root, artifacts)
if args.link_snapshot_copy:
snapshot_stack.enter_context(
link_snapshot_copy(snapshot_disk, args.link_snapshot_copy,
non_volatile_pv(args.cache_config))
)
configure_caching(snapshot_disk, args.cache_config)
iscsi_target_name = snapshot_stack.enter_context(
publish_to_iscsi(snapshot_disk)
)
ipxe_config = snapshot_stack.enter_context(generate_ipxe_config(
args.output, iscsi_target_name, kernel, initrd
))