/
mount.py
858 lines (772 loc) · 32.1 KB
/
mount.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
"""
Mount utilities.
"""
from distutils.spawn import find_executable
from collections import namedtuple
from functools import partial
import logging
import os
from .async_ import to_coro, gather, sleep
from .common import wraps, setdefault, exc_message, format_exc
from .config import IgnoreDevice, match_config
from .locale import _
__all__ = ['Mounter']
# TODO: add / remove / XXX_all should make proper use of the asynchronous
# execution.
def _error_boundary(fn):
@wraps(fn)
async def wrapper(self, device, *args, **kwargs):
try:
return await fn(self, device, *args, **kwargs)
except Exception as e:
self._log.error(_('failed to {0} {1}: {2}',
fn.__name__, device, exc_message(e)))
self._log.debug(format_exc())
return False
return wrapper
def _is_parent_of(parent, child):
"""Check whether the first device is the parent of the second device."""
if child.is_partition:
return child.partition_slave == parent
if child.is_toplevel:
return child.drive == parent and child != parent
return False
class Mounter:
"""
Mount utility.
Stores environment variables (filter, prompt, browser, udisks) to use
across multiple mount operations.
:ivar udisks: adapter to the udisks service
NOTE: The optional parameters are not guaranteed to keep their order and
should always be passed as keyword arguments.
"""
def __init__(self, udisks, config=None, prompt=None, browser=None,
terminal=None, cache=None, cache_hint=False):
"""
Initialize mounter with the given defaults.
:param udisks: udisks service object. May be a Sniffer or a Daemon.
:param list config: list of :class:`DeviceFilter`
:param callable prompt: retrieve passwords for devices
:param callable browser: open devices
:param callable terminal: open devices in terminal
If prompt is None, device unlocking will not work.
If browser is None, browse will not work.
"""
self.udisks = udisks
self._config = (config or []) + [
IgnoreDevice({'symlinks': '/dev/mapper/docker-*', 'ignore': True}),
IgnoreDevice({'symlinks': '/dev/disk/by-id/dm-name-docker-*',
'ignore': True}),
IgnoreDevice({'is_loop': True, 'is_ignored': False,
'loop_file': '/*', 'ignore': False}),
IgnoreDevice({'is_block': False, 'ignore': True}),
IgnoreDevice({'is_external': False,
'is_toplevel': True, 'ignore': True}),
IgnoreDevice({'is_ignored': True, 'ignore': True})]
self._prompt = prompt
self._browser = browser
self._terminal = terminal
self._cache = cache
self._cache_hint = cache_hint
self._log = logging.getLogger(__name__)
def _find_device(self, device_or_path):
"""Find device object from path."""
return self.udisks.find(device_or_path)
async def _find_device_losetup(self, device_or_path):
try:
device = self.udisks.find(device_or_path)
return device, False
except FileNotFoundError:
if not os.path.isfile(device_or_path):
raise
device = await self.losetup(device_or_path)
return device, True
@_error_boundary
async def browse(self, device):
"""
Launch file manager on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched.
"""
device = self._find_device(device)
if not device.is_mounted:
self._log.error(_("not browsing {0}: not mounted", device))
return False
if not self._browser:
self._log.error(_("not browsing {0}: no program", device))
return False
self._log.debug(_('opening {0} on {0.mount_paths[0]}', device))
self._browser(device.mount_paths[0])
self._log.info(_('opened {0} on {0.mount_paths[0]}', device))
return True
@_error_boundary
async def terminal(self, device):
"""
Launch terminal on the mount path of the specified device.
:param device: device object, block device path or mount path
:returns: whether the program was successfully launched.
"""
device = self._find_device(device)
if not device.is_mounted:
self._log.error(_("not opening terminal {0}: not mounted", device))
return False
if not self._terminal:
self._log.error(_("not opening terminal {0}: no program", device))
return False
self._log.debug(_('opening {0} on {0.mount_paths[0]}', device))
self._terminal(device.mount_paths[0])
self._log.info(_('opened {0} on {0.mount_paths[0]}', device))
return True
# mount/unmount
@_error_boundary
async def mount(self, device):
"""
Mount the device if not already mounted.
:param device: device object, block device path or mount path
:returns: whether the device is mounted.
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_filesystem:
self._log.warn(_('not mounting {0}: unhandled device', device))
return False
if device.is_mounted:
self._log.info(_('not mounting {0}: already mounted', device))
return True
options = match_config(self._config, device, 'options', None)
kwargs = dict(options=options)
self._log.debug(_('mounting {0} with {1}', device, kwargs))
self._check_device_before_mount(device)
mount_path = await device.mount(**kwargs)
self._log.info(_('mounted {0} on {1}', device, mount_path))
return True
def _check_device_before_mount(self, device):
if device.id_type == 'ntfs' and not find_executable('ntfs-3g'):
self._log.warn(_(
"Mounting NTFS device with default driver.\n"
"Please install 'ntfs-3g' if you experience problems or the "
"device is readonly."))
@_error_boundary
async def unmount(self, device):
"""
Unmount a Device if mounted.
:param device: device object, block device path or mount path
:returns: whether the device is unmounted
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_filesystem:
self._log.warn(_('not unmounting {0}: unhandled device', device))
return False
if not device.is_mounted:
self._log.info(_('not unmounting {0}: not mounted', device))
return True
self._log.debug(_('unmounting {0}', device))
await device.unmount()
self._log.info(_('unmounted {0}', device))
return True
# unlock/lock (LUKS)
@_error_boundary
async def unlock(self, device):
"""
Unlock the device if not already unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is unlocked
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_crypto:
self._log.warn(_('not unlocking {0}: unhandled device', device))
return False
if device.is_unlocked:
self._log.info(_('not unlocking {0}: already unlocked', device))
return True
if not self._prompt:
self._log.error(_('not unlocking {0}: no password prompt', device))
return False
unlocked = await self._unlock_from_cache(device)
if unlocked:
return True
unlocked = await self._unlock_from_keyfile(device)
if unlocked:
return True
options = dict(allow_keyfile=self.udisks.keyfile_support,
allow_cache=self._cache is not None,
cache_hint=self._cache_hint)
password = await self._prompt(device, options)
# password is either None or udiskie.prompt.PasswordResult:
if password is None:
self._log.debug(_('not unlocking {0}: cancelled by user', device))
return False
cache_hint = password.cache_hint
password = password.password
if isinstance(password, bytes):
self._log.debug(_('unlocking {0} using keyfile', device))
await device.unlock_keyfile(password)
else:
self._log.debug(_('unlocking {0}', device))
await device.unlock(password)
self._update_cache(device, password, cache_hint)
self._log.info(_('unlocked {0}', device))
return True
async def _unlock_from_cache(self, device):
if not self._cache:
return False
try:
password = self._cache[device]
except KeyError:
self._log.debug(_("no cached key for {0}", device))
return False
self._log.debug(_('unlocking {0} using cached password', device))
try:
await device.unlock_keyfile(password)
except Exception:
self._log.debug(_('failed to unlock {0} using cached password', device))
self._log.debug(format_exc())
return False
self._log.info(_('unlocked {0} using cached password', device))
return True
async def _unlock_from_keyfile(self, device):
if not self.udisks.keyfile_support:
return False
filename = match_config(self._config, device, 'keyfile', None)
if filename is None:
self._log.debug(_('No matching keyfile rule for {}.', device))
return False
try:
with open(filename, 'rb') as f:
keyfile = f.read()
except IOError:
self._log.warn(_('keyfile for {0} not found: {1}', device, filename))
return False
self._log.debug(_('unlocking {0} using keyfile {1}', device, filename))
try:
await device.unlock_keyfile(keyfile)
except Exception:
self._log.debug(_('failed to unlock {0} using keyfile', device))
self._log.debug(format_exc())
return False
self._log.info(_('unlocked {0} using keyfile', device))
return True
def _update_cache(self, device, password, cache_hint):
if not self._cache:
return
# TODO: could allow numeric cache_hint (=timeout)…
if cache_hint or cache_hint is None:
self._cache[device] = password
def forget_password(self, device):
try:
del self._cache[device]
except KeyError:
pass
@_error_boundary
async def lock(self, device):
"""
Lock device if unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is locked
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_crypto:
self._log.warn(_('not locking {0}: unhandled device', device))
return False
if not device.is_unlocked:
self._log.info(_('not locking {0}: not unlocked', device))
return True
self._log.debug(_('locking {0}', device))
await device.lock()
self._log.info(_('locked {0}', device))
return True
# add/remove (unlock/lock or mount/unmount)
@_error_boundary
async def add(self, device, recursive=None):
"""
Mount or unlock the device depending on its type.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded
"""
device, created = await self._find_device_losetup(device)
if created and recursive is False:
return device
if device.is_filesystem:
success = await self.mount(device)
elif device.is_crypto:
success = await self.unlock(device)
if success and recursive:
await self.udisks._sync()
device = self.udisks[device.object_path]
success = await self.add(
device.luks_cleartext_holder,
recursive=True)
elif (recursive
and device.is_partition_table
and self.is_handleable(device)):
tasks = [
self.add(dev, recursive=True)
for dev in self.get_all_handleable()
if dev.is_partition and dev.partition_slave == device
]
results = await gather(*tasks)
success = all(results)
else:
self._log.info(_('not adding {0}: unhandled device', device))
return False
return success
@_error_boundary
async def auto_add(self, device, recursive=None, automount=True):
"""
Automatically attempt to mount or unlock a device, but be quiet if the
device is not supported.
:param device: device object, block device path or mount path
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded
"""
device, created = await self._find_device_losetup(device)
if created and recursive is False:
return device
if device.is_luks_cleartext and self.udisks.version_info >= (2, 7, 0):
await sleep(1.5) # temporary workaround for #153, unreliable
success = True
if not self.is_automount(device, automount):
pass
elif device.is_filesystem:
if not device.is_mounted:
success = await self.mount(device)
elif device.is_crypto:
if self._prompt and not device.is_unlocked:
success = await self.unlock(device)
if success and recursive:
await self.udisks._sync()
device = self.udisks[device.object_path]
success = await self.auto_add(
device.luks_cleartext_holder,
recursive=True)
elif recursive and device.is_partition_table:
tasks = [
self.auto_add(dev, recursive=True)
for dev in self.get_all_handleable()
if dev.is_partition and dev.partition_slave == device
]
results = await gather(*tasks)
success = all(results)
else:
self._log.debug(_('not adding {0}: unhandled device', device))
return success
@_error_boundary
async def remove(self, device, force=False, detach=False, eject=False,
lock=False):
"""
Unmount or lock the device depending on device type.
:param device: device object, block device path or mount path
:param bool force: recursively remove all child devices
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lock: lock the associated LUKS cleartext slave
:returns: whether all attempted operations succeeded
"""
device = self._find_device(device)
if device.is_filesystem:
if device.is_mounted or not device.is_loop or detach is False:
success = await self.unmount(device)
elif device.is_crypto:
if force and device.is_unlocked:
await self.auto_remove(device.luks_cleartext_holder, force=True)
success = await self.lock(device)
elif (force
and (device.is_partition_table or device.is_drive)
and self.is_handleable(device)):
kw = dict(force=True, detach=detach, eject=eject, lock=lock)
tasks = [
self.auto_remove(child, **kw)
for child in self.get_all_handleable()
if _is_parent_of(device, child)
]
results = await gather(*tasks)
success = all(results)
else:
self._log.info(_('not removing {0}: unhandled device', device))
success = False
# if these operations work, everything is fine, we can return True:
if lock and device.is_luks_cleartext:
device = device.luks_cleartext_slave
if self.is_handleable(device):
success = await self.lock(device)
if eject:
success = await self.eject(device)
if (detach or detach is None) and device.is_loop:
success = await self.delete(device, remove=False)
elif detach:
success = await self.detach(device)
return success
@_error_boundary
async def auto_remove(self, device, force=False, detach=False, eject=False,
lock=False):
"""
Unmount or lock the device depending on device type.
:param device: device object, block device path or mount path
:param bool force: recursively remove all child devices
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lock: lock the associated LUKS cleartext slave
:returns: whether all attempted operations succeeded
"""
device = self._find_device(device)
success = True
if not self.is_handleable(device):
pass
elif device.is_filesystem:
if device.is_mounted:
success = await self.unmount(device)
elif device.is_crypto:
if force and device.is_unlocked:
await self.auto_remove(device.luks_cleartext_holder, force=True)
if device.is_unlocked:
success = await self.lock(device)
elif force and (device.is_partition_table or device.is_drive):
kw = dict(force=True, detach=detach, eject=eject, lock=lock)
tasks = [
self.auto_remove(child, **kw)
for child in self.get_all_handleable()
if _is_parent_of(device, child)
]
results = await gather(*tasks)
success = all(results)
else:
self._log.debug(_('not removing {0}: unhandled device', device))
# if these operations work, everything is fine, we can return True:
if lock and device.is_luks_cleartext:
device = device.luks_cleartext_slave
success = await self.lock(device)
if eject and device.has_media:
success = await self.eject(device)
if (detach or detach is None) and device.is_loop:
success = await self.delete(device, remove=False)
elif detach and device.is_detachable:
success = await self.detach(device)
return success
# eject/detach device
@_error_boundary
async def eject(self, device, force=False):
"""
Eject a device after unmounting all its mounted filesystems.
:param device: device object, block device path or mount path
:param bool force: remove child devices before trying to eject
:returns: whether the operation succeeded
"""
device = self._find_device(device)
if not self.is_handleable(device):
self._log.warn(_('not ejecting {0}: unhandled device'))
return False
drive = device.drive
if not (drive.is_drive and drive.is_ejectable):
self._log.warn(_('not ejecting {0}: drive not ejectable', drive))
return False
if force:
# Can't autoremove 'device.drive', because that will be filtered
# due to block=False:
await self.auto_remove(device.root, force=True)
self._log.debug(_('ejecting {0}', device))
await drive.eject()
self._log.info(_('ejected {0}', device))
return True
@_error_boundary
async def detach(self, device, force=False):
"""
Detach a device after unmounting all its mounted filesystems.
:param device: device object, block device path or mount path
:param bool force: remove child devices before trying to detach
:returns: whether the operation succeeded
"""
device = self._find_device(device)
if not self.is_handleable(device):
self._log.warn(_('not detaching {0}: unhandled device', device))
return False
drive = device.root
if not drive.is_detachable and not drive.is_loop:
self._log.warn(_('not detaching {0}: drive not detachable', drive))
return False
if force:
await self.auto_remove(drive, force=True)
self._log.debug(_('detaching {0}', device))
if drive.is_detachable:
await drive.detach()
else:
await drive.delete()
self._log.info(_('detached {0}', device))
return True
# mount_all/unmount_all
async def add_all(self, recursive=False):
"""
Add all handleable devices that available at start.
:param bool recursive: recursively mount and unlock child devices
:returns: whether all attempted operations succeeded
"""
tasks = [self.auto_add(device, recursive=recursive)
for device in self.get_all_handleable_leaves()]
results = await gather(*tasks)
success = all(results)
return success
async def remove_all(self, detach=False, eject=False, lock=False):
"""
Remove all filesystems handleable by udiskie.
:param bool detach: detach the root drive
:param bool eject: remove media from the root drive
:param bool lock: lock the associated LUKS cleartext slave
:returns: whether all attempted operations succeeded
"""
kw = dict(force=True, detach=detach, eject=eject, lock=lock)
tasks = [self.auto_remove(device, **kw)
for device in self.get_all_handleable_roots()]
results = await gather(*tasks)
success = all(results)
return success
# loop devices
async def losetup(self, image, read_only=True, offset=None, size=None,
no_part_scan=None):
"""
Setup a loop device.
:param str image: path of the image file
:param bool read_only:
:param int offset:
:param int size:
:param bool no_part_scan:
:returns: the device object for the loop device
"""
try:
device = self.udisks.find(image)
except FileNotFoundError:
pass
else:
self._log.info(_('not setting up {0}: already up', device))
return device
if not os.path.isfile(image):
self._log.error(_('not setting up {0}: not a file', image))
return None
self._log.debug(_('setting up {0}', image))
fd = os.open(image, os.O_RDONLY)
device = await self.udisks.loop_setup(fd, {
'offset': offset,
'size': size,
'read-only': read_only,
'no-part-scan': no_part_scan,
})
self._log.info(_('set up {0} as {1}', image,
device.device_presentation))
return device
@_error_boundary
async def delete(self, device, remove=True):
"""
Detach the loop device.
:param device: device object, block device path or mount path
:param bool remove: whether to unmount the partition etc.
:returns: whether the loop device is deleted
"""
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_loop:
self._log.warn(_('not deleting {0}: unhandled device', device))
return False
if remove:
await self.auto_remove(device, force=True)
self._log.debug(_('deleting {0}', device))
await device.delete()
self._log.info(_('deleted {0}', device))
return True
# iterate devices
def is_handleable(self, device):
# TODO: handle paths in first argument
"""
Check whether this device should be handled by udiskie.
:param device: device object, block device path or mount path
:returns: handleability
Currently this just means that the device is removable and holds a
filesystem or the device is a LUKS encrypted volume.
"""
return not self._ignore_device(device)
def is_automount(self, device, default=True):
if not self.is_handleable(device):
return False
return match_config(self._config, device, 'automount', default)
def _ignore_device(self, device):
return match_config(self._config, device, 'ignore', False)
def is_addable(self, device, automount=True):
"""Check if device can be added with ``auto_add``."""
if not self.is_automount(device, automount):
return False
if device.is_filesystem:
return not device.is_mounted
if device.is_crypto:
return self._prompt and not device.is_unlocked
if device.is_partition_table:
return any(self.is_addable(dev)
for dev in self.get_all_handleable()
if dev.partition_slave == device)
return False
def is_removable(self, device):
"""Check if device can be removed with ``auto_remove``."""
if not self.is_handleable(device):
return False
if device.is_filesystem:
return device.is_mounted
if device.is_crypto:
return device.is_unlocked
if device.is_partition_table or device.is_drive:
return any(self.is_removable(dev)
for dev in self.get_all_handleable()
if _is_parent_of(device, dev))
return False
def get_all_handleable(self):
"""Get list of all known handleable devices."""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._sort_key)
if not node.ignored and node.device]
def get_all_handleable_roots(self):
"""
Get list of all handleable devices, return only those that represent
root nodes within the filtered device tree.
"""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._sort_key)
if not node.ignored and node.device
and (node.root == '/' or nodes[node.root].ignored)]
def get_all_handleable_leaves(self):
"""
Get list of all handleable devices, return only those that represent
leaf nodes within the filtered device tree.
"""
nodes = self.get_device_tree()
return [node.device
for node in sorted(nodes.values(), key=DevNode._sort_key)
if not node.ignored and node.device
and all(child.ignored for child in node.children)]
def get_device_tree(self):
"""Get a tree of all devices."""
root = DevNode(None, None, [], None)
device_nodes = {
dev.object_path: DevNode(dev, dev.parent_object_path, [],
self._ignore_device(dev))
for dev in self.udisks
}
for node in device_nodes.values():
device_nodes.get(node.root, root).children.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.children.sort(key=DevNode._sort_key)
# use parent as fallback, update top->down:
def propagate_ignored(node):
for child in node.children:
if child.ignored is None:
child.ignored = node.ignored
propagate_ignored(child)
propagate_ignored(root)
return device_nodes
class DevNode:
def __init__(self, device, root, children, ignored):
self.device = device
self.root = root
self.children = children
self.ignored = ignored
def _sort_key(self):
return self.device.device_presentation if self.device else ''
# data structs containing the menu hierarchy:
Device = namedtuple('Device', ['root', 'branches', 'device', 'label', 'methods'])
Action = namedtuple('Action', ['method', 'device', 'label', 'action'])
class DeviceActions:
_labels = {
'browse': _('Browse {0}'),
'terminal': _('Hack on {0}'),
'mount': _('Mount {0}'),
'unmount': _('Unmount {0}'),
'unlock': _('Unlock {0}'),
'lock': _('Lock {0}'),
'eject': _('Eject {1}'),
'detach': _('Unpower {1}'),
'forget_password': _('Clear password for {0}'),
'delete': _('Detach {0}'),
}
def __init__(self, mounter, actions={}):
self._mounter = mounter
self._actions = _actions = actions.copy()
setdefault(_actions, {
'browse': mounter.browse,
'terminal': mounter.terminal,
'mount': mounter.mount,
'unmount': mounter.unmount,
'unlock': mounter.unlock,
'lock': partial(mounter.remove, force=True),
'eject': partial(mounter.eject, force=True),
'detach': partial(mounter.detach, force=True),
'forget_password': to_coro(mounter.forget_password),
'delete': mounter.delete,
})
def detect(self, root_device='/'):
"""
Detect all currently known devices.
:param str root_device: object path of root device to return
:returns: root node of device hierarchy
"""
root = Device(None, [], None, "", [])
device_nodes = dict(map(self._device_node,
self._mounter.get_all_handleable()))
# insert child devices as branches into their roots:
for node in device_nodes.values():
device_nodes.get(node.root, root).branches.append(node)
device_nodes['/'] = root
for node in device_nodes.values():
node.branches.sort(key=lambda node: node.label)
return device_nodes[root_device]
def _get_device_methods(self, device):
"""Return an iterable over all available methods the device has."""
if device.is_filesystem:
if device.is_mounted:
if self._mounter._browser:
yield 'browse'
if self._mounter._terminal:
yield 'terminal'
yield 'unmount'
else:
yield 'mount'
elif device.is_crypto:
if device.is_unlocked:
yield 'lock'
else:
yield 'unlock'
cache = self._mounter._cache
if cache and device in cache:
yield 'forget_password'
if device.is_ejectable and device.has_media:
yield 'eject'
if device.is_detachable:
yield 'detach'
if device.is_loop:
yield 'delete'
def _device_node(self, device):
"""Create an empty menu node for the specified device."""
label = device.ui_label
dev_label = device.ui_device_label
# determine available methods
methods = [Action(method, device,
self._labels[method].format(label, dev_label),
partial(self._actions[method], device))
for method in self._get_device_methods(device)]
# find the root device:
root = device.parent_object_path
# in this first step leave branches empty
return device.object_path, Device(root, [], device, dev_label, methods)
def prune_empty_node(node, seen):
"""
Recursively remove empty branches and return whether this makes the node
itself empty.
The ``seen`` parameter is used to avoid infinite recursion due to cycles
(you never know).
"""
if node.methods:
return False
if id(node) in seen:
return True
seen = seen | {id(node)}
for branch in list(node.branches):
if prune_empty_node(branch, seen):
node.branches.remove(branch)
else:
return False
return True