-
Notifications
You must be signed in to change notification settings - Fork 4
/
eliloader.py
executable file
·1168 lines (974 loc) · 41.7 KB
/
eliloader.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/python
# Copyright (c) 2011 Citrix Systems, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only. with the special
# exception on linking described in file LICENSE.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
##
# Bootloader for EL-based distros that support Xen.
#
# We keep all logic for booting these distros contained within this file
# where possible.
# Some brief documentation of the other-config keys this tool knows about:
#
# install-repository: Required. Path to a repository; 'http', 'https', or
# 'nfs'. Should be specified as would be used by the target installer, not
# including prefixes, e.g. method=.
#
# install-vnc: Default: false. Use VNC where available during the
# installation.
#
# install-vncpasswd: Default: empty. The VNC password to use, when providing
# one is possible via the command-line of the target distro
#
# install-round: Default: 1. The current bootloader round. Not to be edited
# by the user
#
# install-distro: Default: 'rhlike'. The general distribution type. Currently
# supported values are 'rhlike', 'sleslike', and 'debianlike'.
#
# install-arch: Default: i386. The architecture to install.
import sys
import subprocess
import os
import os.path
import shutil
import getopt
import tempfile
import urllib2
import traceback
import logging
import re
import itertools
import XenAPI
import xcp.cmd
import xcp.logger
from xen.lowlevel import xs
sys.path.append("/usr/lib/python")
BOOTDIR = "/var/run/xend/boot"
PYGRUB_PATH = "/usr/bin/pygrub"
PYGRUB_SIMPLE_FORMAT = "--output-format=simple"
PYGRUB_CMD = [PYGRUB_PATH, PYGRUB_SIMPLE_FORMAT]
DEBUG_SWITCH = "/var/run/nonpersistent/linux-guest-loader.debug"
PROGRAM_NAME = "eliloader"
never_latch = False
# Set this if you want 2nd round booting to never stop.
class PygrubError(Exception):
def __init__(self, rc, err):
# Pygrub reports errors with a Runtime exception.
m = re.search('RuntimeError: (.*)$', err)
self.value = "Pygrub error (%d): %s" % (rc, m.group(0))
def __str__(self):
return repr(self.value)
RPC_SUCCESS = "Success"
(
DISTRO_RHLIKE,
DISTRO_SLESLIKE,
DISTRO_DEBIANLIKE,
DISTRO_PYGRUB # Distro media bootable via pygrub
) = range(4)
distros = { "rhlike" : DISTRO_RHLIKE, "sleslike" : DISTRO_SLESLIKE, "debianlike": DISTRO_DEBIANLIKE, "pygrub" : DISTRO_PYGRUB }
rounds = {
DISTRO_RHLIKE: 2, DISTRO_SLESLIKE: 2, DISTRO_DEBIANLIKE: 1, DISTRO_PYGRUB: 1
}
guest_installer_dir = "/opt/xensource/packages/files/guest-installer"
mapfiles = []
if os.path.exists(guest_installer_dir):
mapfiles = [ f for f in os.listdir(guest_installer_dir) if f.endswith('.map') ]
# We can sometimes tweak an installer's initrd to give it extra features, e.g.
# CD installs in PV guests. These dictionaries specify the cpio archive used
# as a source for adding files from given an initrd whose md5sum when taken
# directly from the vendor's CD as the key. Note that we use cpio archives
# because although it doesn't seem to be supported yet, it might that in future
# we can simply cat multiple archives together into a single image, and the
# Linux loader will do the right thing.
# Later initrds are cpio.gz archives
cpio_initrd_fixups = {}
# Earlier initrds are ext2.gz filesystems
ext2_initrd_fixups = {}
# Update cpio_initrd_fixups[] and ext2_initrd_fixups[] from the map files dumped
# in guest_installer_dir by the *-guest-installer components
for f in mapfiles:
fd = open(os.path.join(guest_installer_dir, f))
lineno = 0
for line in fd:
lineno += 1
line = line.strip()
if len(line) == 0 or line.startswith('#'):
continue
try:
initrd_md5sum, initrd_type, overlay_fname, distro = line.split(None, 3)
except:
raise Exception, "missing field in file %s/%s line %d" % (guest_installer_dir, fd.name, lineno)
if initrd_type == "cpio":
cpio_initrd_fixups[initrd_md5sum] = overlay_fname
elif initrd_type == "ext2":
ext2_initrd_fixups[initrd_md5sum] = overlay_fname
else:
raise Exception, "incorrect initrd_type in file %s/%s line %d: must be cpio or ext2" % \
(guest_installer_dir, fd.name, lineno)
fd.close()
pv_kernel_max_size = 32 * 1024 * 1024
pv_initrd_max_size = 128 * 1024 * 1024
copy_block_size = 1 * 1024 * 1024
#### EXCEPTIONS
class UsageError(Exception):
pass
class APILevelException(Exception):
exname = "INTERNAL_ERROR"
def apifmt(self):
rc = self.exname + "\n"
for a in self.args:
rc += a + "\n"
return rc
class UnsupportedInstallMethod(APILevelException):
exname = "UNSUPPORTED_INSTALL_METHOD"
class SupportPackageMissing(APILevelException):
exname = "SUPPORT_PACKAGE_MISSING"
class InvalidSource(APILevelException):
exname = "INVALID_SOURCE"
class ResourceTooLarge(APILevelException):
exname = "LIMITS"
class ResourceAccessError(Exception):
def __init__(self, source):
self.source = source
class MountFailureException(Exception):
pass
##### UTILITY FUNCTIONS
def mount(dev, mountpoint, options = None, fstype = None):
cmd = ['/bin/mount']
if options:
assert type(options) == list
if fstype:
cmd.append('-t')
cmd.append(fstype)
if options:
cmd.append("-o")
cmd.append(",".join(options))
cmd.append(dev)
cmd.append(mountpoint)
rc = xcp.cmd.runCmd(cmd, False, False)
if rc != 0:
raise MountFailureException, cmd
def umount(mountpoint):
xcp.cmd.runCmd(["umount", mountpoint])
def get_decompressor(filename):
archive = open(filename)
header = archive.read(2)
archive.close()
if header == "\037\213": # Gzip compressed
return ["/bin/zcat"]
elif header == "\x5d\x00": # Lzma compressed
return ["/usr/bin/xzcat", "--format=lzma"]
else: # Assume uncompressed
return None
# Copy from one fd to another
def copyfd(fromfd, tofd, limit):
bytes_so_far = 0
while bytes_so_far <= limit:
block = fromfd.read(copy_block_size)
l = len(block)
if l == 0:
break
bytes_so_far += l
tofd.write(block)
else:
return bytes_so_far, False
return bytes_so_far, True
# Creation of an NfsRepo object triggers a mount, and the mountpoint is stored int obj.mntpoint.
# The umount is done automatically when the object goes out of scope
class NfsRepo:
# repo is nfs:server:/path/to/repo or nfs://server/path/to/repo or nfs://server:/path/to/repo
def __init__(self, repo):
self.mntpoint = None
xcp.logger.debug("Mounting NFS repo " + repo)
# we deal with RHEL-like NFS paths - if it's a SLES one then
# turn it into something we can understand first:
if repo.startswith("nfs://"):
rest = repo[6:]
if not "/" in rest:
raise InvalidSource, "NFS path was not in a valid format"
server, dir = rest.split("/", 1)
dir = "/" + dir
server = server.rstrip(":")
else:
# work out the components:
[_, server, dir] = repo.split(':', 2)
if dir[0] != '/':
raise InvalidSource, "Directory part of NFS path was not an absolute path."
# make a mountpoint:
self.mntpoint = tempfile.mkdtemp(dir = '/tmp', prefix = 'nfs-repo-')
try:
mount('%s:%s' % (server, dir), self.mntpoint, fstype = "nfs", options = ['ro'])
except MountFailureException, e:
# Mount failed. Re-raise as InvalidSource.
umount(self.mntpoint)
os.rmdir(self.mntpoint)
self.mntpoint = None
raise InvalidSource, "nfs repo %s" % repo
def __del__(self):
# if we're getting called due to an unhandled exception, the
# os module may have already been unloaded
import os
if self.mntpoint:
umount(self.mntpoint)
os.rmdir(self.mntpoint)
# Creation of an CdromRepo object triggers a mount, and the mountpoint is stored int obj.mntpoint.
# The umount is done automatically when the object goes out of scope
class CdromRepo:
# img is a dev node
def __init__(self, img):
# make a mountpoint:
xcp.logger.debug("Mounting CD repo " + img)
self.mntpoint = tempfile.mkdtemp(dir = '/tmp', prefix = 'cdrom-repo-')
try:
mount(img, self.mntpoint, fstype = "iso9660", options = ['ro'])
except MountFailureException, e:
# Mount failed. Re-raise as InvalidSource.
umount(self.mntpoint)
os.rmdir(self.mntpoint)
self.mntpoint = None
raise InvalidSource, "cdrom repo %s" % img
def __del__(self):
# if we're getting called due to an unhandled exception, the
# os module may have already been unloaded
import os
if self.mntpoint:
umount(self.mntpoint)
os.rmdir(self.mntpoint)
# Modified from host-installer.hg/util.py
# source may be
# http://blah
# ftp://blah
# file://blah
#
# Raises ResourceAccessError or InvalidSource.
#
def fetchFile(source, dest, limit):
if source[:5] != 'http:' and source[:5] != 'file:' and source[:4] != 'ftp:':
raise InvalidSource, "Unknown source type."
# This something that can be fetched using urllib2
xcp.logger.debug("Fetching '%s' to '%s'" % (source, dest))
# Actually get the file
try:
fd = urllib2.urlopen(source)
try:
length = int(fd.info().getheader('content-length', None))
except (ValueError, TypeError):
length = None
# Catch various errors and reraise as ResourceAccessError
# urlopen can raise OSError if a file:// URL is not found,
# HTTPError for HTTP error response codes,
# URLError for network issues, bad hostname, malformed URL, etc., and
# IOError for some FTP errors.
except (OSError, urllib2.HTTPError, urllib2.URLError, IOError):
log_exception("ERROR: ", traceback.format_exc())
raise ResourceAccessError(source)
fd_dest = open(dest, 'wb')
dest_len, success = copyfd(fd, fd_dest, limit)
dbg = ""
if length is not None:
dbg = " expecting %d bytes, " % (length, )
xcp.logger.debug(dbg + "got %d bytes, limit %d bytes" % (dest_len, limit))
fd_dest.close()
fd.close()
if not success:
raise ResourceTooLarge("File '%s' exceeds limit of %d bytes"
% (source, limit))
if length is not None and length != dest_len:
raise IOError("Closed connection during download")
# Test existence of a file
# just return True for "exists" or False for "does not exist"
#
# Raises InvalidSource.
def checkFile(source):
if source[:5] != 'http:' and source[:5] != 'file:' and source[:4] != 'ftp:':
raise InvalidSource, "Unknown source type."
# This something that can be fetched using urllib2
xcp.logger.debug("Checking " + source)
try:
request = urllib2.Request(source)
if source[:5] == 'http:':
request.get_method = lambda : 'HEAD'
fd = urllib2.urlopen(request)
fd.close()
return True
except StandardError:
return False
def close_mkstemp(dir = None, prefix = 'tmp'):
fd, name = tempfile.mkstemp(dir = dir, prefix = prefix)
os.close(fd)
return name
def canonicaliseOtherConfig(vm_uuid):
session = XenAPI.xapi_local()
session.login_with_password("", "", "", PROGRAM_NAME)
try:
vm = session.xenapi.VM.get_by_uuid(vm_uuid)
other_config = session.xenapi.VM.get_other_config(vm)
finally:
session.logout()
def collect(d, k, default = None):
if d.has_key(k):
return d[k]
else:
return default
rc = { 'install-repository': collect(other_config, 'install-repository'),
'install-vnc': collect(other_config, 'install-vnc', "false") in ["1", "true"],
'install-vncpasswd': collect(other_config, 'install-vncpasswd'),
'install-distro': collect(other_config, 'install-distro', 'rhlike'),
'install-round': collect(other_config, 'install-round', '1'),
'install-arch': collect(other_config, 'install-arch', 'i386'),
'install-args': collect(other_config, 'install-args', None),
'install-kernel': collect(other_config, 'install-kernel', None),
'install-ramdisk': collect(other_config, 'install-ramdisk', None),
'install-proxy': collect(other_config, 'install-proxy', None),
'debian-release': collect(other_config, 'debian-release') }
return rc
def propagatePostinstallLimits(session, vm):
platform = session.xenapi.VM.get_platform(vm)
try:
key_from = "pv-postinstall-kernel-max-size"
key_to = "pv-kernel-max-size"
if key_from in platform:
session.xenapi.VM.remove_from_platform(vm, key_to)
session.xenapi.VM.add_to_platform(vm, key_to, platform[key_from])
session.xenapi.VM.remove_from_platform(vm, key_from)
except StandardError:
pass
try:
key_from = "pv-postinstall-ramdisk-max-size"
key_to = "pv-ramdisk-max-size"
if key_from in platform:
session.xenapi.VM.remove_from_platform(vm, key_to)
session.xenapi.VM.add_to_platform(vm, key_to, platform[key_from])
session.xenapi.VM.remove_from_platform(vm, key_from)
except StandardError:
pass
def switchBootloader(vm_uuid, target_bootloader = "pygrub"):
if never_latch: return
session = XenAPI.xapi_local()
session.login_with_password("", "", "", PROGRAM_NAME)
try:
xcp.logger.debug("Switching to " + target_bootloader)
vm = session.xenapi.VM.get_by_uuid(vm_uuid)
session.xenapi.VM.set_PV_bootloader(vm, target_bootloader)
propagatePostinstallLimits(session, vm)
finally:
session.logout()
def unpack_cpio_initrd(filename, working_dir):
xcp.logger.debug("Unpacking cpio '%s' into '%s'" % (filename, working_dir))
prog = get_decompressor(filename)
if prog is not None:
decomp = subprocess.Popen(prog + [filename], stdout = subprocess.PIPE)
source = decomp.stdout
else:
source = open(filename)
cpio = subprocess.Popen(["/bin/cpio", "-idu", "--quiet"], cwd = working_dir,
stdin = subprocess.PIPE)
dest_len, success = copyfd(source, cpio.stdin, pv_initrd_max_size)
xcp.logger.debug(" got %d bytes, limit %d bytes" % (dest_len, pv_initrd_max_size))
cpio.stdin.close()
cpio.wait()
source.close()
if prog is not None:
decomp.wait()
if not success:
raise ResourceTooLarge("Unpacking cpio '%s' exceeds limit of %d bytes"
% (filename, pv_initrd_max_size))
def mount_ext2_initrd(infile, outfile, working_dir):
xcp.logger.debug("Mounting ext2 '%s' on '%s'" % (infile, outfile))
prog = get_decompressor(infile)
if prog is not None:
decomp = subprocess.Popen(prog + [infile], stdout = subprocess.PIPE)
source = decomp.stdout
else:
source = open(infile)
dest = open(outfile, "w")
dest_len, success = copyfd(source, dest, pv_initrd_max_size)
xcp.logger.debug(" got %d bytes, limit %d bytes" % (dest_len, pv_initrd_max_size))
dest.close()
source.close()
if prog is not None:
decomp.wait()
if not success:
raise ResourceTooLarge("Unpacking cpio '%s' exceeds limit of %d bytes"
% (infile, pv_initrd_max_size))
mount(outfile, working_dir, options = ['loop'])
def md5sum(filename):
p = subprocess.Popen(["md5sum", filename], stdout=subprocess.PIPE)
stdout, _ = p.communicate()
if p.returncode != 0:
raise InvalidSource("md5sum command failed.")
return stdout.split()[0]
def log_exception(prefix, backtrace):
for line in backtrace.strip().split("\n"):
xcp.logger.debug(prefix + line)
#### INITRD TWEAKING
def mkcpio(working_dir, output_file):
""" Make a cpio archive containg the files in working_dir, writing the
archive to output_file. It will be uncompressed. """
xcp.logger.debug("Building initrd from " + working_dir)
# set output_file to be a full path so that we don't create the output
# file under the new working directory of the cpio process.
output_file = os.path.realpath(output_file)
cpio = subprocess.Popen(["/bin/cpio", "-F", output_file, "-oH", "newc",
"--quiet"], cwd = working_dir,
stdin = subprocess.PIPE, stdout = None)
for root, ds, files in os.walk(working_dir):
assert root.startswith(working_dir), "Root of current walk path starts with original walk path"
base = root[len(working_dir) + 1:]
for f in files + ds:
path = os.path.join(base, f)
cpio.stdin.write(path + "\n")
cpio.communicate()
def tweak_initrd(filename):
""" Patch an initrd with custom files if they are available. Returns the
filename of a patched initrd that should be used instead of the file as
passed in as filename. The caller is responsible for removing the old
version of the initrd. """
digest = md5sum(filename)
initrd_path = None
_initrd_path = None
xcp.logger.debug(filename + " has MD5 " + digest)
if cpio_initrd_fixups.has_key(digest):
# we can patch this initrd, let's unpack it to a temporary directory:
xcp.logger.debug("Fixup with " + cpio_initrd_fixups[digest])
working_dir = tempfile.mkdtemp(dir = "/tmp", prefix = "initrd-fixup-")
cpio_overlay = os.path.join(guest_installer_dir, cpio_initrd_fixups[digest])
if not os.path.isfile(cpio_overlay):
raise SupportPackageMissing, "Dom0 does not contain a required file: %s" % cpio_overlay
try:
try:
# unpack the vendor initrd, then unpack our changes over it:
unpack_cpio_initrd(filename, working_dir)
unpack_cpio_initrd(cpio_overlay, working_dir)
# now repack to make the final image:
_initrd_path = close_mkstemp(dir = BOOTDIR, prefix="tweaked-initrd-")
mkcpio(working_dir, _initrd_path)
except:
xcp.logger.debug("Cleaning '%s' and '%s'" % (working_dir, _initrd_path))
raise
else:
initrd_path = _initrd_path
_initrd_path = None
finally:
# clean up the working_dir tree
shutil.rmtree(working_dir)
if _initrd_path:
os.unlink(_initrd_path)
elif ext2_initrd_fixups.has_key(digest):
# we can patch this initrd, let's unpack it to a temporary directory:
working_dir = tempfile.mkdtemp(dir = "/tmp", prefix = "initrd-fixup-")
cpio_overlay = os.path.join(guest_installer_dir, ext2_initrd_fixups[digest])
if not os.path.isfile(cpio_overlay):
raise SupportPackageMissing, "Dom0 does not contain a required file: %s" % cpio_overlay
try:
try:
# unpack the vendor initrd, then unpack our changes over it:
_initrd_path = close_mkstemp(dir = BOOTDIR, prefix="tweaked-initrd-")
mount_ext2_initrd(filename, _initrd_path, working_dir)
unpack_cpio_initrd(cpio_overlay, working_dir)
except:
xcp.logger.debug("Cleaning '%s' and '%s'" % (working_dir, _initrd_path))
raise
else:
initrd_path = _initrd_path
_initrd_path = None
finally:
umount(working_dir)
shutil.rmtree(working_dir)
if _initrd_path:
os.unlink(_initrd_path)
return initrd_path
def tweak_bootable_disk(vm):
if never_latch: return
session = XenAPI.xapi_local()
session.xenapi.login_with_password("", "", "", PROGRAM_NAME)
try:
# get all VBDs, set bootable = (device == 0):
vm_ref = session.xenapi.VM.get_by_uuid(vm)
vbds = session.xenapi.VM.get_VBDs(vm_ref)
for vbd in vbds:
session.xenapi.VBD.set_bootable(vbd, session.xenapi.VBD.get_userdevice(vbd) == "0")
finally:
session.logout()
##### DISTRO-SPECIFIC CODE
def rhel_first_boot_handler(vm, repo_url):
need_clean = True
if checkFile(repo_url + "images/xen/vmlinuz"):
vmlinuz_suburl = "images/xen/vmlinuz"
ramdisk_suburl = "images/xen/initrd.img"
else:
vmlinuz_suburl = "isolinux/vmlinuz"
ramdisk_suburl = "isolinux/initrd.img"
vmlinuz_file = close_mkstemp(dir = BOOTDIR, prefix = "vmlinuz-")
ramdisk_file = close_mkstemp(dir = BOOTDIR, prefix = "ramdisk-")
# download the kernel and ramdisk:
vmlinuz_url = repo_url + vmlinuz_suburl
ramdisk_url = repo_url + ramdisk_suburl
try:
try:
fetchFile(vmlinuz_url, vmlinuz_file, pv_kernel_max_size)
fetchFile(ramdisk_url, ramdisk_file, pv_initrd_max_size)
modified_ramdisk = tweak_initrd(ramdisk_file)
if modified_ramdisk:
os.unlink(ramdisk_file)
ramdisk_file = modified_ramdisk
except:
xcp.logger.debug("Cleaning '%s' and '%s'" % (vmlinuz_file, ramdisk_file))
raise
else:
need_clean = False
finally:
if need_clean:
os.unlink(vmlinuz_file)
os.unlink(ramdisk_file)
return vmlinuz_file, ramdisk_file
# Return the extra arg needed by RHEL kernel for it to locate installation media
def rhel_first_boot_args(repo):
if True in [ repo.startswith(x) for x in ("http", "ftp", "nfs") ]:
if not repo.endswith("/"):
return "method=%s/" % repo
if repo == "cdrom":
return ''
return "method=%s" % repo
def sles_first_boot_handler(vm, repo_url, other_config):
# look for the xen kernel and initrd in boot first:
if other_config['install-arch'] == 'x86_64':
bootdir = 'boot/x86_64/'
kernel_fname = 'vmlinuz-xen'
initrd_fname = 'initrd-xen'
else:
bootdir = 'boot/i386/'
kernel_fname = 'vmlinuz-xenpae'
initrd_fname = 'initrd-xenpae'
vmlinuz_url = repo_url + bootdir + kernel_fname
vmlinuz_file = close_mkstemp(dir = BOOTDIR, prefix = "vmlinuz-")
ramdisk_url = repo_url + bootdir + initrd_fname
ramdisk_file = close_mkstemp(dir = BOOTDIR, prefix = "ramdisk-")
try:
fetchFile(vmlinuz_url, vmlinuz_file, pv_kernel_max_size)
fetchFile(ramdisk_url, ramdisk_file, pv_initrd_max_size)
except:
xcp.logger.debug("Cleaning '%s' and '%s'" % (vmlinuz_file, ramdisk_file))
os.unlink(vmlinuz_file)
os.unlink(ramdisk_file)
raise
return vmlinuz_file, ramdisk_file
# Return the extra arg needed by SLES kernel for it to locate installation media
def sles_first_boot_args(repo):
args = ""
if repo == "cdrom":
# this should really be "install=cd", but the sles installer interprets
# the disk as a harddrive. If/when we fix that, we will need to replace
# the following line.
args = args + " install=hd"
else:
if True in [ repo.startswith(x) for x in ("http", "ftp", "nfs") ]:
if not repo.endswith("/"):
args = args + " install=%s/" % repo
else:
args = args + " install=%s" % repo
return args;
def debian_first_boot_handler(vm, repo_url, other_config):
if not other_config.has_key('debian-release'):
raise UnsupportedInstallMethod, \
"other-config:debian-release was not set to an appropriate value, " \
"and this is required for the selected distribution type."
if not other_config.has_key('install-arch'):
raise UnsupportedInstallMethod, \
"other-config:install-arch was not set to an appropriate value, " \
"and this is required for the selected distribution type."
if other_config['install-repository'] == "cdrom":
cdrom_dirs = { 'i386': 'install.386/',
'amd64': 'install.amd/',
'x86_64': 'install.amd/' }
vmlinuz_url = repo_url + cdrom_dirs[other_config['install-arch']] + "xen/vmlinuz"
ramdisk_url = repo_url + cdrom_dirs[other_config['install-arch']] + "xen/initrd.gz"
if not checkFile(vmlinuz_url):
vmlinuz_url = repo_url + cdrom_dirs[other_config['install-arch']] + "vmlinuz"
ramdisk_url = repo_url + cdrom_dirs[other_config['install-arch']] + "initrd.gz"
if not checkFile(vmlinuz_url):
vmlinuz_url = repo_url + "install/vmlinuz"
ramdisk_url = repo_url + "install/initrd.gz"
else:
comp = repo_url.split('/dists/', 1)
if len(comp) != 2 or comp[1].replace('/','') == "":
repo_url += "dists/%s/" % other_config['debian-release']
boot_dir = "main/installer-%s/current/images/netboot/xen/" % other_config['install-arch']
vmlinuz_url = repo_url + boot_dir + "vmlinuz"
ramdisk_url = repo_url + boot_dir + "initrd.gz"
# download the kernel and ramdisk:
vmlinuz_file = close_mkstemp(dir = BOOTDIR, prefix = "vmlinuz-")
ramdisk_file = close_mkstemp(dir = BOOTDIR, prefix = "ramdisk-")
try:
fetchFile(vmlinuz_url, vmlinuz_file, pv_kernel_max_size)
fetchFile(ramdisk_url, ramdisk_file, pv_initrd_max_size)
except:
xcp.logger.debug("Cleaning '%s' and '%s'" % (vmlinuz_file, ramdisk_file))
os.unlink(vmlinuz_file)
os.unlink(ramdisk_file)
raise
# Possibly apply tweaks to initrd.
modified_ramdisk = tweak_initrd(ramdisk_file)
if modified_ramdisk:
os.unlink(ramdisk_file)
ramdisk_file = modified_ramdisk
return vmlinuz_file, ramdisk_file
def debian_first_boot_args(repo):
return ""
def pygrub_first_boot_handler(vm_uuid, repo_url, other_config):
RAMDISK = "ramdisk"
KERNEL = "kernel"
def pygrub_parse_simple(s):
# The string to parse comes from pygrub, which builds it based on
# reading and processing the grub configuration from the guest's disc.
# Therefore it may contain malicious content from the guest if pygrub
# has not cleaned it up sufficiently.
# Example of a valid three-line string to parse, with blank third line:
# kernel <kernel:/vmlinuz-2.6.18-412.el5xen>
# args ro root=/dev/VolGroup00/LogVol00 console=ttyS0,115200n8
#
valid_keys = [RAMDISK, KERNEL, "args"]
ret = {}
for line in s.splitlines():
if line == "": # pygrub always adds a blank line at the end.
continue
if " " not in line:
raise InvalidSource, "Syntax error parsing pygrub output, key value separator missing in %s" % line
key, val = line.split(" ", 1)
if key not in valid_keys:
raise InvalidSource, "Unrecognised start of line when parsing bootloader result: line=%s" % line
if ret.has_key(key):
raise InvalidSource, "More than one %s line when parsing bootloader result %s" % (key, s)
ret[key] = val
return ret
if other_config['install-repository'] == "cdrom":
(rc, out, err) = xcp.cmd.runCmd(PYGRUB_CMD + sys.argv[1:], True, True)
if rc != 0:
raise InvalidSource, "Error %d running %s" % (rc,PYGRUB_PATH)
output = pygrub_parse_simple(out)
if not output.has_key(KERNEL):
raise InvalidSource, "No kernel in pygrub output %s" % output
if not output.has_key(RAMDISK):
output[RAMDISK] = None
# Return only kernel and ramdisk, discarding the "args".
return output[KERNEL], output[RAMDISK]
else:
if not other_config.has_key('install-kernel') or other_config['install-kernel'] is None:
raise InvalidSource, "install-distro=pygrub requires install-kernel for network boot"
# download the kernel and ramdisk:
vmlinuz_url = repo_url + other_config['install-kernel']
vmlinuz_file = close_mkstemp(dir = BOOTDIR, prefix = "vmlinuz-")
if other_config.has_key('install-ramdisk') and other_config['install-ramdisk'] is not None:
ramdisk_url = repo_url + other_config['install-ramdisk']
ramdisk_file = close_mkstemp(dir = BOOTDIR, prefix = "ramdisk-")
else:
ramdisk_url = None
ramdisk_file = None
try:
fetchFile(vmlinuz_url, vmlinuz_file, pv_kernel_max_size)
if ramdisk_url is not None and ramdisk_file is not None:
fetchFile(ramdisk_url, ramdisk_file, pv_initrd_max_size)
except:
os.unlink(vmlinuz_file)
xcp.logger.debug("Cleaning '%s' and '%s'" % (vmlinuz_file, ramdisk_file))
if ramdisk_file is not None:
os.unlink(ramdisk_file)
raise
return vmlinuz_file, ramdisk_file
def pygrub_first_boot_args(repo):
return ""
##### MAIN HANDLERS
def handle_first_boot(vm, img, args, other_config):
if other_config['install-distro'] not in distros.keys():
raise RuntimeError, "other-config:install-distro was not present or known."
distro = distros[other_config['install-distro']]
repo = other_config['install-repository']
vnc = other_config['install-vnc']
vncpasswd = other_config['install-vncpasswd']
# extract the kernel and ramdisk
# sanity check repo:
if repo == "cdrom":
pass
elif repo and True in [repo.startswith(x) for x in ['http', 'ftp', 'nfs']]:
pass
else:
raise UnsupportedInstallMethod, \
"other-config:install-repository was not set to an appropriate value, " \
"and this is required for the selected distribution type."
# calculate repo_url, a prefix that can be passed into fetchFile
if repo == "cdrom":
# CdromRepo.__init__ triggers a mount. CdromRepo.__del__ does the umount.
cdrom_repo = CdromRepo(img)
repo_url = "file://%s/" % cdrom_repo.mntpoint
elif repo.startswith("nfs"):
# NfsRepo.__init__ triggers a mount. NfsRepo.__del__ does the umount.
nfs_repo = NfsRepo(repo)
repo_url = "file://%s/" % nfs_repo.mntpoint
else:
repo_url = repo
if not repo_url.endswith("/"):
repo_url += "/"
# invoke distro specific handler for extraction of kernel and ramdisk
if distro == DISTRO_RHLIKE:
kernel, ramdisk = rhel_first_boot_handler(vm, repo_url)
elif distro == DISTRO_SLESLIKE:
kernel, ramdisk = sles_first_boot_handler(vm, repo_url, other_config)
elif distro == DISTRO_DEBIANLIKE:
kernel, ramdisk = debian_first_boot_handler(vm, repo_url, other_config)
elif distro == DISTRO_PYGRUB:
kernel, ramdisk = pygrub_first_boot_handler(vm, repo_url, other_config)
else:
raise UnsupportedInstallMethod
if repo == 'cdrom':
# SLES/RHEL: booting from CDROM this time but booting from 1st disk next time
tweak_bootable_disk(vm)
# Calculate the extra args need by kernel to locate installation repository
if distro == DISTRO_RHLIKE:
extra_args = rhel_first_boot_args(repo)
elif distro == DISTRO_SLESLIKE:
extra_args = sles_first_boot_args(repo)
elif distro == DISTRO_DEBIANLIKE:
extra_args = debian_first_boot_args(repo)
elif distro == DISTRO_PYGRUB:
extra_args = pygrub_first_boot_args(repo)
else:
raise UnsupportedInstallMethod
# Tell eliloader to run 2nd boot phase next time this vm is started
if rounds[distro] == 1:
switchBootloader(vm)
# Put it all together
args += " " + extra_args
if vnc:
args += " vnc"
if vncpasswd:
args += " vncpassword=%s" % vncpasswd
# Or set user defined options if available
if other_config['install-args'] is not None:
args += " " + other_config['install-args']
if ramdisk is not None:
print 'kernel %s\nramdisk %s\nargs %s' % (kernel, ramdisk, args)
else:
print 'kernel %s\nargs %s' % (kernel, args)
def handle_second_boot(vm, img, args, other_config):
distro = distros[other_config['install-distro']]
prepend_args = PYGRUB_CMD
if distro == DISTRO_SLESLIKE:
# SLES 9/10 installers do not create /boot/grub/menu.lst when installing on top of XEN
# SLES 11 does not have this problem.
# If pygrub with no options fails then this must be one of the problematic versions, in
# which case /we/ need to tell pygrub where to find the kernel and initrd.
cmd = PYGRUB_CMD + ["-q", "-n", img]
(rc, out, err) = xcp.cmd.runCmd(cmd, True, True)
if rc > 1:
raise PygrubError(rc, err)
if rc != 0:
# need to emulate domUloader. This is done by finding a kernel that
# we can boot if possible, and then setting PV-bootloader-args.
if other_config['install-arch'] == 'x86_64':
kernel = 'vmlinuz-xen'
initrd = 'initrd-xen'
else:
kernel = 'vmlinuz-xenpae'
initrd = 'initrd-xenpae'
xcp.logger.debug("SLES_LIKE: Pygrub failed, trying again..")
for k, i in [ ("/%s" % kernel, "/%s" % initrd ), ("/boot/%s" % kernel , "/boot/%s" % initrd ) ]:
xcp.logger.debug("SLES_LIKE: Trying %s and %s" % (k, i) )
cmd = PYGRUB_CMD + ["-n", "--kernel", k, "--ramdisk", i, img]
(rc, out, err) = xcp.cmd.runCmd(cmd, True, True)
if rc > 1:
raise PygrubError(rc, err)
if rc == 0:
# found it - make the setting permanent:
xcp.logger.debug("SLES_LIKE: success.")
session = XenAPI.xapi_local()
session.login_with_password("", "", "", PROGRAM_NAME)
try:
prepend_args += ["--kernel", k, "--ramdisk", i]
vm_ref = session.xenapi.VM.get_by_uuid(vm)
if not never_latch:
session.xenapi.VM.set_PV_bootloader_args(vm_ref, "--kernel %s --ramdisk %s" % (k, i))
finally:
session.logout()
break
elif distro == DISTRO_RHLIKE:
# Oracle 5.x uek kernel doesn't boot, so we have to override
# pygrub's default by setting PV-bootloader-args (with --entry N)
cmd = PYGRUB_CMD + ["-q", "-l", img]
(rc, out, err) = xcp.cmd.runCmd(cmd, True, True)
if rc != 0:
raise PygrubError(rc, err)
# Get the title 'title:' lines from pygrub
p = re.compile('^title:')
titles = [l for l in out.splitlines() if p.search(l)]
found_ole_5x = False
p = re.compile(r'Oracle.*el5uek', re.IGNORECASE)
idx = 0
ole5uek_lst = [bool(p.search(t)) for t in titles]
found_ole_5x = True in ole5uek_lst
# Get the (pygrub) indices for non el5uek kernel
indices = []
for (i, b) in itertools.izip(itertools.count(), ole5uek_lst):
if b: # el5uek kernel, so skip the index
pass
else:
indices.append(i)
if found_ole_5x:
if not indices:
raise Exception("Could not find non el5uek kernel")
else:
idx = indices[0]
xcp.logger.debug("RHEL_LIKE: Pygrub found Oracle 5.x .el5euk kernel")
session = XenAPI.xapi_local()
session.login_with_password("", "", "", PROGRAM_NAME)
try:
prepend_args += ["--entry", str(idx)]
vm_ref = session.xenapi.VM.get_by_uuid(vm)
if not never_latch:
session.xenapi.VM.set_PV_bootloader_args(vm_ref, "--entry %s" % idx)