Using a systemd socket service to serialize and send CLI API messages

I’m running the latest jessie on a RPi and wanted to be able to send a CLI message from any user account but you must use sudo with hologram send which I would rather not do so I set up a socket service to handle the out going messages without the need for sudo from user space. With this the user script only needs to do this:

echo my data | nc localhost 3000

to get “my data” sent with out the need for sudo. This also will serialize the data from multiple processes so as to eliminate more that one thread from trying to send at the same time. Maybe there an easier way to accomplish the same thing?

Here is the script that gets started by systemd to listen to the local socket.

#!/bin/bash
coproc netcat -l localhost 3000
while read -r data; do
hologram send "$data"
done <&${COPROC[0]} >&${COPROC[1]}

Here is /lib/systemd/system/holosend.socket
[Unit]
Description=Hologram Message Send Socket
PartOf=holosend.service

[Socket]
ListenStream=127.0.0.1:3000

[Install]
WantedBy=sockets.target

Here is /lib/systemd/system/holosend.service

[Unit]
Description=Hologram Message Send Service
After=network.target holosend.socket
Requires=holosend.socket

[Service]
Type=simple
ExecStart=/bin/bash /root/holosend.sh
TimeoutStopSec=5

[Install]
WantedBy=multi-user.target

After this is all in place, start the service with:
sudo service holosend start

And if you wish it to start on boot:
sudo systemctl enable holosend

So is the main issue here to try to avoid using sudo? Your script is still running as root so in the end it’s kind of the same. Not needing threads is nice.

I agree with you in that I would prefer not to have to use sudo for any of this. It’s something we’ve had on our wish list for a little while. We may put together an install script at some point that sets all the needed permissions so sudo isn’t needed.

Not using sudo from a cron job in user space is one but serializing the messages so multiple user threads do not collide for the same resource is another reason to do it this way.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.