systemd is a set of basic tools that any system can use to build more sophisticated service applications. Using these building you can
create units which can be a:
service
socket
device
mount
automount
swap
target
path
timer
slice
scope
In today’s article, we’ll go through an example that uses service and socket to build a simple server.
Hello, World
To start with, let’s create a “Hello, World” service that will do nothing more than take your connection and send you back the string "Hello, world". First we define our service in a file. Ours is hw.service.
You can install this at ~/.config/systemd/user/hw.service.
The ExecStart holds what systemd will hand the socket connection off to. In this case, we’re going to hand the connection off to a python socket server running from our ~/tmp directory.
You can see that our requires hw.socket. It needs to be up before it will respond to requests. You install this one at ~/.config/systemd/user/hw.socket.
Our socket will listen on 7777 waiting for connections.
The serve.py mentioned in the service file is what systemd will hand the connection off to. The implementation of that server is a simple socket server:
Inside of the Handler class, in the constructor you can see that we avoid the bind and listen steps. This is because systemd has already done this for us. We’re just
going to be handed a file descriptor with the socket already attached.
That’s exactly what’s happening with fromfd here. We’re given a socket to work with via descriptor 3.
The actual implementation of our handler is not doing much more than taking in the request data, and sending back "Hello World".
Getting it installed
You can start your server listening with the following now:
You should be up and running.
Testing
You can use telnet to take a look at your server:
Alternatively, you can just use netcat:
Check that it’s working
After you’ve tested it a few times, you’ll be albe to see requests in the logs.
You should see the lines from the logging.info calls.
Cleaning up
Once you’re done and you’d like to remove these, simply stop the service, remove the units, and reload.