Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Systemd Services: Reacting to Change

#1
Systemd Services: Reacting to Change

<div style="margin: 5px 5% 10px 5%;"><img src="http://www.sickgaming.net/blog/wp-content/uploads/2018/06/systemd-services-reacting-to-change.png" width="1500" height="707" title="" alt="" /></div><div><div><img src="http://www.sickgaming.net/blog/wp-content/uploads/2018/06/systemd-services-reacting-to-change.png" class="ff-og-image-inserted" /></div>
<p><a href="https://www.intel.com/content/www/us/en/products/boards-kits/compute-stick/stk1a32sc.html">I have one of these Compute Sticks</a> (Figure 1) and use it as an all-purpose server. It is inconspicuous and silent and, as it is built around an x86 architecture, I don’t have problems getting it to work with drivers for my printer, and that’s what it does most days: it interfaces with the shared printer and scanner in my living room.</p>
<p>Most of the time it is idle, especially when we are out, so I thought it would be good idea to use it as a surveillance system. The device doesn’t come with its own camera, and it wouldn’t need to be spying all the time. I also didn’t want to have to start the image capturing by hand because this would mean having to log into the Stick using SSH and fire up the process by writing commands in the shell before rushing out the door.</p>
<p>So I thought that the thing to do would be to grab a USB webcam and have the surveillance system fire up automatically just by plugging it in. Bonus points if the surveillance system fired up also after the Stick rebooted, and it found that the camera was connected.</p>
<p>In prior installments, we saw that <a href="https://www.linux.com/blog/learn/intro-to-linux/2018/5/writing-systemd-services-fun-and-profit">systemd services can be started or stopped by hand</a> or <a href="https://www.linux.com/blog/learn/2018/5/systemd-services-beyond-starting-and-stopping">when certain conditions are met</a>. Those conditions are not limited to when the OS reaches a certain state in the boot up or powerdown sequence but can also be when you plug in new hardware or when things change in the filesystem. You do that by combining a Udev rule with a systemd service.</p>
<h3>Hotplugging with Udev</h3>
<p>Udev rules live in the <i>/etc/udev/rules</i> directory and are usually a single line containing <i>conditions</i> and <i>assignments</i> that lead to an <i>action</i>.</p>
<p>That was a bit cryptic. Let’s try again:</p>
<p>Typically, in a Udev rule, you tell systemd what to look for when a device is connected. For example, you may want to check if the make and model of a device you just plugged in correspond to the make and model of the device you are telling Udev to wait for. Those are the <i>conditions</i> mentioned earlier.</p>
<p>Then you may want to change some stuff so you can use the device easily later. An example of that would be to change the read and write permissions to a device: if you plug in a USB printer, you’re going to want users to be able to read information from the printer (the user’s printing app would want to know the model, make, and whether it is ready to receive print jobs or not) and write to it, that is, send stuff to print. Changing the read and write permissions for a device is done using one of the <i>assignments</i> you read about earlier.</p>
<p>Finally, you will probably want the system to do something when the conditions mentioned above are met, like start a backup application to copy important files when a certain external hard disk drive is plugged in. That is an example of an <i>action</i> mentioned above.</p>
<p>With that in mind, ponder this:</p>
<pre>
ACTION=="add", SUBSYSTEM=="video4linux", ATTRS{idVendor}=="03f0", ATTRS{idProduct}=="e207", SYMLINK+="mywebcam", TAG+="systemd", MODE="0666", ENV{SYSTEMD_WANTS}="webcam.service"
</pre>
<p>The first part of the rule,</p>
<pre>
ACTION=="add", SUBSYSTEM=="video4linux", ATTRS{idVendor}=="03f0", ATTRS{idProduct}=="e207" <i>[etc... ]</i>
</pre>
<p>shows the conditions that the device has to meet before doing any of the other stuff you want the system to do. The device has to be added (<code>ACTION=="add"</code>) to the machine, it has to be integrated into the <code>video4linux</code> subsystem. To make sure the rule is applied only when the correct device is plugged in, you have to make sure Udev correctly identifies the manufacturer (<code>ATTRS{idVendor}=="03f0"</code>) and a model (<code>ATTRS{idProduct}=="e207"</code>) of the device.</p>
<p>In this case, we’re talking about this device (Figure 2):</p>
<p>Notice how you use <code>==</code> to indicate that these are a logical operation. You would read the above snippet of the rule like this:</p>
<pre>
if the device is added and the device controlled by the video4linux subsystem and the manufacturer of the device is 03f0 and the model is e207, then...</pre>
<p>But where do you get all this information? Where do you find the action that triggers the event, the manufacturer, model, and so on? You will probably have to use several sources. The <code>IdVendor</code> and <code>idProduct</code> you can get by plugging the webcam into your machine and running <code>lsusb</code>:</p>
<pre>
<b>lsusb</b>
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub <i>Bus 003 Device 003: ID 03f0:e207 Hewlett-Packard</i>
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 003: ID 04f2:b1bb Chicony Electronics Co., Ltd
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
</pre>
<p>The webcam I’m using is made by HP, and you can only see one HP device in the list above. The <code>ID</code> gives you the manufacturer and the model numbers separated by a colon (<code>:</code>). If you have more than one device by the same manufacturer and not sure which is which, unplug the webcam, run <code>lsusb</code> again and check what’s missing.</p>
<p>OR…</p>
<p>Unplug the webcam, wait a few seconds, run the command <code>udevadmin monitor --environment</code> and then plug the webcam back in again. When you do that with the HP webcam, you get:</p>
<pre>
<b>udevadmin monitor --environment</b>
UDEV [35776.495221] add /devices/pci0000:00/0000:00:1c.3/0000:04:00.0
  /usb3/3-1/3-1:1.0/input/input21/event11 (input) .MM_USBIFNUM=00 ACTION=add BACKSPACE=guess DEVLINKS=/dev/input/by-path/pci-0000:04:00.0-usb-0:1:1.0-event   /dev/input/by-id/usb-Hewlett_Packard_HP_Webcam_HD_2300-event-if00 DEVNAME=/dev/input/event11 DEVPATH=/devices/pci0000:00/0000:00:1c.3/0000:04:00.0/
  usb3/3-1/3-1:1.0/input/input21/event11 ID_BUS=usb ID_INPUT=1 ID_INPUT_KEY=1 ID_MODEL=HP_Webcam_HD_2300 ID_MODEL_ENC=HP\x20Webcam\x20HD\x202300 ID_MODEL_ID=e207 ID_PATH=pci-0000:04:00.0-usb-0:1:1.0 ID_PATH_TAG=pci-0000_04_00_0-usb-0_1_1_0 ID_REVISION=1020 ID_SERIAL=Hewlett_Packard_HP_Webcam_HD_2300 ID_TYPE=video ID_USB_DRIVER=uvcvideo ID_USB_INTERFACES=:0e0100:0e0200:010100:010200:030000: ID_USB_INTERFACE_NUM=00 ID_VENDOR=Hewlett_Packard ID_VENDOR_ENC=Hewlett\x20Packard ID_VENDOR_ID=03f0 LIBINPUT_DEVICE_GROUP=3/3f0/e207:usb-0000:04:00.0-1/button MAJOR=13 MINOR=75 SEQNUM=3162 SUBSYSTEM=input USEC_INITIALIZED=35776495065 XKBLAYOUT=es XKBMODEL=pc105 XKBOPTIONS= XKBVARIANT=
</pre>
<p>That may look like a lot to process, but, check this out: the <code>ACTION</code> field early in the list tells you what event just happened, i.e., that a device got added to the system. You can also see the name of the device spelled out on several of the lines, so you can be pretty sure that it is the device you are looking for. The output also shows the manufacturer’s ID number (<code>ID_VENDOR_ID=03f0</code>) and the model number (<code>ID_VENDOR_ID=03f0</code>).</p>
<p>This gives you three of the four values the condition part of the rule needs. You may be tempted to think that it a gives you the fourth, too, because there is also a line that says:</p>
<pre>
SUBSYSTEM=input
</pre>
<p>Be careful! Although it is true that a USB webcam is a device that provides input (as does a keyboard and a mouse), it is also belongs to the <i>usb</i> subsystem, and several others. This means that your webcam gets added to several subsystems and looks like several devices. If you pick the wrong subsystem, your rule may not work as you want it to, or, indeed, at all.</p>
<p>So, the third thing you have to check is all the subsystems the webcam has got added to and pick the correct one. To do that, unplug your webcam again and run:</p>
<pre>
ls /dev/video*
</pre>
<p>This will show you all the video devices connected to the machine. If you are using a laptop, most come with a built-in webcam and it will probably show up as <code>/dev/video0</code>. Plug your webcam back in and run <code>ls /dev/video*</code> again.</p>
<p>Now you should see one more video device (probably <code>/dev/video1</code>).</p>
<p>Now you can find out all the subsystems it belongs to by running <code>udevadm info -a /dev/video1</code>:</p>
<pre>
<b>udevadm info -a /dev/video1</b> Udevadm info starts with the device specified by the devpath and then walks up the chain of parent devices. It prints for every device found, all possible attributes in the udev rules key format. A rule to match, can be composed by the attributes of the device and the attributes from one single parent device. looking at device '/devices/pci0000:00/0000:00:1c.3/0000:04:00.0
  /usb3/3-1/3-1:1.0/video4linux/video1': KERNEL=="video1" SUBSYSTEM=="video4linux" DRIVER=="" ATTR{dev_debug}=="0" ATTR{index}=="0" ATTR{name}=="HP Webcam HD 2300: HP Webcam HD" <i>[etc...]</i>
</pre>
<p>The output goes on for quite a while, but what you’re interested is right at the beginning: <code>SUBSYSTEM=="video4linux"</code>. This is a line you can literally copy and paste right into your rule. The rest of the output (not shown for brevity) gives you a couple more nuggets, like the manufacturer and mode IDs, again in a format you can copy and paste into your rule.</p>
<p>Now you have a way of identifying the device and what event should trigger the action univocally, it is time to tinker with the device.</p>
<p>The next section in the rule, <code>SYMLINK+="mywebcam", TAG+="systemd", MODE="0666"</code> tells Udev to do three things: First, you want to create symbolic link from the device to (e.g. <i>/dev/video1</i>) to <i>/dev/mywebcam</i>. This is because you cannot predict what the system is going to call the device by default. When you have an in-built webcam and you hotplug a new one, the in-built webcam will usually be <i>/dev/video0</i> while the external one will become <i>/dev/video1</i>. However, if you boot your computer with the external USB webcam plugged in, that could be reversed and the internal webcam can become <i>/dev/video1</i> and the external one <i>/dev/video0</i>. What this is telling you is that, although your image-capturing script (which you will see later on) always needs to point to the external webcam device, you can’t rely on it being <i>/dev/video0</i> or <i>/dev/video1</i>. To solve this problem, you tell Udev to create a symbolic link which will never change in the moment the device is added to the <i>video4linux</i> subsystem and you will make your script point to that.</p>
<p>The second thing you do is add <code>"systemd"</code> to the list of Udev tags associated with this rule. This tells Udev that the action that the rule will trigger will be managed by systemd, that is, it will be some sort of systemd service.</p>
<p>Notice how in both cases you use <code>+=</code> operator. This adds the value to a list, which means you can add more than one value to <code>SYMLINK</code> and <code>TAG</code>.</p>
<p>The <code>MODE</code> values, on the other hand, can only contain one value (hence you use the simple <code>=</code> assignment operator). What <code>MODE</code> does is tell Udev who can read from or write to the device. If you are familiar with <code>chmod</code> (and, if you are reading this, you should be), you will also be familiar of <a href="https://chmod-calculator.com/">how you can express permissions using numbers</a>. That is what this is: <code>0666</code> means “<i>give read and write privileges to the device to everybody</i>“.</p>
<p>At last, <code>ENV{SYSTEMD_WANTS}="webcam.service"</code> tells Udev what systemd service to run.</p>
<p>Save this rule into file called <i>90-webcam.rules</i> (or something like that) in <i>/etc/udev/rules.d</i> and you can load it either by rebooting your machine, or by running:</p>
<pre>
sudo udevadm control --reload-rules &amp;&amp; udevadm trigger
</pre>
<h2>Service at Last</h2>
<p>The service the Udev rule triggers is ridiculously simple:</p>
<pre>
# webcam.service [Service] Type=simple ExecStart=/home/[<i>user name</i>]/bin/checkimage.sh
</pre>
<p>Basically, it just runs the <i>checkimage.sh</i> script stored in your personal <i>bin/</i> and pushes it the background. <a href="https://www.linux.com/blog/learn/intro-to-linux/2018/5/writing-systemd-services-fun-and-profit">This is something you saw how to do in prior installments</a>. It may seem something little, but just because it is called by a Udev rule, you have just created a special kind of systemd unit called a <i>device</i> unit. Congratulations.</p>
<p>As for the <i>checkimage.sh</i> script <i>webcam.service</i> calls, there are several ways of grabbing an image from a webcam and comparing it to a prior one to check for changes (which is what <i>checkimage.sh</i> does), but this is how I did it:</p>
<pre>
#!/bin/bash # This is the checkimage.sh script mplayer -vo png -frames 1 tv:// -tv driver=v4l2:width=640:height=480:device=
  /dev/mywebcam &amp;&gt;/dev/null mv 00000001.png /home/[<i>user name</i>]/monitor/monitor.png while true do mplayer -vo png -frames 1 tv:// -tv driver=v4l2:width=640:height=480:device=/dev/mywebcam &amp;&gt;/dev/null mv 00000001.png /home/[<i>user name</i>]/monitor/temp.png imagediff=`compare -metric mae /home/[<i>user name</i>]/monitor/monitor.png /home/[<i>user name</i>]
  /monitor/temp.png /home/[<i>user name</i>]/monitor/diff.png 2&gt;&amp;1 &gt; /dev/null | cut -f 1 -d " "` if [ `echo "$imagediff &gt; 700.0" | bc` -eq 1 ] then mv /home/[<i>user name</i>]/monitor/temp.png /home/[<i>user name</i>]/monitor/monitor.png fi sleep 0.5 done
</pre>
<p>Start by using <a href="https://mplayerhq.hu/design7/news.html">MPlayer</a> to grab a frame (<i>00000001.png</i>) from the webcam. Notice how we point <code>mplayer</code> to the <code>mywebcam</code> symbolic link we created in our Udev rule, instead of to <code>video0</code> or <code>video1</code>. Then you transfer the image to the <i>monitor/</i> directory in your home directory. Then run an infinite loop that does the same thing again and again, but also uses <a href="https://www.imagemagick.org/script/compare.php">Image Magick’s <i>compare</i> tool</a> to see if there any differences between the last image captured and the one that is already in the <i>monitor/</i> directory.</p>
<p>If the images are different, it means something has moved within the webcam’s frame. The script overwrites the original image with the new image and continues comparing waiting for some more movement.</p>
<h3>Plugged</h3>
<p>With all the bits and pieces in place, when you plug your webcam in, your Udev rule will be triggered and will start the <i>webcam.service</i>. The <i>webcam.service</i> will execute <i>checkimage.sh</i> in the background, and <i>checkimage.sh</i> will start taking pictures every half a second. You will know because your webcam’s LED will start flashing indicating every time it takes a snap.</p>
<p>As always, if something goes wrong, run</p>
<pre>
systemctl status webcam.service
</pre>
<p>to check what your service and script are up to.</p>
<h3>Coming up</h3>
<p>You may be wondering: Why overwrite the original image? Surely you would want to see what’s going on if the system detects any movement, right? You would be right, but as you will see in the next installment, leaving things as they are and processing the images using yet another type of systemd unit makes things nice, clean and easy.</p>
<p>Just wait and see.</p>
<p><em>Learn more about Linux through the free <a href="https://training.linuxfoundation.org/linux-courses/system-administration-training/introduction-to-linux">“Introduction to Linux” </a>course from The Linux Foundation and edX.</em></p>
</div>
Reply



Forum Jump:


Users browsing this thread:
3 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016