-
Notifications
You must be signed in to change notification settings - Fork 3
/
test_bless2
executable file
·2845 lines (2463 loc) · 91.8 KB
/
test_bless2
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/python
#
# Copyright (c) 2020 Apple Inc. All rights reserved.
#
# This program tests BLESS(8) Command Line Interface.
#
# To add a new test case:
# (1) create a test_<testname> routine
# (2) update TestListDictionary with the new test information
#
# bless2 library API being used by
# kmutil(K), bootabilityutil(B), PurpleRestore(P), bless2cli(C)
#
# ...C int bless2_summarize(const char *disk, vol_summary_t **s) __result_use_check;
# ...C void bless2_summary_free(vol_summary_t *s);
# .B.C int bless2_isc_preboot(vol_summary_t *s, char *preboot, size_t len);
# .B.C int bless2_os_preboot(vol_summary_t *s, char *preboot, size_t len);
# ...C int bless2_os_recovery(vol_summary_t *s, char *recovery, size_t len);
# K..C int bless2_bootobjects_path(vol_summary_t *s, CFDictionaryRef args,
# char *out_relative_path, size_t path_size);
# .BPC int bless2_boot_with_args(vol_summary_t *s, CFDictionaryRef args);
# ...C int bless2_verify_with_args(vol_summary_t *s, CFDictionaryRef args);
# .BPC int bless2_install_with_args(vol_summary_t *s, CFDictionaryRef args);
# .B.C int bless2_gc_with_args(vol_summary_t *s, CFDictionaryRef args);
# K..C int bless2_install_custom_obj(vol_summary_t *s, CFDictionaryRef args);
# .B.C int bless2_update_all_custom_objs(bless2_update_function_t fn, void *ctxt,
# CFDictionaryRef args);
#
import sys
import os
import logging
import plistlib
import uuid
import re
import collections
import time
import glob
from subprocess import Popen, PIPE, call
from datetime import datetime
from os import listdir
from os.path import expanduser
#
# XXX move common routines to a library for test_asr/test_bless/test_bless2
# XXX rename classes SOURCE, TARGET for common usage
# XXX check how eoslib is arranged
#
Debug = False
ErrorPause = False
BootPlist = 'com.apple.Boot.plist'
isArm = True
# LOG file for each test_bless2 program run on the system
tuuid = uuid.uuid4()
LOGDIR = '/Library/Logs/test_bless/'
TESTDIR = LOGDIR + str(tuuid) + '/'
LOGFILE = TESTDIR + 'test_bless.log'
BATSLOG = LOGDIR + 'bats_bless_presubmit.log'
VOLDIR = '/Volumes/'
#SRCDATA = '/usr/lib'
#SRCDATA = '/usr/local/bin'
# XXX change the folder to avoid issues caused by 64184194
SRCDATA = '/System/Applications/Utilities'
SRCIMG = TESTDIR + 'asr_source.dmg'
SRCVOL = 'test_src' + str(os.getpid())
SRCOSIMG = TESTDIR + 'asr_source_os.dmg'
SRCOSVOL = 'test_src_osvol' + str(os.getpid())
SRCROSVIMG = TESTDIR + 'asr_source_rosv.dmg'
SRCROSVDATAVOL = 'test_src_rosvdata' + str(os.getpid())
SRCROSVSYSVOL = 'test_src_rosvsys' + str(os.getpid())
TGTIMG = TESTDIR + 'asr_target.dmg'
TGTVOL = 'test_tgt' + str(os.getpid())
TGTROSVDATAVOL = 'test_tgt_rosvdata' + str(os.getpid())
TGTROSVSYSVOL = 'test_tgt_rosvsys' + str(os.getpid())
HOLDMNTFILE = '/test_bless_holdmntptfile'
MTREEOUTFILE = TESTDIR + 'asr_mtree.out'
TYPE_SRC_IMG = 1 # Source is a dummy disk image
TYPE_SRC_VOL = 2 # Source is a dummy volume
TYPE_SRC_NAME = 3 # Source is the given name/path
TYPE_SRC_OSIMG = 4 # Source is a dummy OS image to be created
TYPE_SRC_OSVOL = 5 # Source is a dummy OS volume to be created
TYPE_SRC_ROSVIMG = 6 # Source is a dummy ROSV volume-group image to be created
TYPE_SRC_ROSV = 7 # Source is a dummy ROSV volume-group to be created
TYPE_SRC_SNAPVOL = 8 # Source is a volume with multiple snapshots
TYPE_SRC_SNAPIMG = 9 # Source is an image with multiple snapshots
TYPE_SRC_SNAPROSV = 10 # Source is an ROSV volume-group with multiple snapshots
TYPE_SRC_SNAPROSVIMG = 11 # Source is an ROSV diskimage with multiple snapshots
TYPE_SRC_HFSIMG = 12 # Source is a HFS image
# XXX can use smaller space?
SIZE_SRCDATA = '3g'
SIZE_TGTDATA = '5g'
SIZE_TGTFACT = '8g'
SIZE_TGTFACTOS = '40g'
SIZE_TGTFACTOS_INVERT = '70g'
SIZE_TGTFACTOS_ARV = '70g'
SIZE_TGTOS = '40g'
SIZE_TGTOS_INVERT = '50g'
SIZE_TGTXCODE = '60g'
start_time4all = 0
start_time4each = 0
succeed_count = 0
fail_count = 0
known_fail_count = 0
skip_count = 0
unclean_count = 0
check_performance = 0
#
# Test name convension
#
TNAME_ENCRYPT = 'encrypt'
#
# /SWE macOS Images available in
# /SWE/Teams/CoreOS/Images/prod/ASR/
# or /SWE/Teams/MSQ/macOS/asr/
# /SWE XCODE Images available in
# /SWE/Xcode/Images/
#
OSDIR = '/SWE/Teams/CoreOS/Images/prod/ASR/'
OSDIR_GOLDEN = OSDIR + 'Golden/'
OSDIR_JAZZ = OSDIR + 'macOSJazz/'
OSDIR_LIB = OSDIR + 'macOSLiberty/'
XCODEDIR = '/SWE/Xcode/Images/macOS_iOS_tvOS_watchOS_bridgeOS/macOSJazz_Yukon_Yager_Grace_bridgeOSJazz/standard-ui-sdk-internal/'
#
# Local Images location and names
#
DMGDIR = '/tmp/test_bless/'
SWEDMGname = {OSDIR_GOLDEN: '', OSDIR_JAZZ: '', OSDIR_LIB: '', XCODEDIR: ''}
#
# apfs_sealvolume location
#
APFS_SEALER = '/System/Library/Filesystems/apfs.fs/Contents/Resources/apfs_sealvolume'
#
# For bless2, Apple Silicon systems
#
SRCDIR_PATH = '/restore/'
bless2_guuid = ''
bless2_prebvdev = ''
bless2_srcdirpath = ''
bless2_osmanifestpath = ''
bless2_rootCdev = ''
bless2_rootVdev = ''
bless2_root_nvram_boot = ''
bless2_root_nvram_altboot = ''
#================================================
# HELPER FUNCTIONS
#================================================
#
# test_bless program usage
#
def usage():
print 'This test is for libbless2 on Apple Silicon systems.'
print 'Usage:'
print ' test_bless2 all | presubmit | remote <option> (Run all or a subset of tests)'
print ' test_bless2 <testname> <option> (Run a given <testname>)'
print ' <option>'
print ' -debug (Exit right after bless command to debug)'
print ' -errorpause (Pause the process on error before clean up)'
print ' test_bless2 -l (list all <testname>s)'
print ' test_bless2 -c (clean up all log directories)'
print ''
#
# docmd_common without printing out the command line
#
def docmd_common_noprint(cmd):
result = Popen(cmd, stdout=PIPE, stderr=PIPE)
try:
out, errmsg = result.communicate()
except:
print 'Command interrupted...'
exit(1)
err = result.returncode
# Log command output messages
if err and cmd[0] != '/sbin/umount' and cmd[0] != '/bin/rm' and \
cmd[0] != '/bin/ls':
logging.error(out)
logging.error(errmsg)
else:
logging.info(out)
logging.info(errmsg)
# Print result output messages
if cmd[0] == '/usr/sbin/asr' or cmd[0] == '/usr/local/bin/xia' or \
cmd[0] == '/usr/bin/time' or cmd[0] == 'time' or \
(err and cmd[0] != '/sbin/umount' and cmd[0] != '/bin/rm' and \
cmd[0] != '/bin/ls'):
print out
print errmsg
return out, err
#
# Common routine for docmd*
#
def docmd_common(cmd):
logging.info('call: {}'.format(cmd))
print('call: {}'.format(cmd))
out, err = docmd_common_noprint(cmd)
return out, err
#
# Run cmd, return 0 for success, non-zero for failure
#
def docmd(cmd):
out, err = docmd_common(cmd)
return err
#
# Run cmd, return plist for success, error number for failure
#
def docmd_plist(cmd):
out, err = docmd_common(cmd)
if err == 0:
# Success, return plist
plist = plistlib.readPlistFromString(out)
return plist, 0
else:
return out, err
#
# Startup tasks before running all the tests
#
def Startup():
global start_time4all
cmd = ['/bin/mkdir', '-p', TESTDIR]
call(cmd)
cmd = ['/bin/mkdir', '-p', DMGDIR]
call(cmd)
logging.basicConfig(format='%(asctime)s %(levelname)s (%(funcName)s) %(message)s',
datefmt='%m/%d/%Y %H:%M:%S', filename=LOGFILE, level=logging.DEBUG)
start_time4all = datetime.now()
logging.info('\n\nTESTING BEGINS at {}'.format(start_time4all))
print '\nTESTING Begins at {}'.format(start_time4all)
docmd_common_noprint(['/usr/bin/sw_vers'])
#
# Teardown tasks after running all the tests
#
def Teardown():
global succeed_count
global fail_count
global known_fail_count
global skip_count
global unclean_count
global check_performance
now = datetime.now()
time_elapsed = now - start_time4all
logging.info('TESTING ENDS at {}'.format(now))
print 'TESTING ENDS at {}'.format(now)
logging.info('---------------------------------------------------------------')
print '---------------------------------------------------------------'
if known_fail_count:
logging.info('Total number of tests SUCCEED=%d, FAIL=%d (KNOWN=%d), SKIP=%d',
succeed_count, fail_count, known_fail_count, skip_count)
print 'Total number of tests SUCCEED=%d, FAIL=%d (KNOWN=%d), SKIP=%d'%\
(succeed_count, fail_count, known_fail_count, skip_count)
else:
logging.info('Total number of tests SUCCEED=%d, FAIL=%d, SKIP=%d',
succeed_count, fail_count, skip_count)
print 'Total number of tests SUCCEED=%d, FAIL=%d, SKIP=%d'%\
(succeed_count, fail_count, skip_count)
if unclean_count > 0:
logging.info('Total number of tests UNCLEAN=%d (Please clean up manually) ',
unclean_count)
print 'Total number of tests UNCLEAN=%d (Please clean up manually)'\
%unclean_count
logging.info('Total running time {} (h:m:s.ms)'.format(time_elapsed))
print 'Total running time {} (h:m:s.ms)'.format(time_elapsed)
logging.info('Log information in %s\n', LOGFILE)
print 'Log information in %s\n'%LOGFILE
if check_performance == 1:
logging.info('Check PERFORMANCE DATA in the Log file\n')
print 'Check PERFORMANCE DATA in the Log file'
call(['/bin/cp', LOGFILE, BATSLOG])
if fail_count > 0:
exit(1)
else:
exit(0)
#
# Check access permission
#
def checkaccess(dir):
err = docmd(['/bin/ls', '-d', dir])
if err:
logging.error('Can not access ' + dir)
print 'Can not access ' + dir
return err
#
# For each test case, begin wth this
#
def testBegin(testname):
global start_time4each
logging.info('\n\nTEST ' + testname + ' Begin...')
print '\n\nTEST ' + testname + ' Begin...'
start_time4each = datetime.now()
#
# For each test case, end with this
#
def testEnd(testname, src, tgt, err):
global succeed_count
global fail_count
global known_fail_count
global start_time4each
global ErrorPause
if testname.startswith('neg_'):
if err:
err = 0
else:
err = 1
# pause here on error and wait for user input before clean up
if ErrorPause and err:
input = raw_input ("Test paused on error. Enter 'x' to exit or any other key to continue:")
if input == 'x' :
exit()
if src:
src.release()
if tgt:
tgt.release()
time_elapsed = datetime.now() - start_time4each
exist = os.path.isfile(MTREEOUTFILE)
if exist:
docmd(['/bin/rm', '-f', MTREEOUTFILE])
if err:
logging.info('TEST ' + testname + ' FAIL ' +
'(elapsed-time {})'.format(time_elapsed) + '\n')
print 'TEST ' + testname + ' FAIL ' + \
'(elapsed-time {})'.format(time_elapsed) + '\n'
fail_count = fail_count + 1
if 'bug-' in testname:
known_fail_count = known_fail_count + 1
else:
logging.info('TEST ' + testname + ' SUCCEED ' +
'(elapsed-time {})'.format(time_elapsed) + '\n')
print 'TEST ' + testname + ' SUCCEED ' + \
'(elapsed-time {})'.format(time_elapsed) + '\n'
succeed_count = succeed_count + 1
#
# Clean up all log directories in LOGDIR
#
def log_cleanup():
cmd = ['/bin/rm', '-rf', LOGDIR]
call(cmd)
cmd = ['/bin/rm', '-rf', DMGDIR]
call(cmd)
#
# XXX let the caller specify a specific image name: /path/to/image_name?
#
# Get the latest dmg name derived from the given dir
# (OS)
# % ls -lt <dir> | awk '/.AppleInternal.dmg/ {print $9}' | awk 'NR==1 {print $1}'
# (XCODE)
# % ls -lt <dir> | awk '/.dmg/ {print $9}' | awk 'NR==1 {print $1}'
#
def get_dmg_shortname(dir):
err = checkaccess(dir)
if err:
return ''
try:
cmd = ['/bin/ls', '-lt', dir]
ls = Popen(cmd, stdout=PIPE)
if 'Xcode' in dir:
cmd = "/usr/bin/awk '/.dmg/ {print $9}'"
else:
cmd = "/usr/bin/awk '/.AppleInternal.dmg/ {print $9}'"
awk1 = Popen(cmd, stdin=ls.stdout, stdout=PIPE, shell=True)
cmd = "/usr/bin/awk 'NR==1 {print $1}'"
awk2 = Popen(cmd, stdin=awk1.stdout, stdout=PIPE, shell=True)
out, err = awk2.communicate()
if err:
return ''
out = out.strip('\n')
logging.info('get_dmg_shortname: ' + out)
return out
except:
logging.error('get_dmg_shortname Failed')
print 'get_dmg_shortname Failed'
return ''
#
# Copy and get remote OS dmg or XCODE dmg file from the given dir
# to a local directory
#
# If LocalMacOS is True, have macOS ASR images available in $HOME/Downloads/test_asr/,
# e.g.
# % ls $HOME/Downloads/test_asr/*
# /Users/smadmin/Downloads/test_asr/Golden:
# Golden20A284UMIA_ASR_NFA.AppleInternal.dmg
# /Users/smadmin/Downloads/test_asr/macOSJazz:
# macOSJazz19A603.AppleInternal.dmg
# /Users/smadmin/Downloads/test_asr/macOSLiberty:
# macOSLiberty18A391.AppleInternal.dmg
# /Users/smadmin/Downloads/test_asr/Xcode:
# Xcode11M392v_m18A391011_m19A603_i17A878_t17J586_w17R605_b17P572_FastSim_Boost_43GB.dmg
#
def get_dmg_name(testname, dir):
global SWEDMGname, skip_count
global LocalMacOS
# If a local dmg file is already copied for this test run, use it.
if SWEDMGname[dir] != '':
return SWEDMGname[dir]
name = get_dmg_shortname(dir)
if name == '':
skip_count = skip_count + 1
logging.info('SKIP test %s\n', testname)
print 'SKIP test ' + testname
return ''
if LocalMacOS:
local_dmg = dir + name
else:
remote_dmg = dir + name
local_dmg = DMGDIR + name
# If this file is not in local DMGDIR, copy it over
err = docmd(['/bin/ls', local_dmg])
if err:
err = docmd(['/bin/cp', remote_dmg, local_dmg])
if err:
# in case it's partially copied, remove it
docmd(['/bin/rm', local_dmg])
local_dmg = ''
skip_count = skip_count + 1
logging.info('SKIP test %s\n', testname)
print 'SKIP test ' + testname
SWEDMGname[dir] = local_dmg
return local_dmg
#
# Get Volume UUID for the given volume device name
#
def DeviceToUUID(dev):
cmd = ['/usr/sbin/diskutil', 'info', '-plist', dev]
plist, err = docmd_plist(cmd)
try:
uuid = plist['VolumeUUID']
except:
logging.info('Unrecognized VolumeUUID plist format')
uuid = ''
return uuid
#
# Get System Volume device in the Group Volume of the given container
# that can map to the given sysdevi.
# e.g. return /dev/disk2s1 for a given snapshot sysdev /dev/disk2s1s1
#
def getSystemVolumeDev(container, sysdev):
cmd = ['/usr/sbin/diskutil', 'apfs', 'listgroups', '-plist', container]
plist, err = docmd_plist(cmd)
if err:
logging.info('Can not listgroups for %s', container)
return ''
c_array = plist['Containers']
for c_entry in c_array:
vol_grps = c_entry['VolumeGroups']
if vol_grps != '':
for entry in vol_grps:
for vol in entry['Volumes']:
devID = '/dev/' + vol['DeviceIdentifier']
if vol['Role'] == 'System' and sysdev.startswith(devID):
return devID
logging.info('Can not get System Volume device for %s', sysdev)
print 'Can not get System Volume device for ' + sysdev
return ''
#
# Get Volume Group UUID for the System Volume in the given Container
#
def DeviceToGroupUUID(container, sysdev):
cmd = ['/usr/sbin/diskutil', 'apfs', 'listgroups', '-plist', container]
plist, err = docmd_plist(cmd)
if err:
logging.info('Can not listgroups for %s', container)
return ''
c_array = plist['Containers']
for c_entry in c_array:
vol_grps = c_entry['VolumeGroups']
if vol_grps != '':
for entry in vol_grps:
for vol in entry['Volumes']:
devID = '/dev/' + vol['DeviceIdentifier']
if vol['Role'] == 'System' and sysdev.startswith(devID):
guuid = entry['APFSVolumeGroupUUID']
logging.info('GroupUUID for %s is %s', sysdev, guuid)
print 'GroupUUID for ' + sysdev + ' is ' + guuid
return guuid
logging.info('Can not get GroupUUID for %s', sysdev)
print 'Can not get GroupUUID for ' + sysdev
return ''
#
# Check if the given UUID is a Volume Group UUID in this Container
#
def isGroupUUID(container, check_uuid):
cmd = ['/usr/sbin/diskutil', 'apfs', 'listgroups', '-plist', container]
plist, err = docmd_plist(cmd)
if err:
logging.info('Can not listgroups for %s', container)
return ''
c_array = plist['Containers']
for c_entry in c_array:
vol_grps = c_entry['VolumeGroups']
if vol_grps != '':
for entry in vol_grps:
guuid = entry['APFSVolumeGroupUUID']
if guuid == check_uuid:
return True
return False
#
# Check if the given 'Vdev' has the given 'role'.
# Return True if it does, False if it does not.
#
def CheckVdevRole(Cdev, Vdev, role):
plist, err = docmd_plist(['/usr/sbin/diskutil', 'apfs', 'list', '-plist', Cdev])
if err:
return ''
C_array = plist['Containers']
C_dict = C_array[0]
V_array = C_dict['Volumes']
for entry in V_array:
roles_array = entry['Roles']
if roles_array and roles_array[0] == role:
roleVdev = '/dev/' + entry['DeviceIdentifier']
if Vdev == roleVdev:
return True
return False
#
# Get the device with the matching 'role' in the given Container.
# Role can be 'Preboot' or 'Recovery' or 'System', etc.
#
def SysCntToRoleVdev(Cdev, role):
# Find the device with the matching role
plist, err = docmd_plist(['/usr/sbin/diskutil', 'apfs', 'list', '-plist', Cdev])
if err:
return ''
C_array = plist['Containers']
C_dict = C_array[0]
V_array = C_dict['Volumes']
for entry in V_array:
roles_array = entry['Roles']
if (len(roles_array) == 1 and roles_array[0] == role) or \
(len(roles_array) == 0 and role == ''):
return '/dev/' + entry['DeviceIdentifier']
return ''
#
# Get device name for the given volume name
#
def MntptToDevice(volume):
cmd = ['/usr/sbin/diskutil', 'info', '-plist', volume]
plist, err = docmd_plist(cmd)
try:
dev = plist['DeviceNode']
except:
logging.info('Unrecognized DeviceNode plist format')
dev = ''
return dev
#
# Get the mountpoint for the given device name
#
def DeviceToMntpt(device):
docmd(['/usr/sbin/diskutil', 'mount', device])
cmd = ['/usr/sbin/diskutil', 'info', '-plist', device]
plist, err = docmd_plist(cmd)
try:
mntpt = plist['MountPoint']
except:
logging.info('Unrecognized MountPoint plist format for %s', device)
print 'Unrecognized MountPoint plist format for ' + device
mntpt = ''
return mntpt
#
# Get the APFS Container devname for the given dev
#
def DeviceToContainer(dev):
cmd = ['/usr/sbin/diskutil', 'info', '-plist', dev]
plist, err = docmd_plist(cmd)
try:
Cdev = plist['APFSContainerReference']
except:
logging.info('Unrecognized APFS Container plist format')
Cdev = ''
return '/dev/' + Cdev
#
# Get a set of System/Data device name in a given container,
# where it's not the current ROSV root.
#
# Assumption: only 1 non-root volume-group in the given container
#
def ContainerToSysData(Cdev):
sysdev = ''
datadev = ''
if Cdev == '':
return '', ''
plist, err = docmd_plist(['/usr/sbin/diskutil', 'apfs', 'listGroups', '-plist', Cdev])
if err:
return sysdev, datadev
rootsys = MntptToDevice('/')
rootdata = MntptToDevice('/System/Volumes/Data')
C_array = plist['Containers']
C_dict = C_array[0]
VG_array = C_dict['VolumeGroups']
for entry in VG_array:
Volumes = entry['Volumes']
for vol in Volumes:
dev = '/dev/' + vol['DeviceIdentifier']
if dev == rootsys or dev == rootdata:
continue
if vol['Role'] == 'System':
sysdev = dev
elif vol['Role'] == 'Data':
datadev = dev
if sysdev != '' and datadev != '':
break
return sysdev, datadev
#
# Wait for encrypting a volume to finish
#
def wait_for_encrypt(Cdev, vol):
start_time = time.time()
while 1:
elapse_time = time.time() - start_time
# wait upto 300 seconds
if elapse_time > 300:
logging.error('Fail: Timeout waiting for encryption to finish')
print 'Fail: Timeout waiting for encryption to finish'
return 1
plist, err = docmd_plist(['/usr/sbin/diskutil', 'apfs', 'list', '-plist', Cdev])
if err:
logging.error('Fail at waiting for encryption to finish')
print 'Fail at waiting for encryption to finish'
logging.error('Fail to wait for encryption to finish')
print 'Fail to wait for encryption to finish'
return err
C_array = plist['Containers']
C_dict = C_array[0]
V_array = C_dict['Volumes']
for entry in V_array:
Vdev = '/dev/' + entry['DeviceIdentifier']
if Vdev == vol:
inProgress = entry['CryptoMigrationOn']
if inProgress == False:
# encryption is done
return 0
time.sleep(5)
#
# Print the device information associated with Source or Target
#
def print_dev_info(obj):
logging.info(obj.__class__.__name__ + ' Disk Image devname = ' + obj.diskimgdev)
logging.info(obj.__class__.__name__ + ' APFS Container devname (apfsCdev) = ' + obj.apfsCdev)
logging.info(obj.__class__.__name__ + ' APFS Volume devname (apfsVdev) = ' + obj.apfsVdev)
logging.info(obj.__class__.__name__ + ' APFS Volume mountpoint (apfsVmntpt) = ' + obj.apfsVmntpt)
logging.info(obj.__class__.__name__ + ' APFS Data Volume devname (apfsDVdev) = ' + obj.apfsDVdev)
logging.info(obj.__class__.__name__ + ' APFS Data Volume mountpoint (apfsDVmntpt) = ' + obj.apfsDVmntpt)
logging.info(obj.__class__.__name__ + ' HFS Volume devname (hfsdev) = ' + obj.hfsdev)
logging.info('')
print ' Disk Image devname = ' + obj.diskimgdev
print ' APFS Container devname (apfsCdev) = ' + obj.apfsCdev
print ' APFS Volume devname (apfsVdev) = ' + obj.apfsVdev
print ' APFS Volume mountpoint (apfsVmntpt) = ' + obj.apfsVmntpt
print ' APFS Data Volume devname (apfsDVdev) = ' + obj.apfsDVdev
print ' APFS Data Volume mountpoint (apfsDVmntpt) = ' + obj.apfsDVmntpt
print ' HFS Volume devname (hfsdev) = ' + obj.hfsdev
print ''
#
# Attach a disk image, and store the following information in obj:
# Disk Image devname, obj.diskimgdev (e.g. /dev/disk3)
# APFS Container vdevname, obj.apfsCdev (/dev/disk3s2 v.s./dev/disk4)
# APFS Volume devname, obj.apfsVdev (e.g. /dev/disk4s1)
# APFS Volume mountpoint, obj.apfsVmntpt (e.g. /Volumes/apfsvolume)
#
def do_attach(obj, dmg):
plist, err = docmd_plist(['/usr/bin/hdiutil', 'attach', '-plist', dmg])
if err:
return err
# log some information after the attach
docmd(['/usr/sbin/diskutil', 'list'])
docmd(['/sbin/mount'])
Vmntpt = ''
Vdev = ''
entity_array = plist['system-entities']
for entity in entity_array:
if entity['content-hint'] == 'Apple_HFS':
obj.hfsdev = entity['dev-entry']
elif entity['content-hint'] == 'GUID_partition_scheme':
obj.diskimgdev = entity['dev-entry']
elif entity['content-hint'] == 'Apple_APFS':
obj.apfsCdev_phys = entity['dev-entry']
obj.apfsCdev = DeviceToContainer(obj.apfsCdev_phys)
elif 'mount-point' in entity and entity['volume-kind'] == 'apfs':
Vmntpt = entity['mount-point']
Vdev = entity['dev-entry']
# Done if not APFS nor having APFS container
if obj.hfsdev != '' or obj.apfsCdev == '':
print_dev_info(obj)
return 0
# If dmg is APFS ROSV image, can get System and Data Volume device name
obj.apfsVdev, obj.apfsDVdev = ContainerToSysData(obj.apfsCdev)
if obj.apfsVdev != '' and obj.apfsDVdev != '':
obj.apfsVmntpt = DeviceToMntpt(obj.apfsVdev)
obj.apfsDVmntpt = DeviceToMntpt(obj.apfsDVdev)
elif obj.apfsVdev == '' and obj.apfsDVdev == '':
# If dmg is not an ROSV, use Vdev/Vmntpt from the attach plist
obj.apfsVdev = Vdev
obj.apfsVmntpt = Vmntpt
else:
logging.info('do_attach: something is not right')
print 'do_attach: something is not right'
err = 1
print_dev_info(obj)
return err
#
# Check if the given source image has a GroupUUID dir in Preboot
# If so, flag it so that it can be verified on the target
#
def checkGroupUUID(src):
err = do_attach(src, src.name)
if err:
logging.info('checkGroupUUID: Failed to attach')
print 'checkGroupUUID: Failed to attach'
return
preboot_dev = SysCntToRoleVdev(src.apfsCdev, 'Preboot')
if preboot_dev == '':
logging.error('No Preboot device in container %s', src.apfsCdev)
print 'No Preboot device in container %s' + src.apfsCdev
else:
group_uuid = DeviceToGroupUUID(src.apfsCdev, src.apfsVdev)
sys_uuid = DeviceToUUID(src.apfsVdev)
if group_uuid == '':
logging.info('Source image has NO GroupUUID')
print 'Source image has NO GroupUUID'
elif group_uuid != sys_uuid:
mntpt = DeviceToMntpt(preboot_dev)
err = docmd(['/bin/ls', '-ld', mntpt + '/' + group_uuid])
if err == 0:
src.flag |= FLAG_SRC_PREBOOT_GroupUUID
logging.info('Source image has GroupUUID in Preboot')
print 'Source image has GroupUUID in Preboot'
else:
logging.info('Source image does NOT have GroupUUID in Preboot')
print 'Source image does NOT have GroupUUID in Preboot'
docmd(['/usr/sbin/diskutil', 'umount', preboot_dev])
docmd(['hdiutil', 'detach', src.diskimgdev])
src.apfsCdev = ''
src.apfsVdev = ''
#================================================
# VERIFY TARGET RESULT
#================================================
#
# Verify if the resulting target volume can be unmounted, i.e. check EBUSY
#
def verify_unmount(tgt):
logging.info('Verifying if target can be unmount ...')
print 'Verifying if target can be unmount ...'
mntpt = DeviceToMntpt(tgt.apfsVdev)
if mntpt == '':
return 0
# check if the resulting target can be unmount
err = docmd(['/usr/sbin/diskutil', 'umount', tgt.apfsVdev])
if err == 0:
logging.info('Verifying unmount Done')
print 'Verifying unmount Done'
else:
logging.info('Verifying unmount Fail')
print 'Verifying unmount Fail'
return err
#
# Verify test result with fsck
#
def verify_fsck(tgt):
logging.info('Verifying result with fsck at ' + tgt.apfsVdev + '...')
print 'Verifying result with fsck at ' + tgt.apfsVdev + ' ...'
# verify with diskutil (fsck)
err = docmd(['/usr/sbin/diskutil', 'verifyvolume', tgt.apfsVdev])
if err == 0:
logging.info('Verifying result with fsck Done')
print 'Verifying result with fsck Done'
return err
#
# Check if the Preboot or Recovery volume has a directory named as System UUID.
# For Recovery volume, check if the 'com.apple.Boot.plist' file in the system UUID
# directory has 2 items with the same System UUID.
#
# Input 'Preboot' or 'Recovery' to indicate which volume
#
def verify_uuid_preboot_recovery(the_uuid, tgt, preb_or_recov):
dev = SysCntToRoleVdev(tgt.apfsCdev, preb_or_recov)
if dev == '':
logging.error('No device information for container %s', tgt.apfsCdev)
print 'No device information for container ' + tgt.apfsCdev
return 1
mntpt = DeviceToMntpt(dev)
err = docmd(['/bin/ls', '-ld', mntpt + '/' + the_uuid])
if err:
logging.error('No UUID:%s directory in %s', the_uuid, mntpt)
print 'No UUID:' + the_uuid + ' directory in ' + mntpt
return err
if preb_or_recov == 'Recovery':
# check if there is com.apple.Boot.plist file
file = mntpt + '/' + the_uuid + '/' + BootPlist
err = docmd(['/bin/ls', '-l', file])
# Okay if no com.apple.Boot.plist in Recovery Volume
if err:
docmd(['/usr/sbin/diskutil', 'umount', dev])
return 0
# If com.apple.Boot.plist is present, it should contains the
# same UUID as its directory UUID
cmd = ['/usr/bin/grep', the_uuid, file]
logging.info('call: {}'.format(cmd))
print('call: {}'.format(cmd))
grep = Popen(cmd, stdout=PIPE)
cmd = "/usr/bin/wc -l"
wcl = Popen(cmd, stdin=grep.stdout, stdout=PIPE, shell=True)
out, errmsg = wcl.communicate()
logging.info('call: {}'.format(cmd))
print('call: {}'.format(cmd))
out = out.strip()
logging.info(out)
if out != '2':
logging.error('Failed at setting Recovery Volume')
print 'Failed at setting Recovery Volume'
err = 1
docmd(['/usr/sbin/diskutil', 'umount', dev])
return err
#
# Preboot/Recovery volumes should have UUID directory named as either
# the System Volume UUID or Volume Group UUID.
#
# Recovery volume should have a file named com.apple.Boot.plist containing
# 2 items that include the System Volume UUID or Volume Group UUID
#
def verify_uuid_PrebootRecovery(tgt):
logging.info('Verifying Preboot/Recovery UUID: ')
logging.info('...... ')
print 'Verifying Preboot/Recovery UUID: '
print '...... '
if (tgt.src.flag & FLAG_SRC_PREBOOT_GroupUUID):
the_uuid = DeviceToGroupUUID(tgt.apfsCdev, tgt.apfsVdev)
else:
the_uuid = DeviceToUUID(tgt.apfsVdev)
if the_uuid == '':
logging.info('Verifying Preboot/Recovery UUID Fail: can not find UUID ')
print 'Verifying Preboot/Recovery UUID Fail: can not find UUID '
return 1
err = verify_uuid_preboot_recovery(the_uuid, tgt, 'Preboot')
if err:
logging.error('Verifying Preboot UUID Fail: at Preboot')
print 'Verifying Preboot UUID Fail: at Preboot'
return err
err = verify_uuid_preboot_recovery(the_uuid, tgt, 'Recovery')
if err:
logging.error('Verifying Recovery UUID Fail: at Recovery')
print 'Verifying Recovery UUID Fail: at Recovery'
return err
logging.info('Verifying Preboot/Recovery UUID Done')
print 'Verifying Preboot/Recovery UUID Done'
return 0
#
# Verify all APFS container/disk/volume UUID on the system
# are unique, no duplicated UUID.
#
def verify_uuid_nodup():
uuid_dict = {}
logging.info('Verifying no dup UUID ...')
print 'Verifying no dup UUID ...'
plist, err = docmd_plist(['/usr/sbin/diskutil', 'apfs', 'list', '-plist'])
if err:
return err
container_array = plist['Containers']
for c_entry in container_array:
c_uuid = c_entry['APFSContainerUUID']
if c_uuid not in uuid_dict:
uuid_dict[c_uuid] = c_entry['ContainerReference']
else:
vdev = uuid_dict[c_uuid]
logging.error('Fail Duplicated UUID: %s:%s', c_uuid, vdev)
print 'Fail Duplicated UUID: ' + c_uuid + ':' + vdev
return 1
volume_array = c_entry['Volumes']
for v_entry in volume_array:
v_uuid = v_entry['APFSVolumeUUID']
if v_uuid not in uuid_dict:
uuid_dict[v_uuid] = v_entry['DeviceIdentifier']