-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathbackend.py
1645 lines (1371 loc) · 71.2 KB
/
backend.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
# SPDX-License-Identifier: GPL-2.0-only
import os
import os.path
import stat
import subprocess
import datetime
import re
import tempfile
import repository
import generalui
import xelogging
import util
import diskutil
from disktools import *
import fcoeutil
import netutil
import shutil
import constants
import hardware
import upgrade
import init_constants
import scripts
import xcp.bootloader as bootloader
import netinterface
import tui.repo
import xcp.dom0
from xcp import logger
from xcp.version import Version
# Product version and constants:
import version
from version import *
from constants import *
from functools import reduce
MY_PRODUCT_BRAND = PRODUCT_BRAND or PLATFORM_NAME
class InvalidInstallerConfiguration(Exception):
pass
################################################################################
# FIRST STAGE INSTALLATION:
class Task:
"""
Represents an install step.
'fn' is the function to execute
'args' is a list of value labels identifying arguments to the function,
'returns' is a list of the labels of the return values, or a function
that, when given the 'args' labels list, returns the list of the
labels of the return values.
"""
def __init__(self, fn, args, returns, args_sensitive=False,
progress_scale=1, pass_progress_callback=False,
progress_text=None):
self.fn = fn
self.args = args
self.returns = returns
self.args_sensitive = args_sensitive
self.progress_scale = progress_scale
self.pass_progress_callback = pass_progress_callback
self.progress_text = progress_text
def execute(self, answers, progress_callback=lambda x: ()):
args = self.args(answers)
assert type(args) == list
if not self.args_sensitive:
logger.log("TASK: Evaluating %s%s" % (self.fn, args))
else:
logger.log("TASK: Evaluating %s (sensitive data in arguments: not logging)" % self.fn)
if self.pass_progress_callback:
args.insert(0, progress_callback)
rv = self.fn(*args)
if type(rv) is not tuple:
rv = (rv,)
myrv = {}
if callable(self.returns):
ret = self.returns(*args)
else:
ret = self.returns
for r in range(len(ret)):
myrv[ret[r]] = rv[r]
return myrv
###
# INSTALL SEQUENCES:
# convenience functions
# A: For each label in params, gives an arg function that evaluates
# the labels when the function is called (late-binding)
# As: As above but evaluated immediately (early-binding)
# Use A when you require state values as well as the initial input values
A = lambda ans, *params: ( lambda a: [a.get(param) for param in params] )
As = lambda ans, *params: ( lambda _: [ans.get(param) for param in params] )
def getPrepSequence(ans, interactive):
seq = [
Task(util.getUUID, As(ans), ['installation-uuid']),
Task(util.getUUID, As(ans), ['control-domain-uuid']),
Task(util.randomLabelStr, As(ans), ['disk-label-suffix']),
Task(partitionTargetDisk, A(ans, 'primary-disk', 'installation-to-overwrite', 'preserve-first-partition','sr-on-primary'),
['primary-partnum', 'backup-partnum', 'storage-partnum', 'boot-partnum', 'logs-partnum', 'swap-partnum']),
]
if ans['ntp-config-method'] in ("dhcp", "default", "manual"):
seq.append(Task(setTimeNTP, A(ans, 'ntp-servers', 'ntp-config-method'), []))
elif ans['ntp-config-method'] == "none":
seq.append(Task(setTimeManually, A(ans, 'localtime', 'set-time-dialog-dismissed', 'timezone'), []))
if not interactive:
seq.append(Task(verifyRepos, A(ans, 'sources', 'ui'), []))
if ans['install-type'] == INSTALL_TYPE_FRESH:
seq += [
Task(removeBlockingVGs, As(ans, 'guest-disks'), []),
Task(writeDom0DiskPartitions, A(ans, 'primary-disk', 'boot-partnum', 'primary-partnum', 'backup-partnum', 'logs-partnum', 'swap-partnum', 'storage-partnum', 'sr-at-end'),[]),
]
seq.append(Task(writeGuestDiskPartitions, A(ans,'primary-disk', 'guest-disks'), []))
elif ans['install-type'] == INSTALL_TYPE_REINSTALL:
seq.append(Task(getUpgrader, A(ans, 'installation-to-overwrite'), ['upgrader']))
if 'backup-existing-installation' in ans and ans['backup-existing-installation']:
seq.append(Task(doBackup,
lambda a: [ a['upgrader'] ] + [ a[x] for x in a['upgrader'].doBackupArgs ],
lambda progress_callback, upgrader, *a: upgrader.doBackupStateChanges,
progress_text="Backing up existing installation...",
progress_scale=100,
pass_progress_callback=True))
seq.append(Task(prepareTarget,
lambda a: [ a['upgrader'] ] + [ a[x] for x in a['upgrader'].prepTargetArgs ],
lambda progress_callback, upgrader, *a: upgrader.prepTargetStateChanges,
progress_text="Preparing target disk...",
progress_scale=100,
pass_progress_callback=True))
seq.append(Task(prepareUpgrade,
lambda a: [ a['upgrader'] ] + [ a[x] for x in a['upgrader'].prepUpgradeArgs ],
lambda progress_callback, upgrader, *a: upgrader.prepStateChanges,
progress_text="Preparing for upgrade...",
progress_scale=100,
pass_progress_callback=True))
seq += [
Task(createDom0DiskFilesystems, A(ans, 'install-type', 'primary-disk', 'boot-partnum', 'primary-partnum', 'logs-partnum', 'disk-label-suffix', 'fs-type'), []),
Task(mountVolumes, A(ans, 'primary-disk', 'boot-partnum', 'primary-partnum', 'logs-partnum', 'cleanup'), ['mounts', 'cleanup']),
]
return seq
def getMainRepoSequence(ans, repos):
seq = []
seq.append(Task(repository.installFromRepos, lambda a: [repos] + [a.get('mounts')], [],
progress_scale=100,
pass_progress_callback=True,
progress_text="Installing %s..." % (", ".join([repo.name() for repo in repos]))))
for repo in repos:
seq.append(Task(repo.record_install, A(ans, 'mounts', 'installed-repos'), ['installed-repos']))
seq.append(Task(repo.getBranding, A(ans, 'branding'), ['branding']))
return seq
def getRepoSequence(ans, repos):
seq = []
for repo in repos:
seq.append(Task(repo.installPackages, A(ans, 'mounts'), [],
progress_scale=100,
pass_progress_callback=True,
progress_text="Installing %s..." % repo.name()))
seq.append(Task(repo.record_install, A(ans, 'mounts', 'installed-repos'), ['installed-repos']))
seq.append(Task(repo.getBranding, A(ans, 'branding'), ['branding']))
return seq
def getFinalisationSequence(ans):
seq = [
Task(writeResolvConf, A(ans, 'mounts', 'manual-hostname', 'manual-nameservers'), []),
Task(writeMachineID, A(ans, 'mounts'), []),
Task(writeKeyboardConfiguration, A(ans, 'mounts', 'keymap'), []),
Task(configureNetworking, A(ans, 'mounts', 'net-admin-interface', 'net-admin-bridge', 'net-admin-configuration', 'manual-hostname', 'manual-nameservers', 'network-hardware', 'preserve-settings', 'network-backend'), []),
Task(prepareSwapfile, A(ans, 'mounts', 'primary-disk', 'swap-partnum', 'disk-label-suffix'), []),
Task(writeFstab, A(ans, 'mounts', 'primary-disk', 'logs-partnum', 'swap-partnum', 'disk-label-suffix', 'fs-type'), []),
Task(enableAgent, A(ans, 'mounts', 'network-backend', 'services'), []),
Task(configureCC, A(ans, 'mounts'), []),
Task(writeInventory, A(ans, 'installation-uuid', 'control-domain-uuid', 'mounts', 'primary-disk',
'backup-partnum', 'logs-partnum', 'boot-partnum', 'swap-partnum', 'storage-partnum',
'guest-disks', 'net-admin-bridge',
'branding', 'net-admin-configuration', 'host-config', 'install-type'), []),
Task(writeXencommons, A(ans, 'control-domain-uuid', 'mounts'), []),
Task(configureISCSI, A(ans, 'mounts', 'primary-disk'), []),
Task(mkinitrd, A(ans, 'mounts', 'primary-disk', 'primary-partnum'), []),
Task(prepFallback, A(ans, 'mounts', 'primary-disk', 'primary-partnum'), []),
Task(installBootLoader, A(ans, 'mounts', 'primary-disk',
'boot-partnum', 'primary-partnum', 'branding',
'disk-label-suffix', 'bootloader-location', 'write-boot-entry', 'install-type',
'serial-console', 'boot-serial', 'host-config', 'fcoe-interfaces'), []),
Task(touchSshAuthorizedKeys, A(ans, 'mounts'), []),
Task(setRootPassword, A(ans, 'mounts', 'root-password'), [], args_sensitive=True),
Task(setTimeZone, A(ans, 'mounts', 'timezone'), []),
Task(writei18n, A(ans, 'mounts'), []),
Task(configureMCELog, A(ans, 'mounts'), []),
]
# on fresh installs, prepare the storage repository as required:
if ans['install-type'] == INSTALL_TYPE_FRESH:
seq += [
Task(prepareStorageRepositories, A(ans, 'mounts', 'primary-disk', 'storage-partnum', 'guest-disks', 'sr-type'), []),
Task(configureSRMultipathing, A(ans, 'mounts', 'primary-disk'), []),
]
seq.append(Task(setDHCPNTP, A(ans, "mounts", "ntp-config-method"), []))
if ans['ntp-config-method'] != "none":
seq.append(Task(configureNTP, A(ans, 'mounts', 'ntp-config-method', 'ntp-servers'), []))
# complete upgrade if appropriate:
if ans['install-type'] == constants.INSTALL_TYPE_REINSTALL:
seq.append( Task(completeUpgrade, lambda a: [ a['upgrader'] ] + [ a[x] for x in a['upgrader'].completeUpgradeArgs ], []) )
# run the users's scripts
seq.append( Task(scripts.run_scripts, lambda a: ['filesystem-populated', a['mounts']['root']], []) )
seq.append(Task(umountVolumes, A(ans, 'mounts', 'cleanup'), ['cleanup']))
seq.append(Task(writeLog, A(ans, 'primary-disk', 'primary-partnum', 'logs-partnum'), []))
return seq
def prettyLogAnswers(answers):
for a in answers:
if a == 'root-password':
val = (answers[a][0], '< not printed >')
elif a == 'pool-token':
val = '< not printed >'
else:
val = answers[a]
logger.log("%s := %s %s" % (a, val, type(val)))
def executeSequence(sequence, seq_name, answers, ui, cleanup):
answers['cleanup'] = []
answers['ui'] = ui
progress_total = reduce(lambda x, y: x + y,
[task.progress_scale for task in sequence])
pd = None
if ui:
pd = ui.progress.initProgressDialog(
"Installing %s" % MY_PRODUCT_BRAND,
seq_name, progress_total
)
logger.log("DISPATCH: NEW PHASE: %s" % seq_name)
def doCleanup(actions):
for tag, f, a in actions:
try:
f(*a)
except:
logger.log("FAILED to perform cleanup action %s" % tag)
def progressCallback(x):
if ui:
ui.progress.displayProgressDialog(current + x, pd)
try:
current = 0
for item in sequence:
if pd:
if item.progress_text:
text = item.progress_text
else:
text = seq_name
ui.progress.displayProgressDialog(current, pd, updated_text=text)
updated_state = item.execute(answers, progressCallback)
if len(updated_state) > 0:
logger.log(
"DISPATCH: Updated state: %s" %
"; ".join(["%s -> %s" % (k, v) for k, v in updated_state.items()])
)
for state_item in updated_state:
answers[state_item] = updated_state[state_item]
current = current + item.progress_scale
except:
doCleanup(answers['cleanup'])
raise
else:
if ui and pd:
ui.progress.clearModelessDialog()
if cleanup:
doCleanup(answers['cleanup'])
del answers['cleanup']
def performInstallation(answers, ui_package, interactive):
logger.log("INPUT ANSWERS DICTIONARY:")
prettyLogAnswers(answers)
logger.log("SCRIPTS DICTIONARY:")
prettyLogAnswers(scripts.script_dict)
dom0_mem = xcp.dom0.default_memory_for_version(
hardware.getHostTotalMemoryKB(),
Version.from_string(version.PLATFORM_VERSION)) // 1024
dom0_vcpus = xcp.dom0.default_vcpus(hardware.getHostTotalCPUs(), dom0_mem)
default_host_config = { 'dom0-mem': dom0_mem,
'dom0-vcpus': dom0_vcpus,
'xen-cpuid-masks': [] }
defaults = { 'branding': {}, 'host-config': {}, 'write-boot-entry': True }
# update the settings:
if answers['preserve-settings'] == True:
defaults.update({ 'guest-disks': [] })
logger.log("Updating answers dictionary based on existing installation")
try:
answers.update(answers['installation-to-overwrite'].readSettings())
# Use the new default amount of RAM as long as it doesn't result in
# a decrease from the previous installation. Update the number of
# dom0 vCPUs since it depends on the amount of RAM assigned.
if 'dom0-mem' in answers['host-config']:
answers['host-config']['dom0-mem'] = max(answers['host-config']['dom0-mem'],
default_host_config['dom0-mem'])
default_host_config['dom0-vcpus'] = xcp.dom0.default_vcpus(hardware.getHostTotalCPUs(),
answers['host-config']['dom0-mem'])
except Exception as e:
logger.logException(e)
raise RuntimeError("Failed to get existing installation settings")
prettyLogAnswers(answers)
else:
defaults.update({ 'master': None,
'sr-type': constants.SR_TYPE_LVM,
'bootloader-location': constants.BOOT_LOCATION_MBR,
'sr-at-end': True,
'sr-on-primary': True})
logger.log("Updating answers dictionary based on defaults")
for k, v in defaults.items():
if k not in answers:
answers[k] = v
for k, v in default_host_config.items():
if k not in answers['host-config']:
answers['host-config'][k] = v
logger.log("UPDATED ANSWERS DICTIONARY:")
prettyLogAnswers(answers)
# Slight hack: we need to write the bridge name to xensource-inventory
# further down; compute it here based on the admin interface name if we
# haven't already recorded it as part of reading settings from an upgrade:
if answers['install-type'] == INSTALL_TYPE_FRESH:
answers['net-admin-bridge'] = ''
elif 'net-admin-bridge' not in answers:
assert answers['net-admin-interface'].startswith("eth")
answers['net-admin-bridge'] = "xenbr%s" % answers['net-admin-interface'][3:]
# perform installation:
prep_seq = getPrepSequence(answers, interactive)
answers_pristine = answers.copy()
executeSequence(prep_seq, "Preparing for installation...", answers, ui_package, False)
# install from main repositories:
def handleMainRepos(main_repositories, ans):
repo_seq = getMainRepoSequence(ans, main_repositories)
executeSequence(repo_seq, "Reading package information...", ans, ui_package, False)
def handleRepos(repos, ans):
repo_seq = getRepoSequence(ans, repos)
executeSequence(repo_seq, "Reading package information...", ans, ui_package, False)
answers['installed-repos'] = {}
# A list needs to be used rather than a set since the order of updates is
# important. However, since the same repository might exist in multiple
# locations or the same location might be listed multiple times, care is
# needed to ensure that there are no duplicates.
main_repositories = []
update_repositories = []
def add_repos(main_repositories, update_repositories, repos):
"""Add repositories to the appropriate list, ensuring no duplicates,
that the main repository is at the beginning, and that the order of the
rest is maintained."""
for repo in repos:
if isinstance(repo, repository.UpdateYumRepository):
repo_list = update_repositories
else:
repo_list = main_repositories
if repo not in repo_list:
if repo.identifier() == MAIN_REPOSITORY_NAME:
repo_list.insert(0, repo)
else:
repo_list.append(repo)
# A list of sources coming from the answerfile
if 'sources' in answers_pristine:
for i in answers_pristine['sources']:
repos = repository.repositoriesFromDefinition(i['media'], i['address'])
add_repos(main_repositories, update_repositories, repos)
# A single source coming from an interactive install
if 'source-media' in answers_pristine and 'source-address' in answers_pristine:
repos = repository.repositoriesFromDefinition(answers_pristine['source-media'], answers_pristine['source-address'])
add_repos(main_repositories, update_repositories, repos)
for media, address in answers_pristine['extra-repos']:
repos = repository.repositoriesFromDefinition(media, address)
add_repos(main_repositories, update_repositories, repos)
if not main_repositories or main_repositories[0].identifier() != MAIN_REPOSITORY_NAME:
raise RuntimeError("No main repository found")
handleMainRepos(main_repositories, answers)
if update_repositories:
handleRepos(update_repositories, answers)
# Find repositories that we installed from removable media
# and eject the media.
for r in main_repositories + update_repositories:
if r.accessor().canEject():
r.accessor().eject()
if interactive and constants.HAS_SUPPLEMENTAL_PACKS:
# Add supp packs in a loop
while True:
media_ans = dict(answers_pristine)
del media_ans['source-media']
del media_ans['source-address']
media_ans = ui_package.installer.more_media_sequence(media_ans)
if 'more-media' not in media_ans or not media_ans['more-media']:
break
repos = repository.repositoriesFromDefinition(media_ans['source-media'], media_ans['source-address'])
repos = set([repo for repo in repos if str(repo) not in answers['installed-repos']])
if not repos:
continue
handleRepos(repos, answers)
for r in repos:
if r.accessor().canEject():
r.accessor().eject()
# complete the installation:
fin_seq = getFinalisationSequence(answers)
executeSequence(fin_seq, "Completing installation...", answers, ui_package, True)
def configureMCELog(mounts):
"""Disable mcelog on unsupported processors."""
is_amd = False
model = 0
with open('/proc/cpuinfo', 'r') as f:
for line in f:
line = line.strip()
if re.match('vendor_id\s*:\s*AuthenticAMD$', line):
is_amd = True
continue
m = re.match('cpu family\s*:\s*(\d+)$', line)
if m:
model = int(m.group(1))
if is_amd and model >= 16:
util.runCmd2(['chroot', mounts['root'], 'systemctl', 'disable', 'mcelog'])
def rewriteNTPConf(root, ntp_servers):
ntpsconf = open("%s/etc/chrony.conf" % root, 'r')
lines = ntpsconf.readlines()
ntpsconf.close()
lines = [x for x in lines if not x.startswith('server ')]
ntpsconf = open("%s/etc/chrony.conf" % root, 'w')
for line in lines:
ntpsconf.write(line)
if ntp_servers:
for server in ntp_servers:
ntpsconf.write("server %s iburst\n" % server)
ntpsconf.close()
def setTimeNTP(ntp_servers, ntp_config_method):
if ntp_config_method in ("dhcp", "manual"):
rewriteNTPConf('', ntp_servers)
# This might fail or stall if the network is not set up correctly so set a
# time limit and don't expect it to succeed.
if util.runCmd2(['timeout', '15', 'chronyd', '-q']) == 0:
assert util.runCmd2(['hwclock', '--utc', '--systohc']) == 0
def setTimeManually(localtime, set_time_dialog_dismissed, timezone):
newtime = localtime + (datetime.datetime.now() - set_time_dialog_dismissed)
timestr = "%04d-%02d-%02d %02d:%02d:00" % \
(newtime.year, newtime.month, newtime.day,
newtime.hour, newtime.minute)
util.setLocalTime(timestr, timezone=timezone)
assert util.runCmd2(['hwclock', '--utc', '--systohc']) == 0
def setDHCPNTP(mounts, ntp_config_method):
script = os.path.join(mounts['root'], "etc/dhcp/dhclient.d/chrony.sh")
oldPermissions = os.stat(script).st_mode
if ntp_config_method == "dhcp":
newPermissions = oldPermissions | (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) # Add execute permission
else:
newPermissions = oldPermissions & ~(stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) # Remove execute permission
os.chmod(script, newPermissions)
def configureNTP(mounts, ntp_config_method, ntp_servers):
# If NTP servers were specified, update the NTP config file:
if ntp_config_method in ("dhcp", "manual"):
rewriteNTPConf(mounts['root'], ntp_servers)
# now turn on the ntp service:
util.runCmd2(['chroot', mounts['root'], 'systemctl', 'enable', 'chronyd'])
util.runCmd2(['chroot', mounts['root'], 'systemctl', 'enable', 'chrony-wait'])
# This is attempting to understand the desired layout of the future partitioning
# based on options passed and status of disk (like partition to retain).
# This should be used for upgrade or install, not for restore.
# Returns 'primary-partnum', 'backup-partnum', 'storage-partnum', 'boot-partnum', 'logs-partnum', 'swap-partnum'
def partitionTargetDisk(disk, existing, preserve_first_partition, create_sr_part):
primary_part = 1
if existing:
# upgrade, use existing partitioning scheme
tool = PartitionTool(existing.primary_disk)
primary_part = tool.partitionNumber(existing.root_device)
# Determine target install's boot partition number
if existing.boot_device:
boot_partnum = tool.partitionNumber(existing.boot_device)
boot_part = tool.getPartition(boot_partnum)
if 'id' not in boot_part or boot_part['id'] != GPTPartitionTool.ID_EFI_BOOT:
raise RuntimeError("Boot partition is not set up for UEFI mode or missing EFI partition ID.")
else:
boot_partnum = primary_part + 3
logger.log("Upgrading")
# Return install mode and numbers of primary, backup, SR, boot, log and swap partitions
storage_partition = tool.getPartition(primary_part+2)
if storage_partition:
return (primary_part, primary_part+1, primary_part+2, boot_partnum, primary_part+4, primary_part+5)
else:
return (primary_part, primary_part+1, 0, boot_partnum, primary_part+4, primary_part+5)
tool = PartitionTool(disk)
# Cannot preserve partition for legacy DOS partition table.
if tool.partTableType == constants.PARTITION_DOS :
if preserve_first_partition == 'true' or (
preserve_first_partition == constants.PRESERVE_IF_UTILITY and tool.utilityPartitions()):
raise RuntimeError("Preserving initial partition on DOS unsupported")
# Preserve any utility partitions unless user told us to zap 'em
primary_part = 1
if preserve_first_partition == 'true':
primary_part += 1
elif preserve_first_partition == constants.PRESERVE_IF_UTILITY:
utilparts = tool.utilityPartitions()
primary_part += max(utilparts+[0])
if primary_part > 2:
raise RuntimeError("Installer only supports a single Utility Partition at partition 1, but found Utility Partitions at %s" % str(utilparts))
sr_part = -1
if create_sr_part:
sr_part = primary_part+2
boot_part = max(primary_part + 1, sr_part) + 1
logger.log("Fresh install")
return (primary_part, primary_part + 1, sr_part, boot_part, primary_part + 4, primary_part + 5)
def removeBlockingVGs(disks):
for vg in diskutil.findProblematicVGs(disks):
util.runCmd2(['vgreduce', '--removemissing', vg])
util.runCmd2(['lvremove', vg])
util.runCmd2(['vgremove', vg])
###
# Functions to write partition tables to disk
def writeDom0DiskPartitions(disk, boot_partnum, primary_partnum, backup_partnum, logs_partnum, swap_partnum, storage_partnum, sr_at_end):
# we really don't want to screw this up...
assert type(disk) == str
assert disk[:5] == '/dev/'
if not os.path.exists(disk):
raise RuntimeError("The disk %s could not be found." % disk)
# If new partition layout requested: exit if disk is not big enough, otherwise implement it
elif diskutil.blockSizeToGBSize(diskutil.getDiskDeviceSize(disk)) < constants.min_primary_disk_size:
raise RuntimeError("The disk %s is smaller than %dGB." % (disk, constants.min_primary_disk_size))
tool = PartitionTool(disk, constants.PARTITION_GPT)
for num, part in tool.items():
if num >= primary_partnum:
tool.deletePartition(num)
order = primary_partnum
# Create the new partition layout (5,2,1,4,6,3)
# Normal layout
# 1 - dom0 partition
# 2 - backup partition
# 3 - LVM partition
# 4 - Boot partition
# 5 - logs partition
# 6 - swap partition
#
# Create logs partition
# Start the first partition at 1 MiB if there are no other partitions.
# Otherwise start the partition following the utility partition.
if order == 1:
tool.createPartition(tool.ID_LINUX, sizeBytes=logs_size * 2**20, startBytes=2**20, number=logs_partnum, order=order, label=logspart_label)
else:
tool.createPartition(tool.ID_LINUX, sizeBytes=logs_size * 2**20, number=logs_partnum, order=order, label=logspart_label)
order += 1
# Create backup partition
if backup_partnum > 0:
tool.createPartition(tool.ID_LINUX, sizeBytes=backup_size * 2**20, number=backup_partnum, order=order, label=backuppart_label)
order += 1
# Create dom0 partition
tool.createPartition(tool.ID_LINUX, sizeBytes=constants.root_size * 2**20, number=primary_partnum, order=order, label=rootpart_label)
order += 1
# Create Boot partition
tool.createPartition(tool.ID_EFI_BOOT, sizeBytes=boot_size * 2**20, number=boot_partnum, order=order, label=bootpart_label)
order += 1
# Create swap partition
tool.createPartition(tool.ID_LINUX_SWAP, sizeBytes=swap_size * 2**20, number=swap_partnum, order=order, label=swappart_label)
order += 1
# Create LVM partition
if storage_partnum > 0:
tool.createPartition(tool.ID_LINUX_LVM, number=storage_partnum, order=order, label=storagepart_label)
order += 1
if not sr_at_end:
# For upgrade testing, out-of-order partition layout
new_parts = {}
new_parts[primary_partnum] = {'start': tool.partitions[primary_partnum]['start'] + tool.partitions[storage_partnum]['size'],
'size': tool.partitions[primary_partnum]['size'],
'id': tool.partitions[primary_partnum]['id'],
'active': tool.partitions[primary_partnum]['active'],
'partlabel': tool.partitions[primary_partnum]['partlabel']}
if backup_partnum > 0:
new_parts[backup_partnum] = {'start': new_parts[primary_partnum]['start'] + new_parts[primary_partnum]['size'],
'size': tool.partitions[backup_partnum]['size'],
'id': tool.partitions[backup_partnum]['id'],
'active': tool.partitions[backup_partnum]['active'],
'partlabel': tool.partitions[backup_partnum]['partlabel']}
new_parts[storage_partnum] = {'start': tool.partitions[primary_partnum]['start'],
'size': tool.partitions[storage_partnum]['size'],
'id': tool.partitions[storage_partnum]['id'],
'active': tool.partitions[storage_partnum]['active'],
'partlabel': tool.partitions[storage_partnum]['partlabel']}
for part in (primary_partnum, backup_partnum, storage_partnum):
if part > 0:
tool.deletePartition(part)
tool.createPartition(new_parts[part]['id'], new_parts[part]['size'] * tool.sectorSize, part,
new_parts[part]['start'] * tool.sectorSize, new_parts[part]['active'],
new_parts[part]['partlabel'])
tool.commit(log=True)
def writeGuestDiskPartitions(primary_disk, guest_disks):
# At the moment this code uses the same partition table type for Guest Disks as it
# does for the root disk. But we could choose to always use 'GPT' for guest disks.
# TODO: Decide!
for gd in guest_disks:
if gd != primary_disk:
# we really don't want to screw this up...
assert type(gd) == str
assert gd[:5] == '/dev/'
tool = PartitionTool(gd, constants.PARTITION_GPT)
tool.deletePartitions(list(tool.partitions.keys()))
tool.commit(log=True)
def setActiveDiskPartition(disk, boot_partnum, primary_partnum):
tool = PartitionTool(disk, constants.PARTITION_GPT)
tool.commitActivePartitiontoDisk(boot_partnum)
def getSRPhysDevs(primary_disk, storage_partnum, guest_disks):
def sr_partition(disk):
if disk == primary_disk:
return partitionDevice(disk, storage_partnum)
else:
return disk
return [sr_partition(disk) for disk in guest_disks]
def prepareStorageRepositories(mounts, primary_disk, storage_partnum, guest_disks, sr_type):
if len(guest_disks) == 0 or constants.CC_PREPARATIONS and sr_type != constants.SR_TYPE_EXT:
logger.log("No storage repository requested.")
return None
logger.log("Arranging for storage repositories to be created at first boot...")
partitions = getSRPhysDevs(primary_disk, storage_partnum, guest_disks)
# write a config file for the prepare-storage firstboot script:
links = [diskutil.idFromPartition(x) or x for x in partitions]
fd = open(os.path.join(mounts['root'], constants.FIRSTBOOT_DATA_DIR, 'default-storage.conf'), 'w')
print("XSPARTITIONS='%s'" % str.join(" ", links), file=fd)
print("XSTYPE='%s'" % sr_type, file=fd)
# Legacy names
print("PARTITIONS='%s'" % str.join(" ", links), file=fd)
print("TYPE='%s'" % sr_type, file=fd)
fd.close()
def make_free_space(mount, required):
"""Make required bytes of free space available on mount by removing files,
oldest first."""
def getinfo(dirpath, name):
path = os.path.join(dirpath, name)
return os.stat(path).st_mtime, path
def free_space(path):
st = os.statvfs(path)
return st.f_bavail * st.f_frsize
if free_space(mount) >= required:
return
files = []
dirs = []
for dirpath, dirnames, filenames in os.walk(mount):
for i in dirnames:
dirs.append(getinfo(dirpath, i))
for i in filenames:
files.append(getinfo(dirpath, i))
files.sort()
dirs.sort()
for _, path in files:
os.unlink(path)
logger.log('Removed %s' % path)
if free_space(mount) >= required:
return
for _, path in dirs:
shutil.rmtree(path, ignore_errors=True)
logger.log('Removed %s' % path)
if free_space(mount) >= required:
return
raise RuntimeError("Failed to make enough space available on %s (%d, %d)" % (mount, required, free_space(mount)))
###
# Create dom0 disk file-systems:
def createDom0DiskFilesystems(install_type, disk, boot_partnum, primary_partnum, logs_partnum, disk_label_suffix, fs_type):
partition = partitionDevice(disk, boot_partnum)
try:
util.mkfs(bootfs_type, partition,
["-n", bootfs_label%disk_label_suffix.upper()])
except Exception as e:
raise RuntimeError("Failed to create boot filesystem: %s" % e)
partition = partitionDevice(disk, primary_partnum)
try:
util.mkfs(fs_type, partition,
["-L", rootfs_label%disk_label_suffix])
except Exception as e:
raise RuntimeError("Failed to create root filesystem: %s" % e)
tool = PartitionTool(disk)
logs_partition = tool.getPartition(logs_partnum)
if logs_partition:
run_mkfs = True
change_logs_fs_type = diskutil.fs_type_from_device(partitionDevice(disk, logs_partnum)) != fs_type
# If the log partition already exists and is formatted correctly,
# relabel it. Otherwise create the filesystem.
partition = partitionDevice(disk, logs_partnum)
label = None
try:
label = diskutil.readExtPartitionLabel(partition)
except Exception as e:
# Ignore the exception as it just means the partition needs to be
# formatted.
pass
if install_type != INSTALL_TYPE_FRESH and label and label.startswith(logsfs_label_prefix) and not change_logs_fs_type:
# If a filesystem which has not been unmounted cleanly is
# relabelled, it will revert to the original label once it is
# mounted. To prevent this, fsck the filesystem before relabelling.
# If any unfixable errors occur or relabelling fails, just recreate
# the filesystem instead, rather than fail the installation.
if util.runCmd2(['e2fsck', '-y', partition]) in (0, 1):
if util.runCmd2(['e2label', partition, constants.logsfs_label % disk_label_suffix]) == 0:
run_mkfs = False
if run_mkfs:
try:
util.mkfs(fs_type, partition,
["-L", logsfs_label % disk_label_suffix])
except Exception as e:
raise RuntimeError("Failed to create logs filesystem: %s" % e)
else:
# Ensure enough free space is available
mount = util.TempMount(partition, 'logs-')
try:
make_free_space(mount.mount_point, constants.logs_free_space * 1024 * 1024)
finally:
mount.unmount()
#pylint: disable=consider-using-f-string
def _generateBFS(mounts, primary_disk): #pylint: disable=invalid-name
rv, wwid, err = util.runCmd2(["chroot", mounts["root"], "/usr/lib/udev/scsi_id",
"-g", primary_disk], with_stdout=True, with_stderr=True)
if rv != 0:
raise RuntimeError("Failed to whitelist %s with error: %s" % (primary_disk, err) )
# Remove ending line breaker
wwid = wwid.strip()
util.runCmd2(["chroot", mounts["root"], "/usr/sbin/multipath", "-a", wwid])
def __mkinitrd(mounts, primary_disk, partition, kernel_version):
if isDeviceMapperNode(partition):
# Generate a valid multipath configuration
_generateBFS(mounts, primary_disk)
# Run dracut inside dom0 chroot
output_file = os.path.join("/boot", "initrd-%s.img" % kernel_version)
# default to only including host specific kernel modules in initrd
# disable multipath on root partition
try:
if not isDeviceMapperNode(partition):
f = open(os.path.join(mounts['root'], 'etc/dracut.conf.d/xs_disable_multipath.conf'), 'w')
f.write('omit_dracutmodules+=" multipath "\n')
f.close()
except:
pass
cmd = ['dracut', '-f', output_file, kernel_version]
if util.runCmd2(['chroot', mounts['root']] + cmd) != 0:
raise RuntimeError("Failed to create initrd for %s. This is often due to using an installer that is not the same version of %s as your installation source." % (kernel_version, MY_PRODUCT_BRAND))
def getXenVersion(rootfs_mount):
""" Return the xen version by interogating the package version in the chroot """
xen_version = ['rpm', '--root', rootfs_mount, '-q', '--qf', '%{version}', 'xen-hypervisor']
rc, out = util.runCmd2(xen_version, with_stdout=True)
if rc != 0:
return None
return out
def getKernelVersion(rootfs_mount):
""" Returns the kernel release (uname -r) of the installed kernel """
kernel_version = ['rpm', '--root', rootfs_mount, '-q', '--provides', 'kernel']
rc, out = util.runCmd2(kernel_version, with_stdout=True)
if rc != 0:
return None
try:
uname_provides = [x for x in out.split('\n') if x.startswith('kernel-uname-r')]
return uname_provides[0].split('=')[1].strip()
except:
pass
return None
def kernelShortVersion(version):
""" Return the short kernel version string (i.e., just major.minor). """
parts = version.split(".")
return parts[0] + "." + parts[1]
def configureSRMultipathing(mounts, primary_disk):
# Only called on fresh installs:
# Configure multipathed SRs iff root disk is multipathed
fd = open(os.path.join(mounts['root'], constants.FIRSTBOOT_DATA_DIR, 'sr-multipathing.conf'),'w')
if isDeviceMapperNode(primary_disk):
fd.write("MULTIPATHING_ENABLED='True'\n")
else:
fd.write("MULTIPATHING_ENABLED='False'\n")
fd.close()
def adjustISCSITimeoutForFile(path):
iscsiconf = open(path, 'r')
lines = iscsiconf.readlines()
iscsiconf.close()
timeout_key = "node.session.timeo.replacement_timeout"
wrote_key = False
iscsiconf = open(path, 'w')
for line in lines:
if line.startswith(timeout_key):
iscsiconf.write("%s = %d\n" % (timeout_key, MPATH_ISCSI_TIMEOUT))
wrote_key = True
else:
iscsiconf.write(line)
if not wrote_key:
iscsiconf.write("%s = %d\n" % (timeout_key, MPATH_ISCSI_TIMEOUT))
iscsiconf.close()
def configureISCSI(mounts, primary_disk):
if not diskutil.is_iscsi(primary_disk):
return
iname = diskutil.get_initiator_name()
with open(os.path.join(mounts['root'], 'etc/iscsi/initiatorname.iscsi'), 'w') as f:
f.write('InitiatorName=%s\n' % (iname,))
# Create IQN file for XAPI
with open(os.path.join(mounts['root'], 'etc/firstboot.d/data/iqn.conf'), 'w') as f:
f.write("IQN='%s'" % iname)
if util.runCmd2(['chroot', mounts['root'],
'systemctl', 'enable', 'iscsid']):
raise RuntimeError("Failed to enable iscsid")
if util.runCmd2(['chroot', mounts['root'],
'systemctl', 'enable', 'iscsi']):
raise RuntimeError("Failed to enable iscsi")
diskutil.write_iscsi_records(mounts, primary_disk)
# Reduce the timeout when using multipath
if isDeviceMapperNode(primary_disk):
adjustISCSITimeoutForFile("%s/etc/iscsi/iscsid.conf" % mounts['root'])
def mkinitrd(mounts, primary_disk, primary_partnum):
xen_version = getXenVersion(mounts['root'])
if xen_version is None:
raise RuntimeError("Unable to determine Xen version.")
xen_kernel_version = getKernelVersion(mounts['root'])
if not xen_kernel_version:
raise RuntimeError("Unable to determine kernel version.")
partition = partitionDevice(primary_disk, primary_partnum)
__mkinitrd(mounts, primary_disk, partition, xen_kernel_version)
def prepFallback(mounts, primary_disk, primary_partnum):
kernel_version = getKernelVersion(mounts['root'])
# Copy /boot/xen-xxxx.gz to /boot/xen-fallback.gz
xen_gz = os.path.realpath(mounts['root'] + "/boot/xen.gz")
src = os.path.join(mounts['root'], "boot", os.path.basename(xen_gz))
dst = os.path.join(mounts['root'], 'boot/xen-fallback.gz')
shutil.copyfile(src, dst)
# Copy /boot/vmlinuz-yyyy to /boot/vmlinuz-fallback
src = os.path.join(mounts['root'], 'boot/vmlinuz-%s' % kernel_version)
dst = os.path.join(mounts['root'], 'boot/vmlinuz-fallback')
shutil.copyfile(src, dst)
# Extra modules to include in the fallback initrd. Include all
# currently loaded modules so the network module is picked up.
modules = []
proc_modules = open('/proc/modules', 'r')
for line in proc_modules:
modules.append(line.split(' ')[0])
proc_modules.close()
# Generate /boot/initrd-fallback.img.
cmd = ['dracut', '--verbose', '--add-drivers', ' '.join(modules), '--no-hostonly']
cmd += ['/boot/initrd-fallback.img', kernel_version]
if util.runCmd2(['chroot', mounts['root']] + cmd):
raise RuntimeError("Failed to generate fallback initrd")
def buildBootLoaderMenu(mounts, xen_version, xen_kernel_version, boot_config, serial, boot_serial, host_config, primary_disk, disk_label_suffix, fcoe_interfaces):
short_version = kernelShortVersion(xen_kernel_version)
common_xen_params = "dom0_mem=%dM,max:%dM" % ((host_config['dom0-mem'],) * 2)
common_xen_unsafe_params = "watchdog ucode=scan dom0_max_vcpus=1-%d" % host_config['dom0-vcpus']
safe_xen_params = ("nosmp noreboot noirqbalance no-mce no-bootscrub "
"no-numa no-hap no-mmcfg max_cstate=0 "
"nmi=ignore allow_unsafe")
xen_mem_params = "crashkernel=256M,below=4G"
# CA-103933 - AMD PCI-X Hypertransport Tunnel IOAPIC errata
rc, out = util.runCmd2(['lspci', '-n'], with_stdout=True)
if rc == 0 and ('1022:7451' in out or '1022:7459' in out):
common_xen_params += " ioapic_ack=old"
if "sched-gran" in host_config: