9

I am working on a lab for my linux class and the teacher is teaching us about Systemd.

How do I create a service that starts a script when a specific device is mounted using this command: mount /dev/xvdc1 /mnt/backup

What I have tried

  1. Using a Timer I checked if /mnt/backup was a mount point. (teacher would not accept it. It must be strictly event driven)
  2. Creating a .mount unit and making the .service unit require the .mount unit. This approach did not start the script when executing the command: mount /dev/xvdc1 /mnt/backup

I think I may be approaching this problem the wrong way. This is the lab problem.

"Create a unit file that copies all the files from /mnt/backup using rsync as soon as /dev/xvdc1 is mounted."

What I know:

  1. The device that will be mounted will always be /dev/xvdc1
  2. The mount point of the device will always be /mnt/backup
  3. The Service must be started based on /dev/xvdc1 being mounted

Here is my .service unit file

[Unit]
Description=Starts a backup for /dev/xvdc1 when mounted using the mount command.

[Service]
Type=simple
ExecStart=/root/backupscript.sh
ExecStop=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
2

1 Answer 1

4

Systemd Unit Start Conditions

With ConditionPathExists= a file existence condition is checked before a unit is started. If the specified absolute path name does not exist, the condition will fail. If the absolute path name passed to ConditionPathExists= is prefixed with an exclamation mark ("!"), the test is negated, and the unit is only started if the path does not exist.

ConditionPathIsMountPoint= is similar to ConditionPathExists= but verifies whether a certain path exists and is a mount point.

Seems like the easiest method is to include

ConditionPathIsMountPoint=/mnt/backup

In your [Unit] section. Though this doesn't check which device is mounted there, though in the case of creating a backup the user may not be picky.

You'd probably also need Restart=on-failure to continue trying to start the service.


A more precise method would be to write a udev rule that starts the service when a particular device is mounted.

As a reference

Start by finding your device in lsusb. Note the ID (eg 0a81:0101)

Create a new udev rules file in /etc/udev/rules.d/ via sudoedit /etc/udev/rules.d/100-mount-videos.rulesand plonk a new rule in there like this:

ACTION=="add", ATTRS{idVendor}=="0a81", ATTRS{idProduct}=="0101", RUN+="/home/your_username/bin/mount_videos.sh"

You could just replace the RUN+= with RUN+=/usr/bin/systemctl start backup.service or whatever you called your service

1
  • 1
    It doesn't look like systemd tries to start the unit again once the condition is met. Restarting only seems to apply when the unit terminates, not when it couldn't be started at all. Commented Dec 26, 2018 at 0:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .