(auto-)mount (usb-)drives through udisk2 dbus api from python

962 views Asked by At

I've got a python daemon that controls an audio player. Now I want this daemon to monitor USB disks inserted and add their content to the mpd media library.

One part of this is a udisk client that waits for disks inserted and then immediately mounts them.

I want to mount the disks read-only, so there won't be any data corruption if I unplug the the disk without unmounting or shutting down first.

1

There are 1 answers

0
JPT On

My final code is this.

def start_listening():
    import dbus
    from dbus.mainloop.glib import DBusGMainLoop
    DBusGMainLoop(set_as_default=True)

    bus = dbus.SystemBus()

    def cb_insert_disk(*args):
        device = args[0]
        info = args[1]
        if "org.freedesktop.UDisks2.Block" in info:
            if 'org.freedesktop.UDisks2.Partition' in info:
                drive = info['org.freedesktop.UDisks2.Block']['Drive']
                fs = info['org.freedesktop.UDisks2.Partition']['Type']
                print("Mounting", fs, device, "on", drive, "to ...")
                obj = bus.get_object('org.freedesktop.UDisks2', device)
                #mountpoint = obj.Mount(dict(fstype=fs, options="ro"), dbus_interface="org.freedesktop.UDisks2.Filesystem")
                mountpoint = obj.Mount(dict(options="ro"), dbus_interface="org.freedesktop.UDisks2.Filesystem")
                print("Mounted to ", mountpoint)

    bus.add_signal_receiver(cb_insert_disk, 'InterfacesAdded',   'org.freedesktop.DBus.ObjectManager')

    # start the listener loop
    from gi.repository import GObject
    loop = GObject.MainLoop()
    loop.run()

# start a seprate listener thread
thread=threading.Thread(target=start_listening)
thread.daemon=True # enable CTRL+C for aborting
thread.start()

# And our program will continue in this pointless loop
while True:
    time.sleep(1)

As long as you mount read-only or use journaling filesystems like ext4 or NTFS (not sure) you should not have any problem with data integrity when just pulling the plug. Unmounting not required in that case, the mount automatically disappears.

TODO: python complains about outdated GObject.MainLoop()