forked from gson1703/anita
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anita.py
executable file
·2739 lines (2487 loc) · 105 KB
/
anita.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
#
# This is the library part of Anita, the Automated NetBSD Installation
# and Test Application.
#
from __future__ import print_function
from __future__ import division
import gzip
import os
import pexpect
import re
import string
import shutil
import subprocess
import sys
import time
# Deal with gratuitous urllib naming changes in Python 3
if sys.version_info[0] >= 3:
import urllib.request as good_old_urllib
import urllib.parse as good_old_urlparse
else:
import urllib as good_old_urllib
import urlparse as good_old_urlparse
# Find a function for quoting shell commands
try:
from shlex import quote as sh_quote
except ImportError:
from pipes import quote as sh_quote
# Disable buffering of all printed messages (Python 3 only)
if sys.version_info[0] >= 3:
import functools
print = functools.partial(print, flush = True)
__version__='2.10'
# Your preferred NetBSD FTP mirror site.
# This is used only by the obsolete code for getting releases
# by number, not by the recommended method of getting them by URL.
# See http://www.netbsd.org/mirrors/#ftp for the complete list.
netbsd_mirror_url = "ftp://ftp.netbsd.org/pub/NetBSD/"
#netbsd_mirror_url = "ftp://ftp.fi.NetBSD.org/pub/NetBSD/"
# The supported architectures, and their properties.
# If an 'image_name' property is present, installation is done
# using a pre-built image of that name and a kernel from the
# 'kernel_name' list, rather than using sysinst. If multiple
# kernel names are listed, the first one present in the release
# is used.
arch_props = {
'i386': {
'qemu': {
'executable': 'qemu-system-i386',
},
'scratch_disk': 'wd1d',
'boot_from_default': 'floppy',
},
'amd64': {
'qemu': {
'executable': 'qemu-system-x86_64',
},
'scratch_disk': 'wd1d',
'memory_size': '192M',
},
'sparc': {
'qemu': {
'executable': 'qemu-system-sparc',
},
'scratch_disk': 'sd1c',
'memory_size': '64M',
},
'sparc64': {
'qemu': {
'executable': 'qemu-system-sparc64',
},
'scratch_disk': 'wd1c',
'memory_size': '128M',
},
'evbarm-earmv7hf': {
'qemu': {
'executable': 'qemu-system-arm',
'machine_default': 'vexpress-a15',
},
'image_name': 'armv7.img.gz',
'kernel_name': ['netbsd-VEXPRESS_A15.ub.gz', 'netbsd-GENERIC.ub.gz'],
'scratch_disk': None,
'memory_size': '128M',
'disk_size': '2G',
},
'evbarm-aarch64': {
'qemu': {
'executable': 'qemu-system-aarch64',
'machine_default': 'virt',
},
'image_name': 'arm64.img.gz',
'kernel_name': ['netbsd-GENERIC64.img.gz'],
'scratch_disk': 'ld5c',
'memory_size': '512M',
'disk_size': '2G',
},
'pmax': {
'gxemul': {
},
'scratch_disk': 'sd1c',
'memory_size': '128M',
},
'hpcmips': {
'gxemul': {
},
'scratch_disk': None,
},
'landisk': {
'gxemul': {
},
'scratch_disk': 'wd1d'
},
'vax': {
'simh': {
},
'scratch_disk': None,
},
'hppa': {
'qemu': {
'executable': 'qemu-system-hppa',
},
'scratch_disk': 'sd1c',
},
'macppc': {
'qemu': {
'executable': 'qemu-system-ppc',
'machine_default': 'mac99',
},
'memory_size': '256M',
'scratch_disk': 'wd1c',
},
'alpha': {
'qemu': {
'executable': 'qemu-system-alpha',
},
'boot_from_default': 'kernel',
'scratch_disk': 'wd1c',
},
}
# Filename extensions used for the installation sets in different
# versions of NetBSD
set_exts = ['.tgz', '.tar.xz']
# External command to build ISO images. This must be mkisofs to
# build the macppc ISO images.
# Several different kinds of ISO images are used for different purposes:
#
# install boot ISO
# for booting the install kernel, e.g., boot-com.iso from the i386
# distribution
#
# install sets ISO
# for holding the installation sets, e.g., the install_tmp.iso built
# by anita for i386 installation
#
# install combined ISO
# a single ISO serving both the above roles, e.g., the sparc install ISO
#
# runtime boot ISO
# for booting installed maccppc targets only
# A shared file descriptor for /dev/null
fnull = open(os.devnull, 'w')
# Return true if the given program (+args) can be successfully run
def try_program(argv):
try:
result = subprocess.call(argv, stdout = fnull, stderr = fnull)
return result == 0
except OSError:
return False
# Create a directory if missing
def mkdir_p(dir):
if not os.path.isdir(dir):
os.makedirs(dir)
# Remove a file, ignoring errors
def rm_f(fn):
try:
os.unlink(fn)
except:
pass
# Create a hard link, removing the destination first
def ln_f(src, dst):
rm_f(dst)
os.link(src, dst)
# Uncompress a file
def gunzip(src, dst):
with gzip.open(src, 'rb') as srcf:
with open(dst, 'wb') as dstf:
shutil.copyfileobj(srcf, dstf)
# Quote a shell command. This is intended to make it possible to
# manually cut and paste logged command into a shell.
def quote_shell_command(v):
s = ''
for i in range(len(v)):
if i > 0:
# Try to keep options and their arguments on the same line
if v[i - 1].startswith('-') and not v[i].startswith('-'):
s += ' '
else:
s += ' \\\n '
s += sh_quote(v[i])
return s
# Run a shell command safely and with error checking
def spawn(command, args):
print(quote_shell_command(args))
sys.stdout.flush()
ret = os.spawnvp(os.P_WAIT, command, args)
if ret != 0:
raise RuntimeError("could not run " + command)
# Subclass pexpect.spawn to add logging of expect() calls
class pexpect_spawn_log(pexpect.spawn):
def __init__(self, logf, *args, **kwargs):
self.structured_log_f = logf
return super(pexpect_spawn_log, self).__init__(*args, **kwargs)
def expect(self, pattern, *args, **kwargs):
slog(self.structured_log_f, "expect", pattern, timestamp = False);
r = pexpect.spawn.expect(self, pattern, *args, **kwargs)
slog(self.structured_log_f, "match", self.match.group(0), timestamp = False);
return r
# Subclass urllib.FancyURLopener so that we can catch
# HTTP 404 errors
class MyURLopener(good_old_urllib.FancyURLopener):
def http_error_default(self, url, fp, errcode, errmsg, headers):
raise IOError('HTTP error code %d' % errcode)
def my_urlretrieve(url, filename):
r = MyURLopener().retrieve(url, filename)
if sys.version_info >= (2, 7, 12):
# Work around https://bugs.python.org/issue27973
good_old_urllib.urlcleanup()
return r
# Download a file, cleaning up the partial file if the transfer
# fails or is aborted before completion.
def download_file(file, url, optional = False):
try:
print("Downloading", url + "...", end=' ')
sys.stdout.flush()
my_urlretrieve(url, file)
print("OK")
sys.stdout.flush()
except IOError as e:
if optional:
print("missing but optional, so that's OK")
else:
print(e)
sys.stdout.flush()
if os.path.exists(file):
os.unlink(file)
raise
# Create a file of the given size, containing NULs, without holes.
def make_dense_image(fn, size):
f = open(fn, "wb")
blocksize = 64 * 1024
while size > 0:
chunk = min(size, blocksize)
f.write(b"\000" * chunk)
size = size - chunk
f.close()
# As above but with holes
def make_sparse_image(fn, size):
f = open(fn, "wb")
f.seek(size - 1)
f.write(b"\000")
f.close()
def make_qcow2_image(fn, size):
subprocess.check_call(['qemu-img', 'create', '-f', 'qcow2', fn, str(size)])
def make_image(fn, size, format):
if format == 'dense':
f = make_dense_image
elif format == 'sparse':
f = make_sparse_image
elif format == 'qcow2':
f = make_qcow2_image
else:
raise RuntimeError("unknown image format %s" % format)
f(fn, size)
# Parse a size with optional k/M/G/T suffix and return an integer
def parse_size(size):
m = re.match(r'(\d+)([kMGT])?$', size)
if not m:
raise RuntimeError("%s: invalid size" % size)
size, suffix = m.groups()
mult = dict(k=1024, M=1024**2, G=1024**3, T=1024**4).get(suffix, 1)
return int(size) * mult
# Download "url" to the local file "file". If the file already
# exists locally, do nothing. If "optional" is true, ignore download
# failures and cache the absence of a missing file by creating a marker
# file with the extension ".MISSING".
#
# Returns true iff the file is present.
def download_if_missing_2(url, file, optional = False):
if os.path.exists(file):
return True
if os.path.exists(file + ".MISSING"):
return False
dir = os.path.dirname(file)
mkdir_p(dir)
try:
download_file(file, url, optional)
return True
except IOError:
if optional:
f = open(file + ".MISSING", "w")
f.close()
return False
else:
raise
# As above, but download a file from the download directory tree
# rooted at "urlbase" into a mirror tree rooted at "dirbase". The
# file name to download is "relfile", which is relative to both roots.
def download_if_missing(urlbase, dirbase, relfile, optional = False):
url = urlbase + relfile
file = os.path.join(dirbase, relfile)
return download_if_missing_2(url, file, optional)
def download_if_missing_3(urlbase, dirbase, relpath, optional = False):
url = urlbase + "/".join(relpath)
file = os.path.join(*([dirbase] + relpath))
return download_if_missing_2(url, file, optional)
# Map a URL to a directory name. No two URLs should map to the same
# directory.
def url2dir(url):
tail = []
def munge(match):
index = "/:+-".find(match.group())
if index != 0:
tail.append(chr(0x60 + index) + str(match.start()))
return "-"
return "work-" + re.sub("[/:+-]", munge, url) + "+" + "".join(tail)
# Inverse of the above; not used, but included just to show that the
# mapping is invertible and therefore collision-free
class InvalidDir(Exception):
pass
def dir2url(dir):
match = re.match(r"(work-)(.*)\+(.*)", dir)
work, s, tail = match.groups()
if work != 'work-':
raise InvalidDir()
s = re.sub("-", "/", s)
chars = list(s)
while True:
m = re.match(r"([a-z])([0-9]+)", tail)
if not m:
break
c, i = m.groups()
chars[int(i)] = "/:+-"[ord(c) - 0x60]
tail = tail[m.end():]
return "".join(chars)
def check_arch_supported(arch, dist_type):
if not arch in arch_props:
raise RuntimeError(("'%s' is not the name of a " + \
"supported NetBSD port") % arch)
if arch in ['i386', 'amd64'] and dist_type != 'reltree':
raise RuntimeError(("NetBSD/%s must be installed from " +
"a release tree, not an ISO") % arch)
if (arch in ['sparc', 'sparc64', 'vax']) and dist_type != 'iso':
raise RuntimeError(("NetBSD/%s must be installed from " +
"an ISO, not a release tree") % arch)
# Expect any of a set of alternatives. The *args are alternating
# patterns and actions; an action can be a string to be sent
# or a function to be called with no arguments. The alternatives
# will be expected repeatedly until the last one in the list has
# been selected.
def expect_any(child, *args):
# http://stackoverflow.com/questions/11702414/split-a-list-into-half-by-even-and-odd-elements
patterns = args[0:][::2]
actions = args[1:][::2]
while True:
r = child.expect(list(patterns))
action = actions[r]
if isinstance(action, str):
child.send(action)
else:
action()
if r == len(actions) - 1:
break
# Receive and discard (but log) input from the child or a time
# period of "seconds". This is effectively a delay like
# time.sleep(seconds), but generates more useful log output.
def gather_input(child, seconds):
try:
# This regexp will never match
child.expect("(?!)", seconds)
except pexpect.TIMEOUT:
pass
# Reverse the order of sublists of v of length sublist_len
# for which the predicate pred is true.
def reverse_sublists(v, sublist_len, pred):
# Build a list of indices in v in where a sublist satisfying
# pred begins
indices = []
for i in range(len(v) - (sublist_len - 1)):
if pred(v[i:i+sublist_len]):
indices.append(i)
# Swap list element pairs, working outside in
for i in range(len(indices) >> 1):
a = indices[i]
b = indices[-i - 1]
def swap(a, b):
v[a], v[b] = v[b], v[a]
for j in range(sublist_len):
swap(a + j, b + j)
# Reverse the order of any "-drive ... -device virtio-blk-device,..."
# option pairs in v
def reverse_virtio_drives(v):
def is_virtio_blk(sublist):
return sublist[0] == '-drive' and sublist[2] == '-device' \
and sublist[3].startswith('virtio-blk-device')
reverse_sublists(v, 4, is_virtio_blk)
# Format at set of key-value pairs as used in qemu command line options.
# Takes a sequence of tuples.
def qemu_format_attrs(attrs):
return ','.join(["%s=%s" % pair for pair in attrs])
#############################################################################
# A NetBSD version.
#
# Subclasses should define:
#
# dist_url(self)
# the top-level URL for the machine-dependent download tree where
# the version can be downloaded, for example,
# ftp://ftp.netbsd.org/pub/NetBSD/NetBSD-5.0.2/i386/
#
# mi_url(self)
# The top-level URL for the machine-independent download tree,
# for example, ftp://ftp.netbsd.org/pub/NetBSD/NetBSD-5.0.2/
#
# default_workdir(self)
# a file name component identifying the version, for use in
# constructing a unique, version-specific working directory
#
# arch(self)
# the name of the machine architecture the version is for,
# e.g., i386
def make_item(t):
d = dict(list(zip(['filename', 'label', 'install'], t[0:3])))
if isinstance(t[3], list):
d['group'] = make_set_dict_list(t[3])
else:
d['optional'] = t[3]
d['label'] = d['label'].encode('ASCII')
return d
def make_set_dict_list(list_):
return [make_item(t) for t in list_]
def flatten_set_dict_list(list_):
def item2list(item):
group = item.get('group')
if group:
return group
else:
return [item]
return sum([item2list(item) for item in list_], [])
class Version(object):
# Information about the available installation file sets. As the
# set of sets (sic) has evolved over time, this actually represents
# the union of those sets of sets, in other words, this list should
# contain all currently and historically known sets.
#
# This list is used for to determine
# - Which sets we should attempt to download
# - Which sets we should install by default
#
# Each array element is a tuple of four fields:
# - the file name
# - a regular expression matching the label used by sysinst
# (taking into account that it may differ between sysinst versions)
# - a flag indicating that the set should be installed by default
# - a flag indicating that the set is not present in all versions
#
sets = make_set_dict_list([
[ 'kern-GENERIC', 'Kernel (GENERIC)', 1, 0 ],
[ 'kern-GENERIC.NOACPI', 'Kernel \(GENERIC\.NOACPI\)', 0, 1 ],
[ 'modules', 'Kernel [Mm]odules', 1, 1 ],
[ 'base', 'Base', 1, 0 ],
[ 'etc', '(System)|(System configuration files)|(Configuration files) \(/etc\)', 1, 0 ],
[ 'comp', 'Compiler [Tt]ools', 1, 0 ],
[ 'games', 'Games', 0, 0 ],
[ 'gpufw', 'Graphics driver firmware', 1, 1 ],
[ 'man', '(Online )?Manual [Pp]ages', 0, 0 ],
[ 'misc', 'Miscellaneous', 1, 0 ],
[ 'rescue', 'Recovery [Tt]ools', 1, 1 ],
[ 'tests', 'Test programs', 1, 1 ],
[ 'text', 'Text [Pp]rocessing [Tt]ools', 0, 0 ],
[ '_x11', 'X11 sets', 0, [
['xbase', 'X11 base and clients', 0, 1 ],
['xcomp', 'X11 programming', 0, 1 ],
['xetc', 'X11 configuration', 0, 1 ],
['xfont', 'X11 fonts', 0, 1 ],
['xserver', 'X11 servers', 0, 1 ],
]],
[ '_src', 'Source (and debug )?sets', 0, [
['syssrc', 'Kernel sources', 0, 1],
['src', 'Base sources', 0, 1],
# The optionsal "es"? is because the source sets are
# displayed in a pop-up box atop the main distribution
# set list, and as of source date 2019.09.12.06.19.47,
# the "es" in "Share sources" happens to land exactly
# on top of an existing "es" from the word "Yes" in
# the underlying window.
# Curses, eager to to optimize, will reuse that
# existing "es" instead of outputting it anew, causing
# the pattern not to match if it includes the "es".
['sharesrc', 'Share sourc(es)?', 0, 1],
['gnusrc', 'GNU sources', 0, 1],
['xsrc', 'X11 sources', 0, 1],
# The final "s" in "Debug symbols" can also fall victim
# to curses optimization.
['debug', '(debug sets)|(Debug symbols?)', 0, 1],
['xdebug', '(debug X11 sets)|(X11 debug symbols)', 0, 1],
]]
])
flat_sets = flatten_set_dict_list(sets)
def __init__(self, sets = None):
self.tempfiles = []
if sets is not None:
if not any([re.match('kern-', s) for s in sets]):
raise RuntimeError("no kernel set specified")
# Create a Python set containing the names of the NetBSD sets we
# want for O(1) lookup. Yes, the multiple meansings of the word
# "set" here are confusing.
sets_wanted = set(sets)
for required in ['base', 'etc']:
if not required in sets_wanted:
raise RuntimeError("the '%s' set is required", required)
for s in self.flat_sets:
s['install'] = (s['filename'] in sets_wanted)
sets_wanted.discard(s['filename'])
if len(sets_wanted):
raise RuntimeError("no such set: " + sets_wanted.pop())
def set_workdir(self, dir):
self.workdir = dir
# The directory where we mirror files needed for installation
def download_local_mi_dir(self):
return self.workdir + "/download/"
def download_local_arch_dir(self):
return self.download_local_mi_dir() + self.arch() + "/"
# The path to the install sets ISO image, which
# may or may not also be the install boot ISO
def install_sets_iso_path(self):
return os.path.join(self.workdir, self.install_sets_iso_name())
# The path to the ISO used for booting an installed
# macppc system (not to be confused with the installation
# boot ISO)
def runtime_boot_iso_path(self):
return os.path.join(self.workdir, 'boot.iso')
# The directory for the install floppy images
def floppy_dir(self):
return os.path.join(self.download_local_arch_dir(),
"installation/floppy")
def boot_iso_dir(self):
return os.path.join(self.download_local_arch_dir(),
"installation/cdrom")
def boot_from_default(self):
return arch_props[self.arch()].get('boot_from_default')
def xen_kernel(self, type):
if type == 'pvh':
return 'netbsd-GENERIC.gz'
arch = self.arch()
if arch == 'i386':
return 'netbsd-XEN3PAE_DOMU.gz'
elif arch == 'amd64':
return 'netbsd-XEN3_DOMU.gz'
else:
return None
def xen_install_kernel(self, type):
if type == 'pvh':
return 'netbsd-INSTALL.gz'
arch = self.arch()
if arch == 'i386':
return 'netbsd-INSTALL_XEN3PAE_DOMU.gz'
elif arch == 'amd64':
return 'netbsd-INSTALL_XEN3_DOMU.gz'
else:
return None
# The list of boot floppies we should try downloading;
# not all may actually exist. amd64 currently has five,
# i386 has three, and older versions may have fewer.
# Add a couple extra to accomodate future growth.
def potential_floppies(self):
return ['boot-com1.fs'] + ['boot%i.fs' % i for i in range(2, 8)]
# The list of boot floppies we actually have
def floppies(self):
return [f for f in self.potential_floppies() \
if os.path.exists(os.path.join(self.floppy_dir(), f))]
# The list of boot ISOs we should try downloading
def boot_isos(self):
return ['boot-com.iso']
def cleanup(self):
for fn in self.tempfiles:
try:
os.unlink(fn)
except:
pass
def set_path(self, setname, ext):
if re.match(r'.*src$', setname):
return ['source', 'sets', setname + ext]
else:
return [self.arch(), 'binary', 'sets', setname + ext]
# Download this release
# The ISO class overrides this to download the ISO only
def download(self):
# Optimization of file:// URLs is disabled for now; it doesn't
# work for the source sets.
#if hasattr(self, 'url') and self.url[:7] == 'file://':
# mkdir_p(os.path.join(self.workdir, 'download'))
# if not os.path.lexists(os.path.join(self.workdir, 'download', self.arch())):
# os.symlink(self.url[7:], os.path.join(self.workdir, 'download', self.arch()))
# return
# Deal with architectures that we don't know how to install
# using sysinst, but instead use a pre-installed image
if 'image_name' in arch_props[self.arch()]:
download_if_missing_3(self.dist_url(), self.download_local_arch_dir(), ["binary", "gzimg", arch_props[self.arch()]['image_name']])
for file in arch_props[self.arch()]['kernel_name']:
if download_if_missing_3(self.dist_url(), self.download_local_arch_dir(), ["binary", "kernel", file], True):
break
# Nothing more to do as we aren't doing a full installation
return
if self.arch() == 'hpcmips':
download_if_missing_3(self.dist_url(), self.download_local_arch_dir(), ["installation", "netbsd.gz"])
if self.arch() in ['hpcmips', 'landisk', 'macppc', 'alpha']:
download_if_missing_3(self.dist_url(), self.download_local_arch_dir(), ["binary", "kernel", "netbsd-GENERIC.gz"])
if self.arch() in ['macppc']:
download_if_missing_3(self.dist_url(), self.download_local_arch_dir(), ["binary", "kernel", "netbsd-INSTALL.gz"])
if self.arch() in ['alpha']:
# Consistency would be nice
download_if_missing_3(self.dist_url(), self.download_local_arch_dir(), ["installation", "instkernel", "netbsd.gz"])
if self.arch() in ['i386', 'amd64']:
# This is used when netbooting only, and marked optional
# so that we can still install NetBSD 4.0 where it doesn't
# exist yet.
download_if_missing_3(self.dist_url(), self.download_local_arch_dir(), ["installation", "misc", "pxeboot_ia32.bin"], True)
i = 0
# Depending on the NetBSD version, there may be two or more
# boot floppies. Treat any floppies past the first two as
# optional files.
for floppy in self.potential_floppies():
download_if_missing_3(self.dist_url(),
self.download_local_arch_dir(),
["installation", "floppy", floppy],
True)
i = i + 1
for bootcd in (self.boot_isos()):
download_if_missing_3(self.dist_url(),
self.download_local_arch_dir(),
["installation", "cdrom", bootcd],
True)
# For noemu
download_if_missing_3(self.dist_url(),
self.download_local_arch_dir(),
["installation", "misc", "pxeboot_ia32.bin"],
True)
download_if_missing_3(self.dist_url(),
self.download_local_arch_dir(),
["binary", "kernel", "netbsd-INSTALL.gz"],
True)
for set in self.flat_sets:
if set['install']:
present = [
download_if_missing_3(self.mi_url(),
self.download_local_mi_dir(),
self.set_path(set['filename'],
ext),
True)
for ext in set_exts
]
if not set['optional'] and not any(present):
raise RuntimeError('install set %s does not exist with extension %s' %
(set['filename'], ' nor '.join(set_exts)))
# Create an ISO image
def make_iso(self, image, dir):
mkisofs = ["mkisofs", "-r", "-o"]
if self.arch() == 'macppc':
# Need to use mkisofs for HFS support
makefs = ["mkisofs", "-r", "-hfs", "-part", "-l", "-J", "-N", "-o"]
else:
# Prefer native tools
if os.uname()[0] == 'NetBSD':
makefs = ["/usr/sbin/makefs", "-t", "cd9660", "-o", "rockridge"]
elif os.uname()[0] == 'FreeBSD':
makefs = mkisofs
elif os.uname()[0] == 'Darwin':
makefs = ["hdiutil", "makehybrid", "-iso", "-o"]
else:
# Linux distributions differ. Ubuntu has genisoimage
# and mkisofs (as an alias of genisoimage); CentOS has
# mkisofs only. Debian 7 has genisoimage only.
if os.path.isfile('/usr/bin/genisoimage'):
makefs = ["genisoimage", "-r", "-o"]
else:
makefs = mkisofs
spawn(makefs[0], makefs + [image, dir])
# Create the install sets ISO image
def make_install_sets_iso(self):
self.download()
if self.arch() == 'macppc':
gunzip(os.path.join(self.download_local_arch_dir(), 'binary/kernel/netbsd-INSTALL.gz'),
os.path.join(self.download_local_mi_dir(), 'netbsd-INSTALL'))
self.make_iso(self.install_sets_iso_path(),
os.path.dirname(os.path.realpath(os.path.join(self.download_local_mi_dir(), self.arch()))))
self.tempfiles.append(self.install_sets_iso_path())
# Create the runtime boot ISO image (macppc only)
def make_runtime_boot_iso(self):
# The ISO will contain only the GENERIC kernel
d = os.path.join(self.workdir, 'runtime_boot_iso')
mkdir_p(d)
gunzip(os.path.join(self.download_local_arch_dir(), 'binary/kernel/netbsd-GENERIC.gz'),
os.path.join(d, 'netbsd-GENERIC'))
self.make_iso(self.runtime_boot_iso_path(), d)
# Do not add the ISO to self.tempfiles as it's needed after the install.
# Get the architecture name. This is a hardcoded default for use
# by the obsolete subclasses; the "URL" class overrides it.
def arch(self):
return "i386"
# Backwards compatibility with Anita 1.2 and older
def install(self):
Anita(dist = self).install()
def boot(self):
Anita(dist = self).boot()
def interact(self):
Anita(dist = self).interact()
# Subclass for versions where we pass in the version number explicitly
# Deprecated, use anita.URL instead
class NumberedVersion(Version):
def __init__(self, ver, **kwargs):
Version.__init__(self, **kwargs)
self.ver = ver
# The file name of the install ISO (sans directory)
def install_sets_iso_name(self):
if re.match("^[3-9]", self.ver) is not None:
return "i386cd-" + self.ver + ".iso"
else:
return "i386cd.iso"
# The directory for files related to this release
def default_workdir(self):
return "netbsd-" + self.ver
# An official NetBSD release
# Deprecated, use anita.URL instead
class Release(NumberedVersion):
def __init__(self, ver, **kwargs):
NumberedVersion.__init__(self, ver, **kwargs)
pass
def mi_url(self):
return netbsd_mirror_url + "NetBSD-" + self.ver + "/"
def dist_url(self):
return self.mi_url() + self.arch() + "/"
# The top-level URL of a release tree
class URL(Version):
def __init__(self, url, **kwargs):
Version.__init__(self, **kwargs)
self.url = url
match = re.match(r'(^.*/)([^/]+)/$', url)
if match is None:
raise RuntimeError(("URL '%s' doesn't look like the URL of a " + \
"NetBSD distribution") % url)
self.url_mi_part = match.group(1)
self.m_arch = match.group(2)
check_arch_supported(self.m_arch, 'reltree')
def dist_url(self):
return self.url
def mi_url(self):
return self.url_mi_part
def install_sets_iso_name(self):
return "install_tmp.iso"
def default_workdir(self):
return url2dir(self.url)
def arch(self):
return self.m_arch
# A local release directory
class LocalDirectory(URL):
def __init__(self, dir, **kwargs):
# This could be optimized to avoid copying the files
URL.__init__(self, "file://" + dir, **kwargs)
# An URL or local file name pointing at an ISO image
class ISO(Version):
def __init__(self, iso_url, **kwargs):
Version.__init__(self, **kwargs)
if re.match(r'/', iso_url):
self.m_iso_url = "file://" + iso_url
self.m_iso_path = iso_url
else:
self.m_iso_url = iso_url
self.m_iso_path = None
# We can't determine the final ISO file name yet because the work
# directory is not known at this point, but we can precalculate the
# basename of it.
self.m_iso_basename = os.path.basename(
good_old_urllib.url2pathname(good_old_urlparse.urlparse(iso_url)[2]))
m = re.match(r"(.*)cd.*iso|NetBSD-[0-9\._A-Z]+-(.*).iso", self.m_iso_basename)
if m is None:
raise RuntimeError("cannot guess architecture from ISO name '%s'"
% self.m_iso_basename)
if m.group(1) is not None:
self.m_arch = m.group(1)
if m.group(2) is not None:
self.m_arch = m.group(2)
check_arch_supported(self.m_arch, 'iso')
def install_sets_iso_path(self):
if self.m_iso_path is not None:
return self.m_iso_path
else:
return os.path.join(self.download_local_arch_dir(),
self.m_iso_basename)
def default_workdir(self):
return url2dir(self.m_iso_url)
def make_install_sets_iso(self):
self.download()
def download(self):
if self.m_iso_path is None:
download_if_missing_2(self.m_iso_url, self.install_sets_iso_path())
else:
mkdir_p(self.workdir)
def arch(self):
return self.m_arch
def boot_from_default(self):
return 'cdrom-with-sets'
# Virtual constructior that accepts a release URL, ISO, or local path
# and constructs an URL, ISO, or LocalDirectory object as needed.
def distribution(distarg, **kwargs):
if re.search(r'\.iso$', distarg):
return ISO(distarg, **kwargs)
elif re.match(r'/', distarg):
if not re.search(r'/$', distarg):
raise RuntimeError("distribution directory should end in a slash")
return LocalDirectory(distarg, **kwargs)
elif re.match(r'[a-z0-9\.0-]+:', distarg):
if not re.search(r'/$', distarg):
raise RuntimeError("distribution URL should end in a slash")
return URL(distarg, **kwargs)
else:
raise RuntimeError("expected distribution URL or directory, got " + distarg)
#############################################################################
def vmm_is_xen(vmm):
return vmm == 'xm' or vmm == 'xl'
# Log a message to the structured log file "fd".
def slog(fd, tag, data, timestamp = True):
if timestamp:
print("%s(%.3f, %s)" % (tag, time.time(), repr(data)), file=fd)
else:
print("%s(%s)" % (tag, repr(data)), file=fd)
fd.flush()
def slog_info(fd, data):
slog(fd, 'info', data)
# A file-like object that escapes unprintable data and prefixes each
# line with a tag, for logging I/O.
class Logger(object):
def __init__(self, tag, fd):
self.tag = tag
self.fd = fd
def write(self, data):
slog(self.fd, self.tag, data)
def __getattr__(self, name):
return getattr(self.fd, name)
# Logger veneer that hides the data sent, for things like passwords and entropy
class CensorLogger(object):
def __init__(self, fd):
self.fd = fd
def write(self, data):
self.fd.write(b'*' * len(data))
def __getattr__(self, name):
return getattr(self.fd, name)
# http://stackoverflow.com/questions/616645/how-do-i-duplicate-sys-stdout-to-a-log-file-in-python
class multifile(object):
def __init__(self, files):
self._files = files
def __getattr__(self, attr, *args):
return self._wrap(attr, *args)
def _wrap(self, attr, *args):
def g(*a, **kw):
for f in self._files:
res = getattr(f, attr, *args)(*a, **kw)
return res
return g
class BytesWriter(object):
def __init__(self, fd):
self.fd = fd
def write(self, data):
self.fd.buffer.write(data)
def __getattr__(self, name):
return getattr(self.fd, name)
# Convert binary data to a hexadecimal string
if sys.version_info[0] >= 3:
def bytes2hex(s):
return s.hex()
else:
def bytes2hex(s):
return s.encode('hex')