forked from rhinstaller/anaconda
-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
1243 lines (1018 loc) · 46.2 KB
/
__init__.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
# Entry point for anaconda's software management module.
#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
import os
import shutil
import re
import functools
from glob import glob
from fnmatch import fnmatch
from abc import ABCMeta
from pyanaconda.core.configuration.anaconda import conf
from pyanaconda.core.constants import DRACUT_ISODIR, DRACUT_REPODIR, DD_ALL, DD_FIRMWARE, \
DD_RPMS, INSTALL_TREE, ISO_DIR, GRAPHICAL_TARGET, TEXT_ONLY_TARGET
from pyanaconda.modules.common.constants.services import SERVICES
from pykickstart.constants import GROUP_ALL, GROUP_DEFAULT, GROUP_REQUIRED
from pyanaconda.flags import flags
from pyanaconda.core import util
from pyanaconda import isys
from pyanaconda.image import findFirstIsoImage
from pyanaconda.image import mountImage
from pyanaconda.image import opticalInstallMedia, verifyMedia, verify_valid_installtree
from pyanaconda.core.util import ProxyString, ProxyStringError
from pyanaconda.core.regexes import VERSION_DIGITS
from pyanaconda.payload.errors import PayloadError, PayloadSetupError, NoSuchGroup
from pyanaconda.payload import utils as payload_utils
from pyanaconda.payload.install_tree_metadata import InstallTreeMetadata
from pyanaconda.payload.requirement import PayloadRequirements
from pyanaconda.product import productName, productVersion
from pykickstart.parser import Group
from blivet.errors import StorageError
from pyanaconda.anaconda_loggers import get_module_logger
log = get_module_logger(__name__)
USER_AGENT = "%s (anaconda)/%s" % (productName, productVersion)
class Payload(metaclass=ABCMeta):
"""Payload is an abstract class for OS install delivery methods."""
def __init__(self, data):
"""Initialize Payload class
:param data: This param is a kickstart.AnacondaKSHandler class.
"""
self.data = data
self.storage = None
self.tx_id = None
self._install_tree_metadata = None
self._first_payload_reset = True
# A list of verbose error strings from the subclass
self.verbose_errors = []
self._session = util.requests_session()
# Additional packages required by installer based on used features
self.requirements = PayloadRequirements()
@property
def first_payload_reset(self):
return self._first_payload_reset
def setup(self, storage):
"""Do any payload-specific setup."""
self.storage = storage
self.verbose_errors = []
def unsetup(self):
"""Invalidate a previously setup payload."""
self.storage = None
self._install_tree_metadata = None
def post_setup(self):
"""Run specific payload post-configuration tasks on the end of
the restart_thread call.
This method could be overriden.
"""
self._first_payload_reset = False
def release(self):
"""Release any resources in use by this object, but do not do final
cleanup. This is useful for dealing with payload backends that do
not get along well with multithreaded programs.
"""
pass
def reset(self):
"""Reset the instance, not including ksdata."""
pass
def prepare_mount_targets(self, storage):
"""Run when physical storage is mounted, but other mount points may
not exist. Used by the RPMOSTreePayload subclass.
"""
pass
###
# METHODS FOR WORKING WITH REPOSITORIES
###
@property
def addons(self):
"""A list of addon repo identifiers."""
return [r.name for r in self.data.repo.dataList()]
@property
def base_repo(self):
"""Get the identifier of the current base repo or None."""
return None
@property
def mirrors_available(self):
"""Is the closest/fastest mirror option enabled? This does not make
sense for those payloads that do not support this concept.
"""
return conf.payload.enable_closest_mirror
@property
def disabled_repos(self):
"""A list of disabled repos."""
disabled = []
for repo in self.addons:
if not self.is_repo_enabled(repo):
disabled.append(repo)
return disabled
@property
def enabled_repos(self):
"""A list of enabled repos."""
enabled = []
for repo in self.addons:
if self.is_repo_enabled(repo):
enabled.append(repo)
return enabled
def is_repo_enabled(self, repo_id):
"""Return True if repo is enabled."""
repo = self.get_addon_repo(repo_id)
if repo:
return repo.enabled
else:
return False
def get_addon_repo(self, repo_id):
"""Return a ksdata Repo instance matching the specified repo id."""
repo = None
for r in self.data.repo.dataList():
if r.name == repo_id:
repo = r
break
return repo
def _repo_needs_network(self, repo):
"""Returns True if the ksdata repo requires networking."""
urls = [repo.baseurl]
if repo.mirrorlist:
urls.extend(repo.mirrorlist)
elif repo.metalink:
urls.extend(repo.metalink)
return self._source_needs_network(urls)
def _source_needs_network(self, sources):
"""Return True if the source requires network.
:param sources: Source paths for testing
:type sources: list
:returns: True if any source requires network
"""
network_protocols = ["http:", "ftp:", "nfs:", "nfsiso:"]
for s in sources:
if s and any(s.startswith(p) for p in network_protocols):
log.debug("Source %s needs network for installation", s)
return True
log.debug("Source doesn't require network for installation")
return False
@property
def needs_network(self):
"""Test base and additional repositories if they require network."""
url = ""
if self.data.method.method is None:
# closest mirror set
return True
elif self.data.method.method == "nfs":
# NFS is always on network
return True
elif self.data.method.method == "url":
if self.data.url.url:
url = self.data.url.url
elif self.data.url.mirrorlist:
url = self.data.url.mirrorlist
elif self.data.url.metalink:
url = self.data.url.metalink
return (self._source_needs_network([url]) or
any(self._repo_needs_network(repo) for repo in self.data.repo.dataList()))
def update_base_repo(self, fallback=True, checkmount=True):
"""Update the base repository from ksdata.method."""
pass
def gather_repo_metadata(self):
pass
def add_repo(self, ksrepo):
"""Add the repo given by the pykickstart Repo object ksrepo to the
system. The repo will be automatically enabled and its metadata
fetched.
Duplicate repos will not raise an error. They should just silently
take the place of the previous value.
"""
# Add the repo to the ksdata so it'll appear in the output ks file.
ksrepo.enabled = True
self.data.repo.dataList().append(ksrepo)
def remove_repo(self, repo_id):
repos = self.data.repo.dataList()
try:
idx = [repo.name for repo in repos].index(repo_id)
except ValueError:
log.error("failed to remove repo %s: not found", repo_id)
else:
repos.pop(idx)
def enable_repo(self, repo_id):
repo = self.get_addon_repo(repo_id)
if repo:
repo.enabled = True
def disable_repo(self, repo_id):
repo = self.get_addon_repo(repo_id)
if repo:
repo.enabled = False
def verify_available_repositories(self):
"""Verify availability of existing repositories.
This method tests if URL links from active repositories can be reached.
It is useful when network settings is changed so that we can verify if repositories
are still reachable.
This method should be overriden.
"""
log.debug("Install method %s is not able to verify availability",
self.__class__.__name__)
return False
###
# METHODS FOR WORKING WITH GROUPS
###
def is_language_supported(self, language):
"""Is the given language supported by the payload?
:param language: a name of the language
"""
return True
def is_locale_supported(self, language, locale):
"""Is the given locale supported by the payload?
:param language: a name of the language
:param locale: a name of the locale
"""
return True
def language_groups(self):
return []
def langpacks(self):
return []
def selected_groups(self):
"""Return list of selected group names from kickstart.
NOTE:
This group names can be mix of group IDs and other valid identifiers.
If you want group IDs use `selected_groups_IDs` instead.
:return: list of group names in a format specified by a kickstart file.
"""
return [grp.name for grp in self.data.packages.groupList]
def selected_groups_IDs(self):
"""Return list of IDs for selected groups.
Implementation depends on a specific payload class.
"""
return self.selected_groups()
def group_selected(self, groupid):
return Group(groupid) in self.data.packages.groupList
def select_group(self, groupid, default=True, optional=False):
if optional:
include = GROUP_ALL
elif default:
include = GROUP_DEFAULT
else:
include = GROUP_REQUIRED
grp = Group(groupid, include=include)
if grp in self.data.packages.groupList:
# I'm not sure this would ever happen, but ensure that re-selecting
# a group with a different types set works as expected.
if grp.include != include:
grp.include = include
return
if grp in self.data.packages.excludedGroupList:
self.data.packages.excludedGroupList.remove(grp)
self.data.packages.groupList.append(grp)
def deselect_group(self, groupid):
grp = Group(groupid)
if grp in self.data.packages.excludedGroupList:
return
if grp in self.data.packages.groupList:
self.data.packages.groupList.remove(grp)
self.data.packages.excludedGroupList.append(grp)
###
# METHODS FOR QUERYING STATE
###
@property
def space_required(self):
"""The total disk space (Size) required for the current selection."""
raise NotImplementedError()
@property
def kernel_version_list(self):
"""An iterable of the kernel versions installed by the payload."""
raise NotImplementedError()
###
# METHODS FOR TREE VERIFICATION
###
def _refresh_install_tree(self, url):
"""Refresh installation tree metadata.
:param url: url of the repo
:type url: string
"""
if not url:
return
if hasattr(self.data.method, "proxy"):
proxy_url = self.data.method.proxy
else:
proxy_url = None
# ssl_verify can be:
# - the path to a cert file
# - True, to use the system's certificates
# - False, to not verify
ssl_verify = getattr(self.data.method, "sslcacert", not flags.noverifyssl)
ssl_client_cert = getattr(self.data.method, "ssl_client_cert", None)
ssl_client_key = getattr(self.data.method, "ssl_client_key", None)
ssl_cert = (ssl_client_cert, ssl_client_key) if ssl_client_cert else None
log.debug("retrieving treeinfo from %s (proxy: %s ; ssl_verify: %s)",
url, proxy_url, ssl_verify)
proxies = {}
if proxy_url:
try:
proxy = ProxyString(proxy_url)
proxies = {"http": proxy.url,
"https": proxy.url}
except ProxyStringError as e:
log.info("Failed to parse proxy for _getTreeInfo %s: %s",
proxy_url, e)
headers = {"user-agent": USER_AGENT}
self._install_tree_metadata = InstallTreeMetadata()
try:
ret = self._install_tree_metadata.load_url(url, proxies, ssl_verify, ssl_cert, headers)
except IOError as e:
self._install_tree_metadata = None
self.verbose_errors.append(str(e))
log.warning("Install tree metadata fetching failed: %s", str(e))
return
if not ret:
log.warning("Install tree metadata can't be loaded!")
self._install_tree_metadata = None
def _get_release_version(self, url):
"""Return the release version of the tree at the specified URL."""
try:
version = re.match(VERSION_DIGITS, productVersion).group(1)
except AttributeError:
version = "rawhide"
log.debug("getting release version from tree at %s (%s)", url, version)
if self._install_tree_metadata:
version = self._install_tree_metadata.get_release_version()
log.debug("using treeinfo release version of %s", version)
else:
log.debug("using default release version of %s", version)
return version
###
# METHODS FOR MEDIA MANAGEMENT (XXX should these go in another module?)
###
@staticmethod
def _setup_device(device, mountpoint):
"""Prepare an install CD/DVD for use as a package source."""
log.info("setting up device %s and mounting on %s", device.name, mountpoint)
# Is there a symlink involved? If so, let's get the actual path.
# This is to catch /run/install/isodir vs. /mnt/install/isodir, for
# instance.
real_mountpoint = os.path.realpath(mountpoint)
mdev = payload_utils.get_mount_device(real_mountpoint)
if mdev:
if mdev:
log.warning("%s is already mounted on %s", mdev, mountpoint)
if mdev == device.path:
return
else:
payload_utils.unmount(real_mountpoint)
try:
device.setup()
device.format.setup(mountpoint=mountpoint)
except StorageError as e:
log.error("mount failed: %s", e)
device.teardown(recursive=True)
raise PayloadSetupError(str(e))
@staticmethod
def _setup_NFS(mountpoint, server, path, options):
"""Prepare an NFS directory for use as an install source."""
log.info("mounting %s:%s:%s on %s", server, path, options, mountpoint)
dev = payload_utils.get_mount_device(mountpoint)
# test if the mountpoint is occupied already
if dev:
_server, colon, _path = dev.partition(":")
if colon == ":" and server == _server and path == _path:
log.debug("%s:%s already mounted on %s", server, path, mountpoint)
return
else:
log.debug("%s already has something mounted on it", mountpoint)
payload_utils.unmount(mountpoint)
# mount the specified directory
url = "%s:%s" % (server, path)
if not options:
options = "nolock"
elif "nolock" not in options:
options += ",nolock"
payload_utils.mount(url, mountpoint, fstype="nfs", options=options)
###
# METHODS FOR INSTALLING THE PAYLOAD
###
def pre_install(self):
"""Perform pre-installation tasks."""
util.mkdirChain(util.getSysroot() + "/root")
self._write_module_blacklist()
def install(self):
"""Install the payload."""
raise NotImplementedError()
def _write_module_blacklist(self):
"""Copy modules from modprobe.blacklist=<module> on cmdline to
/etc/modprobe.d/anaconda-blacklist.conf so that modules will
continue to be blacklisted when the system boots.
"""
if "modprobe.blacklist" not in flags.cmdline:
return
util.mkdirChain(util.getSysroot() + "/etc/modprobe.d")
with open(util.getSysroot() + "/etc/modprobe.d/anaconda-blacklist.conf", "w") as f:
f.write("# Module blacklists written by anaconda\n")
for module in flags.cmdline["modprobe.blacklist"].split():
f.write("blacklist %s\n" % module)
def _copy_driver_disk_files(self):
# Multiple driver disks may be loaded, so we need to glob for all
# the firmware files in the common DD firmware directory
for f in glob(DD_FIRMWARE + "/*"):
try:
shutil.copyfile(f, "%s/lib/firmware/" % util.getSysroot())
except IOError as e:
log.error("Could not copy firmware file %s: %s", f, e.strerror)
# copy RPMS
for d in glob(DD_RPMS):
shutil.copytree(d, util.getSysroot() + "/root/" + os.path.basename(d))
# copy modules and firmware into root's home directory
if os.path.exists(DD_ALL):
try:
shutil.copytree(DD_ALL, util.getSysroot() + "/root/DD")
except IOError as e:
log.error("failed to copy driver disk files: %s", e.strerror)
# XXX TODO: real error handling, as this is probably going to
# prevent boot on some systems
@property
def needs_storage_configuration(self):
"""Should we write the storage before doing the installation?
Some payloads require that the storage configuration will be written out
before doing installation. Right now, this is basically just the dnfpayload.
"""
return False
@property
def handles_bootloader_configuration(self):
"""Whether this payload backend writes the bootloader configuration itself; if
False (the default), the generic bootloader configuration code will be used.
"""
return False
def recreate_initrds(self):
"""Recreate the initrds by calling new-kernel-pkg or dracut
This needs to be done after all configuration files have been
written, since dracut depends on some of them.
:returns: None
"""
if os.path.exists(util.getSysroot() + "/usr/sbin/new-kernel-pkg"):
use_dracut = False
else:
log.warning("new-kernel-pkg does not exist - grubby wasn't installed? "
" using dracut instead.")
use_dracut = True
for kernel in self.kernel_version_list:
log.info("recreating initrd for %s", kernel)
if not conf.target.is_image:
if use_dracut:
util.execInSysroot("depmod", ["-a", kernel])
util.execInSysroot("dracut",
["-f",
"/boot/initramfs-%s.img" % kernel,
kernel])
else:
util.execInSysroot("new-kernel-pkg",
["--mkinitrd", "--dracut", "--depmod",
"--update", kernel])
# if the installation is running in fips mode then make sure
# fips is also correctly enabled in the installed system
if flags.cmdline.get("fips") == "1":
# We use the --no-bootcfg option as we don't want fips-mode-setup to
# modify the bootloader configuration.
# Anaconda already does everything needed & it would require grubby to
# be available on the system.
util.execInSysroot("fips-mode-setup", ["--enable", "--no-bootcfg"])
else:
# hostonly is not sensible for disk image installations
# using /dev/disk/by-uuid/ is necessary due to disk image naming
util.execInSysroot("dracut",
["-N",
"--persistent-policy", "by-uuid",
"-f", "/boot/initramfs-%s.img" % kernel,
kernel])
def _set_default_boot_target(self):
"""Set the default systemd target for the system."""
if not os.path.exists(util.getSysroot() + "/etc/systemd/system"):
log.error("systemd is not installed -- can't set default target")
return
# If the target was already set, we don't have to continue.
services_proxy = SERVICES.get_proxy()
if services_proxy.DefaultTarget:
log.debug("The default target is already set.")
return
try:
import rpm
except ImportError:
log.info("failed to import rpm -- not adjusting default runlevel")
else:
ts = rpm.TransactionSet(util.getSysroot())
# XXX one day this might need to account for anaconda's display mode
if ts.dbMatch("provides", 'service(graphical-login)').count() and \
not flags.usevnc:
# We only manipulate the ksdata. The symlink is made later
# during the config write out.
services_proxy.SetDefaultTarget(GRAPHICAL_TARGET)
else:
services_proxy.SetDefaultTarget(TEXT_ONLY_TARGET)
def post_install(self):
"""Perform post-installation tasks."""
# set default systemd target
self._set_default_boot_target()
# write out static config (storage, modprobe, keyboard, ??)
# kickstart should handle this before we get here
self._copy_driver_disk_files()
log.info("Installation requirements: %s", self.requirements)
if not self.requirements.applied:
log.info("Some of the requirements were not applied.")
class PackagePayload(Payload, metaclass=ABCMeta):
"""A PackagePayload installs a set of packages onto the target system."""
def __init__(self, data):
super().__init__(data)
self.install_device = None
self._rpm_macros = []
# Used to determine which add-ons to display for each environment.
# The dictionary keys are environment IDs. The dictionary values are two-tuples
# consisting of lists of add-on group IDs. The first list is the add-ons specific
# to the environment, and the second list is the other add-ons possible for the
# environment.
self._environment_addons = {}
def pre_install(self):
super().pre_install()
# Set rpm-specific options
# nofsync speeds things up at the risk of rpmdb data loss in a crash.
# But if we crash mid-install you're boned anyway, so who cares?
self.rpm_macros.append(('__dbi_htconfig', 'hash nofsync %{__dbi_other} %{__dbi_perms}'))
if self.data.packages.excludeDocs:
self.rpm_macros.append(('_excludedocs', '1'))
if self.data.packages.instLangs is not None:
# Use nil if instLangs is empty
self.rpm_macros.append(('_install_langs', self.data.packages.instLangs or '%{nil}'))
if conf.security.selinux:
for d in ["/tmp/updates",
"/etc/selinux/targeted/contexts/files",
"/etc/security/selinux/src/policy",
"/etc/security/selinux"]:
f = d + "/file_contexts"
if os.access(f, os.R_OK):
self.rpm_macros.append(('__file_context_path', f))
break
else:
self.rpm_macros.append(('__file_context_path', '%{nil}'))
# Add platform specific group
groupid = util.get_platform_groupid()
if groupid and groupid in self.groups:
self.requirements.add_groups([groupid], reason="platform")
elif groupid:
log.warning("Platform group %s not available.", groupid)
@property
def kernel_packages(self):
if "kernel" in self.data.packages.excludedList:
return []
kernels = ["kernel"]
if payload_utils.arch_is_x86() and isys.isPaeAvailable():
kernels.insert(0, "kernel-PAE")
# ARM systems use either the standard Multiplatform or LPAE platform
if payload_utils.arch_is_arm():
if isys.isLpaeAvailable():
kernels.insert(0, "kernel-lpae")
return kernels
@property
def kernel_version_list(self):
# Find all installed rpms that provide 'kernel'
# If a PackagePayload is in use, rpm needs to be available
try:
import rpm
except ImportError:
raise PayloadError("failed to import rpm-python, cannot determine kernel versions")
files = []
ts = rpm.TransactionSet(util.getSysroot())
mi = ts.dbMatch('providename', 'kernel')
for hdr in mi:
unicode_fnames = (f.decode("utf-8") for f in hdr.filenames)
# Find all /boot/vmlinuz- files and strip off vmlinuz-
files.extend((f.split("/")[-1][8:] for f in unicode_fnames
if fnmatch(f, "/boot/vmlinuz-*") or
fnmatch(f, "/boot/efi/EFI/%s/vmlinuz-*" % conf.bootloader.efi_dir)))
return sorted(files, key=functools.cmp_to_key(payload_utils.version_cmp))
@property
def rpm_macros(self):
"""A list of (name, value) pairs to define as macros in the rpm transaction."""
return self._rpm_macros
@rpm_macros.setter
def rpm_macros(self, value):
self._rpm_macros = value
def reset(self):
self.reset_install_device()
self.reset_additional_repos()
def reset_install_device(self):
"""Unmount the previous base repo and reset the install_device."""
# cdrom: install_device.teardown (INSTALL_TREE)
# hd: umount INSTALL_TREE, install_device.teardown (ISO_DIR)
# nfs: umount INSTALL_TREE
# nfsiso: umount INSTALL_TREE, umount ISO_DIR
if os.path.ismount(INSTALL_TREE):
if self.install_device and \
payload_utils.get_mount_device(INSTALL_TREE) == self.install_device.path:
self.install_device.teardown(recursive=True)
else:
payload_utils.unmount(INSTALL_TREE, raise_exc=True)
if os.path.ismount(ISO_DIR):
if self.install_device and \
payload_utils.get_mount_device(ISO_DIR) == self.install_device.path:
self.install_device.teardown(recursive=True)
# The below code will fail when nfsiso is the stage2 source
# But if we don't do this we may not be able to switch from
# one nfsiso repo to another nfsiso repo. We need to have a
# way to detect the stage2 state and work around it.
# Commenting out the below is a hack for F18. FIXME
# else:
# # NFS
# blivet.util.umount(ISO_DIR)
self.install_device = None
def reset_additional_repos(self):
for name in self._find_mounted_additional_repos():
installation_dir = INSTALL_TREE + "-" + name
self._unmount_source_directory(installation_dir)
iso_dir = ISO_DIR + "-" + name
self._unmount_source_directory(iso_dir)
def _find_mounted_additional_repos(self):
prefix = ISO_DIR + "-"
prefix_len = len(prefix)
result = []
for dir_path in glob(prefix + "*"):
result.append(dir_path[prefix_len:])
return result
def _unmount_source_directory(self, mount_point):
if os.path.ismount(mount_point):
device_path = payload_utils.get_mount_device(mount_point)
device = self.storage.devicetree.get_device_by_path(device_path)
if device:
device.teardown(recursive=True)
else:
payload_utils.unmount(mount_point, raise_exc=True)
def _setup_media(self, device):
method = self.data.method
if method.method == "harddrive":
try:
method.dir = self._find_and_mount_iso(device, ISO_DIR, method.dir, INSTALL_TREE)
except PayloadSetupError as ex:
log.warning(str(ex))
try:
self._setup_install_tree(device, method.dir, INSTALL_TREE)
except PayloadSetupError as ex:
log.error(str(ex))
raise PayloadSetupError("failed to setup installation tree or ISO from HDD")
# Check to see if the device is already mounted, in which case
# we don't need to mount it again
elif method.method == "cdrom" and payload_utils.get_mount_paths(device.path):
return
else:
device.format.setup(mountpoint=INSTALL_TREE)
def _find_and_mount_iso(self, device, device_mount_dir, iso_path, iso_mount_dir):
"""Find and mount installation source from ISO on device.
Return changed path to the iso to save looking for iso in the future call.
"""
self._setup_device(device, mountpoint=device_mount_dir)
# check for ISO images in the newly mounted dir
path = device_mount_dir
if iso_path:
path = os.path.normpath("%s/%s" % (path, iso_path))
# XXX it would be nice to streamline this when we're just setting
# things back up after storage activation instead of having to
# pretend we don't already know which ISO image we're going to
# use
image = findFirstIsoImage(path)
if not image:
device.teardown(recursive=True)
raise PayloadSetupError("failed to find valid iso image")
if path.endswith(".iso"):
path = os.path.dirname(path)
# this could already be set up the first time through
if not os.path.ismount(iso_mount_dir):
# mount the ISO on a loop
image = os.path.normpath("%s/%s" % (path, image))
mountImage(image, iso_mount_dir)
if not iso_path.endswith(".iso"):
result_path = os.path.normpath("%s/%s" % (iso_path,
os.path.basename(image)))
while result_path.startswith("/"):
# ridiculous
result_path = result_path[1:]
return result_path
return iso_path
def _setup_install_tree(self, device, install_tree_path, device_mount_dir):
self._setup_device(device, mountpoint=device_mount_dir)
path = os.path.normpath("%s/%s" % (device_mount_dir, install_tree_path))
if not verify_valid_installtree(path):
device.teardown(recursive=True)
raise PayloadSetupError("failed to find valid installation tree")
def _setup_install_device(self, storage, checkmount):
# XXX FIXME: does this need to handle whatever was set up by dracut?
method = self.data.method
url = None
mirrorlist = None
metalink = None
# See if we already have stuff mounted due to dracut
isodev = payload_utils.get_mount_device(DRACUT_ISODIR)
device = payload_utils.get_mount_device(DRACUT_REPODIR)
if method.method == "harddrive":
log.debug("Setting up harddrive install device")
url = self._setup_harddrive_device(storage, method, isodev, device)
elif method.method == "nfs":
log.debug("Setting up nfs install device")
url = self._setup_nfs_device(storage, method, isodev, device)
elif method.method == "url":
url = method.url
mirrorlist = method.mirrorlist
metalink = method.metalink
elif method.method == "hmc":
log.debug("Setting up hmc install device")
url = self._setup_hmc_device(storage, method, isodev, device)
elif method.method == "cdrom" or (checkmount and not method.method):
log.debug("Setting up cdrom install device")
url = self._setup_cdrom_device(storage, method, isodev, device)
return url, mirrorlist, metalink
def _setup_harddrive_device(self, storage, method, isodev, device):
url = None
need_mount = False
if method.biospart:
log.warning("biospart support is not implemented")
dev_spec = method.biospart
else:
dev_spec = method.partition
need_mount = True
# See if we used this method for stage2, thus dracut left it
if isodev and method.partition and \
method.partition in isodev and \
DRACUT_ISODIR in device:
# Everything should be setup
url = "file://" + DRACUT_REPODIR
need_mount = False
# We don't setup an install_device here
# because we can't tear it down
iso_device = storage.devicetree.resolve_device(dev_spec)
if need_mount:
if not iso_device:
raise PayloadSetupError("device for HDISO install %s does not exist" % dev_spec)
self._setup_media(iso_device)
url = "file://" + INSTALL_TREE
self.install_device = iso_device
return url
def _setup_nfs_device(self, storage, method, isodev, device):
# There are several possible scenarios here:
# 1. dracut could have mounted both the nfs repo and an iso and used
# the stage2 from inside the iso to boot from.
# isodev and device will be set in this case.
# 2. dracut could have mounted the nfs repo and used a stage2 from
# the NFS mount w/o mounting the iso.
# isodev will be None and device will be the nfs: path
# 3. dracut did not mount the nfs (eg. stage2 came from elsewhere)
# isodev and/or device are None
# 4. The repo may not contain an iso, in that case use it as is
url = None
path = None
if isodev and device:
path = util.parseNfsUrl('nfs:%s' % isodev)[2]
# See if the dir holding the iso is what we want
# and also if we have an iso mounted to /run/install/repo
if path and path in isodev and DRACUT_ISODIR in device:
# Everything should be setup
url = "file://" + DRACUT_REPODIR
else:
# see if the nfs dir is mounted
need_mount = True
if device:
_options, host, path = util.parseNfsUrl('nfs:%s' % device)
if method.server and method.server == host and \
method.dir and method.dir == path:
need_mount = False
path = DRACUT_REPODIR
elif isodev:
# isodev with no device can happen when options on an existing
# nfs mount have changed. It is already mounted, but on INSTALL_TREE
# which is the same as DRACUT_ISODIR, making it hard for _setup_NFS
# to detect that it is already mounted.
_options, host, path = util.parseNfsUrl('nfs:%s' % isodev)
if path and path in isodev:
need_mount = False
path = DRACUT_ISODIR
if need_mount:
# Mount the NFS share on INSTALL_TREE. If it ends up
# being nfsiso we will move the mountpoint to ISO_DIR.
if method.dir.endswith(".iso"):
nfs_dir = os.path.dirname(method.dir)
else:
nfs_dir = method.dir
self._setup_NFS(INSTALL_TREE, method.server, nfs_dir, method.opts)
path = INSTALL_TREE
# check for ISO images in the newly mounted dir
if method.dir.endswith(".iso"):
# if the given URL includes a specific ISO image file, use it
image_file = os.path.basename(method.dir)
path = os.path.normpath("%s/%s" % (path, image_file))
image = findFirstIsoImage(path)
# An image was found, mount it on INSTALL_TREE
if image:
if path.startswith(INSTALL_TREE):
# move the INSTALL_TREE mount to ISO_DIR so we can