Mounting drives and Udev - Udev does not mount drives but executes other aspects of the script

I want to hot plug an external hard drive, have it mount and automatically run the Unison File Synchronizer.

I have made a udev rule called /etc/udev/rules.d/100-sync.rules

ACTION=="add", SUBSYSTEMS=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="wxyz", ATTRS{idProduct}=="wxyz", RUN+="/home/william/sync.sh"

It triggers this script:

#!/bin/bash
mkdir /media/william/Backup
mount -U <my_drives_uuid> /media/william/Backup
su william -c 'notify-send "Unison" "Starting Sync"'
su william -c 'unison Desktop_Ext_local_connection.prf -silent > /home/william/unison_errors.log'
su william -c 'notify-send "Unison" "Finished Sync"'
umount /media/william/Backup
rmdir /media/william/Backup

Running the script from a root shell works as expected, however when it is triggered by udev, the drive does not mount. (I still get system notifications and directory creation/destruction)

Based on this, I think it doesn't work because udev uses a different namespace. I've tried creating a file /etc/systemd/system/systemd-udevd.service with the contents

[Service]
MountFlags=shared *(and alternatively PrivateMounts=no)*

However this does not change the behaviour - it still doesn't mount. (yes I restarted the daemon)

How can I get the drive to mount using udev?

After my script is done, Ubuntu automatically mounts the drive. Is there a work around which lets Ubuntu mount the drive before udev runs my script?

I cannot see any udev rule which Ubuntu uses to mount the drive, the contents of /etc/udev/rules.d are just

100-sync.rules  70-snap.snapd.rules  70-snap.snap-store.rules

So how is Ubuntu mounting the drive after my script is done, and how can I change the order so that they are mounted first?

I am using Ubuntu 20.04.3 LTS, the same issue occurs on my laptop running 21.04


Solution 1:

AFAIK, all udev scripts that include FS mounting are old few years ago. I believe it had been changed around the time systemd emerged.

Here is a reference note from udev_237 - man udev (Ubuntu_18.04)

RUN{type}

     ︙

    Note that running programs that access the network or mount/unmount filesystems is not allowed inside of udev rules, due to the default sandbox that is enforced on systemd-udevd.service.

Better to go with solutions that use libs like udev, udisks, ... Or an external script that keep watching for that device.

BTW, 100- is too early even for other applications (udev rules files are processed in lexical order), wise to change it into a high 2 digit number. If you want last use 99-