/
devicetree.py
2714 lines (2307 loc) · 112 KB
/
devicetree.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
# devicetree.py
# Device management for anaconda's storage configuration module.
#
# Copyright (C) 2009-2014 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.
#
# Red Hat Author(s): Dave Lehman <dlehman@redhat.com>
#
import os
import block
import re
import shutil
import pprint
import copy
from .errors import CryptoError, DeviceError, DeviceTreeError, DiskLabelCommitError, DMError, FSError, InvalidDiskLabelError, LUKSError, MDRaidError, StorageError, UnusableConfigurationError
from .devices import BTRFSDevice, BTRFSSubVolumeDevice, BTRFSVolumeDevice, BTRFSSnapShotDevice
from .devices import DASDDevice, DMDevice, DMLinearDevice, DMRaidArrayDevice, DiskDevice
from .devices import FcoeDiskDevice, FileDevice, LoopDevice, LUKSDevice
from .devices import LVMLogicalVolumeDevice, LVMVolumeGroupDevice
from .devices import LVMThinPoolDevice, LVMThinLogicalVolumeDevice
from .devices import LVMSnapShotDevice, LVMThinSnapShotDevice
from .devices import MDRaidArrayDevice, MDBiosRaidArrayDevice
from .devices import MultipathDevice, NoDevice, OpticalDevice
from .devices import PartitionDevice, ZFCPDiskDevice, iScsiDiskDevice
from .devices import devicePathToName
from .deviceaction import ActionCreateDevice, ActionDestroyDevice, action_type_from_string, action_object_from_string
from . import formats
from .formats import getFormat
from .formats.fs import nodev_filesystems
from .devicelibs import mdraid
from .devicelibs import dm
from .devicelibs import lvm
from .devicelibs import mpath
from .devicelibs import loop
from .devicelibs import edd
from . import udev
from . import util
from . import mounts
from .platform import platform
from . import tsort
from .flags import flags
from .storage_log import log_exception_info, log_method_call, log_method_return
from .i18n import _
from .size import Size
import logging
log = logging.getLogger("blivet")
class DeviceTree(object):
""" A quasi-tree that represents the devices in the system.
The tree contains a list of :class:`~.devices.StorageDevice` instances,
which does not necessarily reflect the actual state of the system's
devices. :class:`~.deviceaction.DeviceAction` is used to perform
modifications to the tree, except when initially populating the tree.
:class:`~.deviceaction.DeviceAction` instances are registered, possibly
causing the addition or removal of :class:`~.devices.StorageDevice`
instances to/from the tree. A :class:`~.deviceaction.DeviceAction`
is reversible up to the time its 'execute' method is called.
Only one action of any given type/object pair should exist for
any given device at any given time.
:class:`~.deviceaction.DeviceAction` instances can only be registered
for leaf devices, except for resize actions.
"""
def __init__(self, conf=None, passphrase=None, luksDict=None,
iscsi=None, dasd=None):
"""
:keyword conf: storage discovery configuration
:type conf: :class:`~.StorageDiscoveryConfig`
:keyword passphrase: default LUKS passphrase
:keyword luksDict: a dict with UUID keys and passphrase values
:type luksDict: dict
:keyword iscsi: ISCSI control object
:type iscsi: :class:`~.iscsi.iscsi`
:keyword dasd: DASD control object
:type dasd: :class:`~.dasd.DASD`
"""
self.mountsCache = mounts.MountsCache()
self.reset(conf, passphrase, luksDict, iscsi, dasd)
def reset(self, conf=None, passphrase=None, luksDict=None,
iscsi=None, dasd=None):
""" Reset the instance to its initial state. """
# internal data members
self._devices = []
self._actions = []
self._completed_actions = []
# a list of all device names we encounter
self.names = []
self._hidden = []
# indicates whether or not the tree has been fully populated
self.populated = False
self.exclusiveDisks = getattr(conf, "exclusiveDisks", [])
self.ignoredDisks = getattr(conf, "ignoredDisks", [])
self.iscsi = iscsi
self.dasd = dasd
self.diskImages = {}
images = getattr(conf, "diskImages", {})
if images:
# this will overwrite self.exclusiveDisks
self.setDiskImages(images)
# protected device specs as provided by the user
self.protectedDevSpecs = getattr(conf, "protectedDevSpecs", [])
self.liveBackingDevice = None
# names of protected devices at the time of tree population
self.protectedDevNames = []
self.unusedRaidMembers = []
# initialize attributes that may later hold cached lvm info
self.dropLVMCache()
self.__passphrases = []
if passphrase:
self.__passphrases.append(passphrase)
self.__luksDevs = {}
if luksDict and isinstance(luksDict, dict):
self.__luksDevs = luksDict
self.__passphrases.extend([p for p in luksDict.values() if p])
lvm.lvm_cc_resetFilter()
self._cleanup = False
def setDiskImages(self, images):
""" Set the disk images and reflect them in exclusiveDisks.
:param images: dict with image name keys and filename values
:type images: dict
.. note::
Disk images are automatically exclusive. That means that, in the
presence of disk images, any local storage not associated with
the disk images is ignored.
"""
self.diskImages = images
# disk image files are automatically exclusive
self.exclusiveDisks = list(self.diskImages.keys())
def addIgnoredDisk(self, disk):
self.ignoredDisks.append(disk)
lvm.lvm_cc_addFilterRejectRegexp(disk)
@property
def pvInfo(self):
if self._pvInfo is None:
self._pvInfo = lvm.pvinfo() # pylint: disable=attribute-defined-outside-init
return self._pvInfo
@property
def lvInfo(self):
if self._lvInfo is None:
self._lvInfo = lvm.lvs() # pylint: disable=attribute-defined-outside-init
return self._lvInfo
def dropLVMCache(self):
""" Drop cached lvm information. """
self._pvInfo = None # pylint: disable=attribute-defined-outside-init
self._lvInfo = None # pylint: disable=attribute-defined-outside-init
def pruneActions(self):
""" Remove redundant/obsolete actions from the action list. """
for action in reversed(self._actions[:]):
if action not in self._actions:
log.debug("action %d already pruned", action.id)
continue
for obsolete in self._actions[:]:
if action.obsoletes(obsolete):
log.info("removing obsolete action %d (%d)",
obsolete.id, action.id)
self._actions.remove(obsolete)
if obsolete.obsoletes(action) and action in self._actions:
log.info("removing mutually-obsolete action %d (%d)",
action.id, obsolete.id)
self._actions.remove(action)
def sortActions(self):
""" Sort actions based on dependencies. """
if not self._actions:
return
edges = []
# collect all ordering requirements for the actions
for action in self._actions:
action_idx = self._actions.index(action)
children = []
for _action in self._actions:
if _action == action:
continue
# create edges based on both action type and dependencies.
if _action.requires(action):
children.append(_action)
for child in children:
child_idx = self._actions.index(child)
edges.append((action_idx, child_idx))
# create a graph reflecting the ordering information we have
graph = tsort.create_graph(list(range(len(self._actions))), edges)
# perform a topological sort based on the graph's contents
order = tsort.tsort(graph)
# now replace self._actions with a sorted version of the same list
actions = []
for idx in order:
actions.append(self._actions[idx])
self._actions = actions
def _preProcessActions(self):
""" Prepare the action queue for execution. """
for action in self._actions:
log.debug("action: %s", action)
log.info("pruning action queue...")
self.pruneActions()
problematic = self.findActiveDevicesOnActionDisks()
if problematic:
if flags.installer_mode:
self.teardownAll()
else:
raise RuntimeError("partitions in use on disks with changes "
"pending: %s" %
",".join(problematic))
log.info("resetting parted disks...")
for device in self.devices:
if device.partitioned:
device.format.resetPartedDisk()
if device.originalFormat.type == "disklabel" and \
device.originalFormat != device.format:
device.originalFormat.resetPartedDisk()
# Call preCommitFixup on all devices
mpoints = [getattr(d.format, 'mountpoint', "") for d in self.devices]
for device in self.devices:
device.preCommitFixup(mountpoints=mpoints)
# Also call preCommitFixup on any devices we're going to
# destroy (these are already removed from the tree)
for action in self._actions:
if isinstance(action, ActionDestroyDevice):
action.device.preCommitFixup(mountpoints=mpoints)
# setup actions to create any extended partitions we added
#
# If the extended partition was explicitly requested it will already
# have an action registered.
#
# XXX At this point there can be duplicate partition paths in the
# tree (eg: non-existent sda6 and previous sda6 that will become
# sda5 in the course of partitioning), so we access the list
# directly here.
for device in self._devices:
if isinstance(device, PartitionDevice) and \
device.isExtended and not device.exists and \
not self.findActions(device=device, action_type="create"):
# don't properly register the action since the device is
# already in the tree
action = ActionCreateDevice(device)
# apply the action first in case the apply method fails
action.apply()
self._actions.append(action)
log.info("sorting actions...")
self.sortActions()
for action in self._actions:
log.debug("action: %s", action)
# Remove lvm filters for devices we are operating on
for device in (d for d in self._devices if d.dependsOn(action.device)):
lvm.lvm_cc_removeFilterRejectRegexp(device.name)
def _postProcessActions(self):
""" Clean up relics from action queue execution. """
# removal of partitions makes use of originalFormat, so it has to stay
# up to date in case of multiple passes through this method
for disk in (d for d in self.devices if d.partitioned):
disk.format.updateOrigPartedDisk()
disk.originalFormat = copy.deepcopy(disk.format)
# now we have to update the parted partitions of all devices so they
# match the parted disks we just updated
for partition in self.getDevicesByInstance(PartitionDevice):
pdisk = partition.disk.format.partedDisk
partition.partedPartition = pdisk.getPartitionByPath(partition.path)
def findActiveDevicesOnActionDisks(self):
""" Return a list of devices using the disks we plan to change. """
# Find out now if there are active devices using partitions on disks
# whose disklabels we are going to change. If there are, do not proceed.
disks = []
for action in self._actions:
disk = None
if action.isDevice and isinstance(action.device, PartitionDevice):
disk = action.device.disk
elif action.isFormat and action.format.type == "disklabel":
disk = action.device
if disk is not None and disk not in disks:
disks.append(disk)
active = (dev for dev in self.devices
if (dev.status and
(not dev.isDisk and
not isinstance(dev, PartitionDevice))))
devices = [a.name for a in active if any(d in disks for d in a.disks)]
return devices
def processActions(self, callbacks=None, dryRun=None):
"""
Execute all registered actions.
:param callbacks: callbacks to be invoked when actions are executed
:type callbacks: :class:`~.callbacks.DoItCallbacks`
"""
self._preProcessActions()
for action in self._actions[:]:
log.info("executing action: %s", action)
if not dryRun:
try:
action.execute(callbacks)
except DiskLabelCommitError:
# it's likely that a previous action
# triggered setup of an lvm or md device.
# include deps no longer in the tree due to pending removal
devs = self._devices + [a.device for a in self._actions]
for dep in set(devs):
if dep.exists and dep.dependsOn(action.device.disk):
dep.teardown(recursive=True)
action.execute(callbacks)
udev.settle()
for device in self._devices:
# make sure we catch any renumbering parted does
if device.exists and isinstance(device, PartitionDevice):
device.updateName()
device.format.device = device.path
self._completed_actions.append(self._actions.pop(0))
self._postProcessActions()
def _addDevice(self, newdev, new=True):
""" Add a device to the tree.
:param newdev: the device to add
:type newdev: a subclass of :class:`~.devices.StorageDevice`
Raise ValueError if the device's identifier is already
in the list.
"""
if newdev.uuid and newdev.uuid in [d.uuid for d in self._devices] and \
not isinstance(newdev, NoDevice):
raise ValueError("device is already in tree")
# make sure this device's parent devices are in the tree already
for parent in newdev.parents:
if parent not in self._devices:
raise DeviceTreeError("parent device not in tree")
newdev.addHook(new=new)
self._devices.append(newdev)
# don't include "req%d" partition names
if ((newdev.type != "partition" or
not newdev.name.startswith("req")) and
newdev.type != "btrfs volume" and
newdev.name not in self.names):
self.names.append(newdev.name)
log.info("added %s %s (id %d) to device tree", newdev.type,
newdev.name,
newdev.id)
def _removeDevice(self, dev, force=None, modparent=True):
""" Remove a device from the tree.
:param dev: the device to remove
:type dev: a subclass of :class:`~.devices.StorageDevice`
:keyword force: whether to force removal of a non-leaf device
:type force: bool
:keyword modparent: update parent device to account for removal
:type modparent: bool
.. note::
Only leaves may be removed.
"""
if dev not in self._devices:
raise ValueError("Device '%s' not in tree" % dev.name)
if not dev.isleaf and not force:
log.debug("%s has %d kids", dev.name, dev.kids)
raise ValueError("Cannot remove non-leaf device '%s'" % dev.name)
dev.removeHook(modparent=modparent)
if modparent:
# if this is a partition we need to remove it from the parted.Disk
if isinstance(dev, PartitionDevice) and dev.disk is not None:
# adjust all other PartitionDevice instances belonging to the
# same disk so the device name matches the potentially altered
# name of the parted.Partition
for device in self._devices:
if isinstance(device, PartitionDevice) and \
device.disk == dev.disk:
device.updateName()
self._devices.remove(dev)
if dev.name in self.names and getattr(dev, "complete", True):
self.names.remove(dev.name)
log.info("removed %s %s (id %d) from device tree", dev.type,
dev.name,
dev.id)
def _removeChildrenFromTree(self, device):
devs_to_remove = self.getDependentDevices(device)
while devs_to_remove:
leaves = [d for d in devs_to_remove if d.isleaf]
for leaf in leaves:
self._removeDevice(leaf, modparent=False)
devs_to_remove.remove(leaf)
if len(devs_to_remove) == 1 and devs_to_remove[0].isExtended:
self._removeDevice(devs_to_remove[0], force=True, modparent=False)
break
def registerAction(self, action):
""" Register an action to be performed at a later time.
:param action: the action
:type action: :class:`~.deviceaction.DeviceAction`
Modifications to the Device instance are handled before we
get here.
"""
if not (action.isCreate and action.isDevice) and \
action.device not in self._devices:
raise DeviceTreeError("device is not in the tree")
elif (action.isCreate and action.isDevice):
if action.device in self._devices:
raise DeviceTreeError("device is already in the tree")
if action.isCreate and action.isDevice:
self._addDevice(action.device)
elif action.isDestroy and action.isDevice:
self._removeDevice(action.device)
elif action.isCreate and action.isFormat:
if isinstance(action.device.format, formats.fs.FS) and \
action.device.format.mountpoint in self.filesystems:
raise DeviceTreeError("mountpoint already in use")
# apply the action before adding it in case apply raises an exception
action.apply()
log.info("registered action: %s", action)
self._actions.append(action)
def cancelAction(self, action):
""" Cancel a registered action.
:param action: the action
:type action: :class:`~.deviceaction.DeviceAction`
This will unregister the action and do any required
modifications to the device list.
Actions all operate on a Device, so we can use the devices
to determine dependencies.
"""
if action.isCreate and action.isDevice:
# remove the device from the tree
self._removeDevice(action.device)
elif action.isDestroy and action.isDevice:
# add the device back into the tree
self._addDevice(action.device, new=False)
action.cancel()
self._actions.remove(action)
log.info("canceled action %s", action)
def findActions(self, device=None, action_type=None, object_type=None,
path=None, devid=None):
""" Find all actions that match all specified parameters.
A value of None for any of the keyword arguments indicates that any
value is acceptable for that field.
:keyword device: device to match
:type device: :class:`~.devices.StorageDevice` or None
:keyword action_type: action type to match (eg: "create", "destroy")
:type action_type: str or None
:keyword object_type: operand type to match (eg: "device" or "format")
:type object_type: str or None
:keyword path: device path to match
:type path: str or None
:keyword devid: device id to match
:type devid: int or None
:returns: a list of matching actions
:rtype: list of :class:`~.deviceaction.DeviceAction`
"""
if device is None and action_type is None and object_type is None and \
path is None and devid is None:
return self._actions[:]
# convert the string arguments to the types used in actions
_type = action_type_from_string(action_type)
_object = action_object_from_string(object_type)
actions = []
for action in self._actions:
if device is not None and action.device != device:
continue
if _type is not None and action.type != _type:
continue
if _object is not None and action.obj != _object:
continue
if path is not None and action.device.path != path:
continue
if devid is not None and action.device.id != devid:
continue
actions.append(action)
return actions
def getDependentDevices(self, dep):
""" Return a list of devices that depend on dep.
The list includes both direct and indirect dependents.
:param dep: the device whose dependents we are looking for
:type dep: :class:`~.devices.StorageDevice`
"""
dependents = []
# don't bother looping looking for dependents if this is a leaf device
if dep.isleaf:
return dependents
incomplete = [d for d in self._devices
if not getattr(d, "complete", True)]
for device in self.devices + incomplete:
if device.dependsOn(dep):
dependents.append(device)
return dependents
def isIgnored(self, info):
""" Return True if info is a device we should ignore.
:param info: udevdb device entry
:type info: dict
:returns: whether the device will be ignored
:rtype: bool
"""
sysfs_path = udev.device_get_sysfs_path(info)
name = udev.device_get_name(info)
if not sysfs_path:
return None
# Special handling for mdraid external metadata sets (mdraid BIOSRAID):
# 1) The containers are intermediate devices which will never be
# in exclusiveDisks
# 2) Sets get added to exclusive disks with their dmraid set name by
# the filter ui. Note that making the ui use md names instead is not
# possible as the md names are simpy md# and we cannot predict the #
if udev.device_is_md(info) and \
udev.device_get_md_level(info) == "container":
return False
if udev.device_get_md_container(info) and \
udev.device_is_md(info) and \
udev.device_get_md_name(info):
md_name = udev.device_get_md_name(info)
# mdadm may have appended _<digit>+ if the current hostname
# does not match the one in the array metadata
alt_name = re.sub(r"_\d+$", "", md_name)
raw_pattern = "isw_[a-z]*_%s"
# XXX FIXME: This is completely insane.
for i in range(0, len(self.exclusiveDisks)):
if re.match(raw_pattern % md_name, self.exclusiveDisks[i]) or \
re.match(raw_pattern % alt_name, self.exclusiveDisks[i]):
self.exclusiveDisks[i] = name
return False
# never ignore mapped disk images. if you don't want to use them,
# don't specify them in the first place
if udev.device_is_dm_anaconda(info) or udev.device_is_dm_livecd(info):
return False
# Ignore loop and ram devices, we normally already skip these in
# udev.py: enumerate_block_devices(), but we can still end up trying
# to add them to the tree when they are slaves of other devices, this
# happens for example with the livecd
if name.startswith("ram"):
return True
if name.startswith("loop"):
# ignore loop devices unless they're backed by a file
return (not loop.get_backing_file(name))
# FIXME: check for virtual devices whose slaves are on the ignore list
def udevDeviceIsDisk(self, info):
""" Return True if the udev device looks like a disk.
:param info: udevdb device entry
:type info: dict
:returns: whether the device is a disk
:rtype: bool
We want exclusiveDisks to operate on anything that could be
considered a directly usable disk, ie: fwraid array, mpath, or disk.
Unfortunately, since so many things are represented as disks by
udev/sysfs, we have to define what is a disk in terms of what is
not a disk.
"""
return (udev.device_is_disk(info) and
not (udev.device_is_cdrom(info) or
udev.device_is_partition(info) or
udev.device_is_dm_partition(info) or
udev.device_is_dm_lvm(info) or
udev.device_is_dm_crypt(info) or
(udev.device_is_md(info) and
not udev.device_get_md_container(info))))
def addUdevLVDevice(self, info):
name = udev.device_get_name(info)
log_method_call(self, name=name)
sysfs_path = udev.device_get_sysfs_path(info)
vg_name = udev.device_get_lv_vg_name(info)
device = self.getDeviceByName(vg_name, hidden=True)
if device and not isinstance(device, LVMVolumeGroupDevice):
log.warning("found non-vg device with name %s", vg_name)
device = None
if not device:
# initiate detection of all PVs and hope that it leads to us having
# the VG and LVs in the tree
for pv_name in os.listdir(sysfs_path + "/slaves"):
link = os.readlink(sysfs_path + "/slaves/" + pv_name)
pv_sysfs_path = os.path.normpath(sysfs_path + '/slaves/' + link)
pv_info = udev.get_device(pv_sysfs_path)
self.addUdevDevice(pv_info)
vg_name = udev.device_get_lv_vg_name(info)
device = self.getDeviceByName(vg_name)
if not device:
log.error("failed to find vg '%s' after scanning pvs", vg_name)
# Don't return the device like we do in the other addUdevFooDevice
# methods. The device we have here is a vg, not an lv.
def addUdevDMDevice(self, info):
name = udev.device_get_name(info)
log_method_call(self, name=name)
sysfs_path = udev.device_get_sysfs_path(info)
device = None
for dmdev in self.devices:
if not isinstance(dmdev, DMDevice):
continue
try:
# there is a device in the tree already with the same
# major/minor as this one but with a different name
# XXX this is kind of racy
if dmdev.getDMNode() == os.path.basename(sysfs_path):
# XXX should we take the name already in use?
device = dmdev
break
except DMError:
# This is a little lame, but the VG device is a DMDevice
# and it won't have a dm node. At any rate, this is not
# important enough to crash the install.
log.debug("failed to find dm node for %s", dmdev.name)
continue
handle_luks = (udev.device_is_dm_luks(info) and
(self._cleanup or not flags.installer_mode))
slave_dev = None
slave_info = None
if device is None:
# we couldn't find it, so create it
# first, get a list of the slave devs and look them up
slave_dir = os.path.normpath("%s/slaves" % sysfs_path)
slave_names = os.listdir(slave_dir)
for slave_name in slave_names:
# if it's a dm-X name, resolve it to a map name first
if slave_name.startswith("dm-"):
dev_name = dm.name_from_dm_node(slave_name)
else:
dev_name = slave_name.replace("!", "/") # handles cciss
slave_dev = self.getDeviceByName(dev_name)
path = os.path.normpath("%s/%s" % (slave_dir, slave_name))
new_info = udev.get_device(os.path.realpath(path))
if not slave_dev:
# we haven't scanned the slave yet, so do it now
if new_info:
self.addUdevDevice(new_info)
slave_dev = self.getDeviceByName(dev_name)
if slave_dev is None:
# if the current slave is still not in
# the tree, something has gone wrong
log.error("failure scanning device %s: could not add slave %s", name, dev_name)
return
if handle_luks:
slave_info = new_info
# try to get the device again now that we've got all the slaves
device = self.getDeviceByName(name)
if device is None and udev.device_is_dm_partition(info):
diskname = udev.device_get_dm_partition_disk(info)
disk = self.getDeviceByName(diskname)
return self.addUdevPartitionDevice(info, disk=disk)
# if this is a luks device whose map name is not what we expect,
# fix up the map name and see if that sorts us out
if device is None and handle_luks and slave_info and slave_dev:
slave_dev.format.mapName = name
self.handleUdevLUKSFormat(slave_info, slave_dev)
# try once more to get the device
device = self.getDeviceByName(name)
# create a device for the livecd OS image(s)
if device is None and udev.device_is_dm_livecd(info):
device = DMDevice(name, dmUuid=info.get('DM_UUID'),
sysfsPath=sysfs_path, exists=True,
parents=[slave_dev])
device.protected = True
device.controllable = False
self._addDevice(device)
# if we get here, we found all of the slave devices and
# something must be wrong -- if all of the slaves are in
# the tree, this device should be as well
if device is None:
lvm.lvm_cc_addFilterRejectRegexp(name)
log.warning("ignoring dm device %s", name)
return device
def addUdevMultiPathDevice(self, info):
name = udev.device_get_name(info)
log_method_call(self, name=name)
sysfs_path = udev.device_get_sysfs_path(info)
slave_devs = []
# TODO: look for this device by dm-uuid?
# first, get a list of the slave devs and look them up
slave_dir = os.path.normpath("%s/slaves" % sysfs_path)
slave_names = os.listdir(slave_dir)
for slave_name in slave_names:
# if it's a dm-X name, resolve it to a map name first
if slave_name.startswith("dm-"):
dev_name = dm.name_from_dm_node(slave_name)
else:
dev_name = slave_name.replace("!", "/") # handles cciss
slave_dev = self.getDeviceByName(dev_name)
path = os.path.normpath("%s/%s" % (slave_dir, slave_name))
new_info = udev.get_device(os.path.realpath(path))
if not slave_dev:
# we haven't scanned the slave yet, so do it now
if new_info:
self.addUdevDevice(new_info)
slave_dev = self.getDeviceByName(dev_name)
if slave_dev is None:
# if the current slave is still not in
# the tree, something has gone wrong
log.error("failure scanning device %s: could not add slave %s", name, dev_name)
return
slave_devs.append(slave_dev)
device = None
if slave_devs:
try:
serial = info["DM_UUID"].split("-", 1)[1]
except (IndexError, AttributeError):
log.error("multipath device %s has no DM_UUID", name)
raise DeviceTreeError("multipath %s has no DM_UUID" % name)
device = MultipathDevice(name, parents=slave_devs,
serial=serial)
self._addDevice(device)
return device
def addUdevMDDevice(self, info):
name = udev.device_get_md_name(info)
log_method_call(self, name=name)
sysfs_path = udev.device_get_sysfs_path(info)
slave_dir = os.path.normpath("%s/slaves" % sysfs_path)
slave_names = os.listdir(slave_dir)
for slave_name in slave_names:
# if it's a dm-X name, resolve it to a map name
if slave_name.startswith("dm-"):
dev_name = dm.name_from_dm_node(slave_name)
else:
dev_name = slave_name
slave_dev = self.getDeviceByName(dev_name)
if not slave_dev:
# we haven't scanned the slave yet, so do it now
path = os.path.normpath("%s/%s" % (slave_dir, slave_name))
new_info = udev.get_device(os.path.realpath(path))
if new_info:
self.addUdevDevice(new_info)
if self.getDeviceByName(dev_name) is None:
# if the current slave is still not in
# the tree, something has gone wrong
log.error("failure scanning device %s: could not add slave %s", name, dev_name)
return
# try to get the device again now that we've got all the slaves
device = self.getDeviceByName(name, incomplete=flags.allow_imperfect_devices)
if device is None:
try:
uuid = udev.device_get_md_uuid(info)
except KeyError:
log.warning("failed to obtain uuid for mdraid device")
else:
device = self.getDeviceByUuid(uuid, incomplete=flags.allow_imperfect_devices)
if device:
# update the device instance with the real name in case we had to
# look it up by something other than name
# XXX bypass the setter since a) the device exists and b) the name
# must be valid since it is currently in use
device._name = name
else:
# if we get here, we found all of the slave devices and
# something must be wrong -- if all of the slaves are in
# the tree, this device should be as well
if name is None:
name = udev.device_get_name(info)
path = "/dev/" + name
else:
path = "/dev/md/" + name
log.error("failed to scan md array %s", name)
try:
mdraid.mddeactivate(path)
except MDRaidError:
log.error("failed to stop broken md array %s", name)
return device
def addUdevPartitionDevice(self, info, disk=None):
name = udev.device_get_name(info)
log_method_call(self, name=name)
sysfs_path = udev.device_get_sysfs_path(info)
if name.startswith("md"):
name = mdraid.name_from_md_node(name)
device = self.getDeviceByName(name)
if device:
return device
if disk is None:
disk_name = os.path.basename(os.path.dirname(sysfs_path))
disk_name = disk_name.replace('!','/')
if disk_name.startswith("md"):
disk_name = mdraid.name_from_md_node(disk_name)
disk = self.getDeviceByName(disk_name)
if disk is None:
# create a device instance for the disk
new_info = udev.get_device(os.path.dirname(sysfs_path))
if new_info:
self.addUdevDevice(new_info)
disk = self.getDeviceByName(disk_name)
if disk is None:
# if the current device is still not in
# the tree, something has gone wrong
log.error("failure scanning device %s", disk_name)
lvm.lvm_cc_addFilterRejectRegexp(name)
return
if not disk.partitioned:
# Ignore partitions on:
# - devices we do not support partitioning of, like logical volumes
# - devices that do not have a usable disklabel
# - devices that contain disklabels made by isohybrid
#
if disk.partitionable and \
disk.format.type != "iso9660" and \
not disk.format.hidden and \
not self._isIgnoredDisk(disk):
if info.get("ID_PART_TABLE_TYPE") == "gpt":
msg = "corrupt gpt disklabel on disk %s" % disk.name
else:
msg = "failed to scan disk %s" % disk.name
raise UnusableConfigurationError(msg)
# there's no need to filter partitions on members of multipaths or
# fwraid members from lvm since multipath and dmraid are already
# active and lvm should therefore know to ignore them
if not disk.format.hidden:
lvm.lvm_cc_addFilterRejectRegexp(name)
log.debug("ignoring partition %s on %s", name, disk.format.type)
return
device = None
try:
device = PartitionDevice(name, sysfsPath=sysfs_path,
major=udev.device_get_major(info),
minor=udev.device_get_minor(info),
exists=True, parents=[disk])
except DeviceError as e:
# corner case sometime the kernel accepts a partition table
# which gets rejected by parted, in this case we will
# prompt to re-initialize the disk, so simply skip the
# faulty partitions.
# XXX not sure about this
log.error("Failed to instantiate PartitionDevice: %s", e)
return
self._addDevice(device)
return device
def addUdevDiskDevice(self, info):
name = udev.device_get_name(info)
log_method_call(self, name=name)
sysfs_path = udev.device_get_sysfs_path(info)
serial = udev.device_get_serial(info)
bus = udev.device_get_bus(info)
# udev doesn't always provide a vendor.
vendor = udev.device_get_vendor(info)
if not vendor:
vendor = ""
kwargs = { "serial": serial, "vendor": vendor, "bus": bus }
if udev.device_is_iscsi(info):
diskType = iScsiDiskDevice
initiator = udev.device_get_iscsi_initiator(info)
target = udev.device_get_iscsi_name(info)
address = udev.device_get_iscsi_address(info)
port = udev.device_get_iscsi_port(info)