Brain Phrye

code cooking diy fiction personal photos politics reviews tools 


Systemd User

A while back I set up a CO2 sensor in my office. The setup requires a prometheus server to scrape it and a python script to get the data off the sensor and expose them for prometheus to scrape.

I’ve been running it in two open terminals for several months now. You can upgrade Linux desktops without rebooting or restarting your desktop session for quite a while. Eventually though it will start getting kinda flakey. But I wasn’t going to bounce my machine and then start those two stupid terminals all over again.

When I first played with systemd I noticed it allowed you to have init files for users. Hunting around I found this page which gave some good overview of what to do. However there were some things missing. So what follows are some notes on running a personal prometheus server using systemd’s user unit support.

First step is to make a unit file. These go in ~/.config/systemd/user/ and the one I used for prometheus was in prometheus.service:

1
2
3
4
5
6
7
8
9
[Unit]
Description=Prometheus Metrics Server

[Service]
WorkingDirectory=/home/lyda/Downloads/prometheus-2.10.0.linux-amd64
ExecStart=/home/lyda/Downloads/prometheus-2.10.0.linux-amd64/prometheus --storage.tsdb.retention.time=400d

[Install]
WantedBy=default.target

Now that’s all very specific to me on this machine. If you’re copying this, note that it includes where I downloaded prometheus, my username and so on. The WorkingDirectory is there because by default prometheus uses it’s current directory to store data and read consoles. You can explicitly set all that as a set of command line flags. This was just a quick and dirty way of doing it.

Next you’ll want this to run on system startup.

To do this just run sudo loginctl enable-linger $USER. Some versions of systemd have a bug so make sure /var/lib/systemd/linger/$USER exists and if not just run sudo touch /var/lib/systemd/linger/$USER

Next up you’ll need to get systemd to reread its configs. Not the system systemd, but the systemd for your user. To do that run systemctl --user daemon-reload. At this point the new unit is seen but it’s not yet enabled.

To enable it, just run systemctl --user enable prometheus.service - again, this is just as you would do with systemctl commands for the system as a whole, just with the --user flag.

At the next reboot, this will start right up. To start it now, just run systemctl --user start prometheus.service. To confirm it’s running you can just do systemctl --user status prometheus.service and to look at the logs, just run journalctl --user -u prometheus

This is pretty handy and I can imagine uses beyond this. Generally these revolve around caching things and keeping stuff up to daye and since you can have timer services with systemd, this could be a way to manage them. I could easily keep all periodic jobs for each machine in my home dir configs .