Stop a systemd service when a volume is detached (Linux)
To avoid data loss if a volume is detached via the control panel, you can automatically stop the service that depends on it through its systemd service file.
In Linux, it's possible to stop a service that depends on a volume, assuming the service is controlled by systemd. This will help prevent data loss in case you accidentally detach the wrong volume.
This will be demonstrated with a simple service writing the current date and time to a text file on a volume. Once the volume is detached, the service will be stopped automatically.
The example setup
In this setup, a volume with the WWN 3fa0d41402141ef7 is mounted on /mnt/volume1 on a Debian VM.
The program that writes the current date and time to a file is a simple Bash script that looks like below. The file is called date-writer.sh and is placed in /usr/local/sbin/ by root.
#!/bin/bash
PATH=/bin:/usr/bin:/usr/local/bin
while true; do
date >> /mnt/volume1/date-output.txt
sleep 1
doneThe systemd service file for the above script is called date-writer.service and is placed in /etc/systemd/system/ (by root). The two important lines are RequiresMountsFor=/mnt/volume1 and BindsTo=mnt-volume1.mount.
The mnt-volume1.mount file is automatically created by systemd for the volume. Systemd creates its own mounts for all mounts in /etc/fstab. To figure out the correct filename, replace all slashes (/) except the first with a hyphen (-) and add a .mount suffix. In this example, /mnt/volume1 becomes mnt-volume1.mount for systemd. If you have trouble figuring out the systemd name of the mount, you can take a look inside the /run/systemd/generator/ directory.
[Unit]
Description=Write the date to a file
RequiresMountsFor=/mnt/volume1
BindsTo=mnt-volume1.mount
[Service]
ExecStart=/usr/local/sbin/date-writer.sh
[Install]
WantedBy=multi-user.targetOnce the above service file is placed in /etc/systemd/system/ you need to reload the systemd daemon to make it recognize the new file.
Enable and start the service.
Double-check that the service is running.
Check if the script is writing the current date and time to the volume.
Testing
Navigate to Block storage → Storage in the control panel and click on the volume that is mounted on /mnt/volume1. Click Detach.

Confirm the detach in the next dialog box by clicking Detach.

Check if the date-writer.service is running. It should be stopped by now.
The service is indeed stopped (inactive). No more lines should be written to the date-output.txt file.
Once the volume is attached again, you need to manually mount it with sudo mount /mnt/volume1. You also need to restart the service with sudo systemctl restart date-writer.service once the volume is mounted.
The same thing will happen if you manually unmount the volume using sudo umount /mnt/volume1. The service will be instantly stopped to make sure no data is written to the directory /mnt/volume1 when nothing is mounted on it.
Last updated
Was this helpful?