-
Notifications
You must be signed in to change notification settings - Fork 345
/
__init__.py
1471 lines (1207 loc) · 54 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
# __init__.py
# Entry point for anaconda's software management module.
#
# Copyright (C) 2012 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.
#
"""
TODO
- error handling!!!
- document all methods
"""
import os
import requests
import configparser
import shutil
from glob import glob
from fnmatch import fnmatch
import threading
import re
import functools
import time
from blivet.size import Size
from pyanaconda.iutil import requests_session
if __name__ == "__main__":
from pyanaconda import anaconda_log
anaconda_log.init()
from pyanaconda.constants import DRACUT_ISODIR, DRACUT_REPODIR, DD_ALL, DD_FIRMWARE, DD_RPMS, INSTALL_TREE, ISO_DIR
from pyanaconda.constants import THREAD_STORAGE, THREAD_WAIT_FOR_CONNECTING_NM, THREAD_PAYLOAD
from pyanaconda.constants import THREAD_PAYLOAD_RESTART
from pykickstart.constants import GROUP_ALL, GROUP_DEFAULT, GROUP_REQUIRED
from pyanaconda.flags import flags
from pyanaconda.i18n import _, N_
from pyanaconda import iutil
from pyanaconda import isys
from pyanaconda.image import findFirstIsoImage
from pyanaconda.image import mountImage
from pyanaconda.image import opticalInstallMedia, verifyMedia
from pyanaconda.iutil import ProxyString, ProxyStringError, xprogressive_delay
from pyanaconda.threads import threadMgr, AnacondaThread
from pyanaconda.regexes import VERSION_DIGITS
from pykickstart.parser import Group
import logging
log = logging.getLogger("packaging")
from blivet.errors import StorageError
import blivet.util
import blivet.arch
from blivet.platform import platform
from blivet import set_sysroot
from pyanaconda.product import productName, productVersion
USER_AGENT = "%s (anaconda)/%s" % (productName, productVersion)
from distutils.version import LooseVersion
REPO_NOT_SET = False
MAX_TREEINFO_DOWNLOAD_RETRIES = 6
def versionCmp(v1, v2):
"""Compare two version number strings."""
firstVersion = LooseVersion(v1)
secondVersion = LooseVersion(v2)
return (firstVersion > secondVersion) - (firstVersion < secondVersion)
###
### ERROR HANDLING
###
class PayloadError(Exception):
pass
class MetadataError(PayloadError):
pass
class NoNetworkError(PayloadError):
pass
# setup
class PayloadSetupError(PayloadError):
pass
class ImageMissingError(PayloadSetupError):
pass
class ImageDirectoryMountError(PayloadSetupError):
pass
# software selection
class NoSuchGroup(PayloadError):
def __init__(self, group, adding=True, required=False):
PayloadError.__init__(self, group)
self.group = group
self.adding = adding
self.required = required
class NoSuchPackage(PayloadError):
def __init__(self, package, required=False):
PayloadError.__init__(self, package)
self.package = package
self.required = required
class DependencyError(PayloadError):
pass
# installation
class PayloadInstallError(PayloadError):
pass
class Payload(object):
"""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.
"""
if self.__class__ is Payload:
raise TypeError("Payload is an abstract class")
self.data = data
self.storage = None
self.instclass = None
self.txID = None
# A list of verbose error strings from the subclass
self.verbose_errors = []
self._session = requests_session()
def setup(self, storage, instClass):
"""Do any payload-specific setup."""
self.storage = storage
self.instclass = instClass
self.verbose_errors = []
def unsetup(self):
"""Invalidate a previously setup payload."""
self.storage = None
self.instclass = None
def preStorage(self):
"""Do any payload-specific work necessary before writing the storage
configuration. This method need not be provided by all payloads.
"""
pass
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 prepareMountTargets(self, storage):
"""Run when physical storage is mounted, but other mount points may
not exist. Used by the RPMOSTreePayload subclass.
"""
pass
def requiredDeviceSize(self, format_class):
"""We need to provide information how big device is required to have successful
installation. ``format_class`` should be filesystem format
class for the **root** filesystem this class carry information about
metadata size.
:param format_class: Class of the filesystem format.
:type format_class: Class which inherits :class:`blivet.formats.fs.FS`
:returns: Size of the device with given filesystem format.
:rtype: :class:`blivet.size.Size`
"""
device_size = format_class.get_required_size(self.spaceRequired)
return device_size.round_to_nearest(Size("1 MiB"))
###
### 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 baseRepo(self):
"""Get the identifier of the current base repo or None."""
return None
@property
def mirrorEnabled(self):
"""Is the closest/fastest mirror option enabled? This does not make
sense for those payloads that do not support this concept.
"""
return True
def isRepoEnabled(self, repo_id):
"""Return True if repo is enabled."""
repo = self.getAddOnRepo(repo_id)
if repo:
return repo.enabled
else:
return False
def getAddOnRepo(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 _repoNeedsNetwork(self, repo):
"""Returns True if the ksdata repo requires networking."""
urls = [repo.baseurl]
if repo.mirrorlist:
urls.extend(repo.mirrorlist)
return self._sourceNeedsNetwork(urls)
def _sourceNeedsNetwork(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 needsNetwork(self):
"""Test base and additional repositories if they require network."""
url = ""
if 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
else:
url = self.data.url.mirrorlist
return (self._sourceNeedsNetwork([url]) or
any(self._repoNeedsNetwork(repo) for repo in self.data.repo.dataList()))
def updateBaseRepo(self, fallback=True, checkmount=True):
"""Update the base repository from ksdata.method."""
pass
def gatherRepoMetadata(self):
pass
def addRepo(self, newrepo):
"""Add the repo given by the pykickstart Repo object newrepo 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.
self.data.repo.dataList().append(newrepo)
def removeRepo(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 enableRepo(self, repo_id):
repo = self.getAddOnRepo(repo_id)
if repo:
repo.enabled = True
def disableRepo(self, repo_id):
repo = self.getAddOnRepo(repo_id)
if repo:
repo.enabled = False
def verifyAvailableRepositories(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 languageGroups(self):
return []
def selectedGroups(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 `selectedGroupsIDs` 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 selectedGroupsIDs(self):
"""Return list of IDs for selected groups.
Implementation depends on a specific payload class.
"""
return self.selectedGroups()
def groupSelected(self, groupid):
return Group(groupid) in self.data.packages.groupList
def selectGroup(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 deselectGroup(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 spaceRequired(self):
"""The total disk space (Size) required for the current selection."""
raise NotImplementedError()
@property
def kernelVersionList(self):
"""An iterable of the kernel versions installed by the payload."""
raise NotImplementedError()
##
## METHODS FOR TREE VERIFICATION
##
def _getTreeInfo(self, url, proxy_url, sslverify):
"""Retrieve treeinfo and return the path to the local file.
:param baseurl: url of the repo
:type baseurl: string
:param proxy_url: Optional full proxy URL of or ""
:type proxy_url: string
:param sslverify: True if SSL certificate should be verified
:type sslverify: bool
:returns: Path to retrieved .treeinfo file or None
:rtype: string or None
"""
if not url:
return None
log.debug("retrieving treeinfo from %s (proxy: %s ; sslverify: %s)",
url, proxy_url, sslverify)
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)
# Retry treeinfo downloads with a progressively longer pause,
# so NetworkManager have a chance setup a network and we have
# full connectivity before trying to download things. (#1292613)
xdelay = xprogressive_delay()
response = None
ret_code = [None, None]
headers = {"user-agent": USER_AGENT}
for retry_count in range(0, MAX_TREEINFO_DOWNLOAD_RETRIES + 1):
if retry_count > 0:
time.sleep(next(xdelay))
# Downloading .treeinfo
log.info("Trying to download '.treeinfo'")
(response, ret_code[0]) = self._download_treeinfo_file(url, ".treeinfo",
headers, proxies, sslverify)
if response:
break
# Downloading treeinfo
log.info("Trying to download 'treeinfo'")
(response, ret_code[1]) = self._download_treeinfo_file(url, "treeinfo",
headers, proxies, sslverify)
if response:
break
# The [.]treeinfo wasn't downloaded. Try it again if [.]treeinfo
# is on the server.
#
# Server returned HTTP 404 code -> no need to try again
if (ret_code[0] is not None and ret_code[0] == 404 and ret_code[1] is not None and ret_code[1] == 404):
response = None
log.error("Got HTTP 404 Error when downloading [.]treeinfo files")
break
if retry_count < MAX_TREEINFO_DOWNLOAD_RETRIES:
# retry
log.info("Retrying repo info download for %s, retrying (%d/%d)",
url, retry_count + 1, MAX_TREEINFO_DOWNLOAD_RETRIES)
else:
# run out of retries
err_msg = ("Repo info download for %s failed after %d retries" %
(url, retry_count))
log.error(err_msg)
self.verbose_errors.append(err_msg)
response = None
if response:
# get the treeinfo contents
text = response.text
# close the response
response.close()
# write the local treeinfo file
with open("/tmp/.treeinfo", "w") as f:
f.write(text)
# and also return the treeinfo contents as a string
return text
else:
return None
def _download_treeinfo_file(self, url, file_name, headers, proxies, verify):
try:
result = self._session.get("%s/%s" % (url, file_name), headers=headers,
proxies=proxies, verify=verify)
# Server returned HTTP 4XX or 5XX codes
if result.status_code >= 400 and result.status_code < 600:
log.info("Server returned %i code", result.status_code)
return (None, result.status_code)
log.debug("Retrieved '%s' from %s", file_name, url)
except requests.exceptions.RequestException as e:
log.info("Error downloading '%s': %s", file_name, e)
return (None, None)
return (result, result.status_code)
def _getReleaseVersion(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 hasattr(self.data.method, "proxy"):
proxy = self.data.method.proxy
else:
proxy = None
treeinfo = self._getTreeInfo(url, proxy, not flags.noverifyssl)
if treeinfo:
c = configparser.ConfigParser()
c.read(treeinfo)
try:
# Trim off any -Alpha or -Beta
version = re.match(VERSION_DIGITS, c.get("general", "version")).group(1)
except AttributeError:
version = "rawhide"
except configparser.Error:
pass
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 _setupDevice(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.
realMountpoint = os.path.realpath(mountpoint)
if os.path.ismount(realMountpoint):
mdev = blivet.util.get_mount_device(realMountpoint)
if mdev:
log.warning("%s is already mounted on %s", mdev, mountpoint)
if mdev == device.path:
return
else:
try:
blivet.util.umount(realMountpoint)
except OSError as e:
log.error(str(e))
log.info("umount failed -- mounting on top of it")
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 _setupNFS(mountpoint, server, path, options):
"""Prepare an NFS directory for use as a package source."""
log.info("mounting %s:%s:%s on %s", server, path, options, mountpoint)
if os.path.ismount(mountpoint):
dev = blivet.util.get_mount_device(mountpoint)
_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)
try:
blivet.util.umount(mountpoint)
except OSError as e:
log.error(str(e))
log.info("umount failed -- mounting on top of it")
# mount the specified directory
url = "%s:%s" % (server, path)
if not options:
options = "nolock"
elif "nolock" not in options:
options += ",nolock"
try:
blivet.util.mount(url, mountpoint, fstype="nfs", options=options)
except OSError as e:
raise PayloadSetupError(str(e))
###
### METHODS FOR INSTALLING THE PAYLOAD
###
def preInstall(self, packages=None, groups=None):
"""Perform pre-installation tasks."""
iutil.mkdirChain(iutil.getSysroot() + "/root")
self._writeModuleBlacklist()
def install(self):
"""Install the payload."""
raise NotImplementedError()
def _writeModuleBlacklist(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
iutil.mkdirChain(iutil.getSysroot() + "/etc/modprobe.d")
with open(iutil.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 _copyDriverDiskFiles(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/" % iutil.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, iutil.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, iutil.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
def recreateInitrds(self):
"""Recreate the initrds by calling new-kernel-pkg
This needs to be done after all configuration files have been
written, since dracut depends on some of them.
:returns: None
"""
if not os.path.exists(iutil.getSysroot() + "/usr/sbin/new-kernel-pkg"):
log.error("new-kernel-pkg does not exist - grubby wasn't installed? skipping")
return
for kernel in self.kernelVersionList:
log.info("recreating initrd for %s", kernel)
if not flags.imageInstall:
iutil.execInSysroot("new-kernel-pkg",
["--mkinitrd", "--dracut",
"--depmod", "--update", kernel])
else:
# hostonly is not sensible for disk image installations
# using /dev/disk/by-uuid/ is necessary due to disk image naming
iutil.execInSysroot("dracut",
["-N",
"--persistent-policy", "by-uuid",
"-f", "/boot/initramfs-%s.img" % kernel,
kernel])
def _setDefaultBootTarget(self):
"""Set the default systemd target for the system."""
if not os.path.exists(iutil.getSysroot() + "/etc/systemd/system"):
log.error("systemd is not installed -- can't set default target")
return
# If X was already requested we don't have to continue
if self.data.xconfig.startX:
return
try:
import rpm
except ImportError:
log.info("failed to import rpm -- not adjusting default runlevel")
else:
ts = rpm.TransactionSet(iutil.getSysroot())
# XXX one day this might need to account for anaconda's display mode
if ts.dbMatch("provides", 'service(graphical-login)').count() and \
ts.dbMatch('provides', 'xorg-x11-server-Xorg').count() and \
not flags.usevnc:
# We only manipulate the ksdata. The symlink is made later
# during the config write out.
self.data.xconfig.startX = True
def dracutSetupArgs(self):
args = []
try:
import rpm
except ImportError:
pass
else:
iutil.resetRpmDb()
ts = rpm.TransactionSet(iutil.getSysroot())
# Only add "rhgb quiet" on non-s390, non-serial installs
if iutil.isConsoleOnVirtualTerminal() and \
(ts.dbMatch('provides', 'rhgb').count() or \
ts.dbMatch('provides', 'plymouth').count()):
args.extend(["rhgb", "quiet"])
return args
def postInstall(self):
"""Perform post-installation tasks."""
# set default systemd target
self._setDefaultBootTarget()
# write out static config (storage, modprobe, keyboard, ??)
# kickstart should handle this before we get here
self._copyDriverDiskFiles()
def writeStorageEarly(self):
"""Some payloads require that the storage configuration be written out
before doing installation. Right now, this is basically just the
dnfpayload. Payloads should only implement one of these methods
by overriding the unneeded one with a pass.
"""
if not flags.dirInstall:
self.storage.write()
def writeStorageLate(self):
"""Some payloads require that the storage configuration be written out
after doing installation. Right now, this is basically every payload
except for dnf. Payloads should only implement one of these methods
by overriding the unneeded one with a pass.
"""
if iutil.getSysroot() != iutil.getTargetPhysicalRoot():
set_sysroot(iutil.getTargetPhysicalRoot(), iutil.getSysroot())
self.prepareMountTargets(self.storage)
if not flags.dirInstall:
self.storage.write()
# Inherit abstract methods from Payload
# pylint: disable=abstract-method
class ImagePayload(Payload):
"""An ImagePayload installs an OS image to the target system."""
def __init__(self, data):
if self.__class__ is ImagePayload:
raise TypeError("ImagePayload is an abstract class")
Payload.__init__(self, data)
# Inherit abstract methods from ImagePayload
# pylint: disable=abstract-method
class ArchivePayload(ImagePayload):
"""An ArchivePayload unpacks source archives onto the target system."""
def __init__(self, data):
if self.__class__ is ArchivePayload:
raise TypeError("ArchivePayload is an abstract class")
ImagePayload.__init__(self, data)
class PackagePayload(Payload):
"""A PackagePayload installs a set of packages onto the target system."""
DEFAULT_REPOS = [productName.split('-')[0].lower(), "rawhide"] # pylint: disable=no-member
def __init__(self, data):
if self.__class__ is PackagePayload:
raise TypeError("PackagePayload is an abstract class")
super(PackagePayload, self).__init__(data)
self.install_device = None
self._rpm_macros = []
self.requiredPackages = []
self.requiredGroups = []
# 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._environmentAddons = {}
def preInstall(self, packages=None, groups=None):
super(PackagePayload, self).preInstall()
# 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.rpmMacros.append(('__dbi_htconfig', 'hash nofsync %{__dbi_other} %{__dbi_perms}'))
if self.data.packages.excludeDocs:
self.rpmMacros.append(('_excludedocs', '1'))
if self.data.packages.instLangs is not None:
# Use nil if instLangs is empty
self.rpmMacros.append(('_install_langs', self.data.packages.instLangs or '%{nil}'))
if flags.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.rpmMacros.append(('__file_context_path', f))
break
else:
self.rpmMacros.append(('__file_context_path', '%{nil}'))
# Add platform specific group
groupid = iutil.get_platform_groupid()
if groupid and groupid in self.groups:
if isinstance(groups, list):
log.info("Adding platform group %s", groupid)
groups.append(groupid)
else:
log.warning("Could not add %s to groups, not a list.", groupid)
elif groupid:
log.warning("Platform group %s not available.", groupid)
def postSetup(self):
"""Run specific payload post-configuration tasks on the end of
the restartThread call.
This method could be overriden.
"""
pass
@property
def kernelPackages(self):
if "kernel" in self.data.packages.excludedList:
return []
kernels = ["kernel"]
if blivet.arch.is_x86(32) and isys.isPaeAvailable():
kernels.insert(0, "kernel-PAE")
# most ARM systems use platform-specific kernels
if blivet.arch.is_arm():
if platform.arm_machine is not None:
kernels = ["kernel-%s" % platform.arm_machine]
if isys.isLpaeAvailable():
kernels.insert(0, "kernel-lpae")
return kernels
@property
def kernelVersionList(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(iutil.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-*" % self.instclass.efi_dir)))
return sorted(files, key=functools.cmp_to_key(versionCmp))
@property
def rpmMacros(self):
"""A list of (name, value) pairs to define as macros in the rpm transaction."""
return self._rpm_macros
@rpmMacros.setter
def rpmMacros(self, value):
self._rpm_macros = value
def reset(self):
self.reset_install_device()
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) and not flags.testing:
if self.install_device and \
blivet.util.get_mount_device(INSTALL_TREE) == self.install_device.path:
self.install_device.teardown(recursive=True)
else:
blivet.util.umount(INSTALL_TREE)
if os.path.ismount(ISO_DIR) and not flags.testing:
if self.install_device and \
blivet.util.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 _setupMedia(self, device):
method = self.data.method
if method.method == "harddrive":
self._setupDevice(device, mountpoint=ISO_DIR)
# check for ISO images in the newly mounted dir
path = ISO_DIR
if method.dir:
path = os.path.normpath("%s/%s" % (path, method.dir))
# 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(INSTALL_TREE):
# mount the ISO on a loop
image = os.path.normpath("%s/%s" % (path, image))
mountImage(image, INSTALL_TREE)
if not method.dir.endswith(".iso"):
method.dir = os.path.normpath("%s/%s" % (method.dir,
os.path.basename(image)))
while method.dir.startswith("/"):
# riduculous
method.dir = method.dir[1:]
# 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 blivet.util.get_mount_paths(device.path):
return
else:
device.format.setup(mountpoint=INSTALL_TREE)
def _setupInstallDevice(self, storage, checkmount):
# XXX FIXME: does this need to handle whatever was set up by dracut?
method = self.data.method
sslverify = True
url = None
mirrorlist = None
# See if we already have stuff mounted due to dracut
isodev = blivet.util.get_mount_device(DRACUT_ISODIR)
device = blivet.util.get_mount_device(DRACUT_REPODIR)
if method.method == "harddrive":
if method.biospart:
log.warning("biospart support is not implemented")
devspec = method.biospart
else:
devspec = method.partition
needmount = 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: