Rclone mount on startup with systemd

All the examples above have one issue: if the mount is currently busy, rclone will exit with nonzero status, fuser will not unmount and the directory will stay busy, trying to access it will result in a 'transport not connected' error. I won't speculate on who's job is to gracefully handle this, for the systemd to do it you need a ExecStop script:

#!/bin/bash
exec 1>&2
# next line sends SIGTERM to any process accessing the mounted filesystem:
fuser -Mk -SIGTERM -m "$@"
while :;
do
    if fuser -m "$@";
    then 
        echo "Mount $@ is busy, waiting..."; sleep 1
    else 
        fusermount -u "$@"; exit 0
    fi

done

The script expects a mount point as its argument. It will send SIGTERM to any process that's accessing the mount (it's optional, can be commented out) and then waits for it to become free. If you comment out the SIGTERM sending line the service will endlessly wait until the mount becomes free.

A sample user service I used it with:

[Unit]
Description=Sample service for mounting a cloud storage with rclone
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/bin/rclone mount RemoteName: /path/to/mountpoint  --cache-dir "$XDG_RUNTIME_DIR" --vfs-cache-mode full --vfs-cache-max-size 262144 --umask 077
ExecStop=/path/to/the/script/above /path/to/mountpoint

[Install]
WantedBy=default.target

p.s. If you need an rclone mount for use only when you're logged in, use systemd user service make things so much easier.

1 Like