Lab 2: Creating a Service

 

Objective

To learn about service files by creating our own service.


 

Ticker Service

For this lab you will make a service, or daemon, which starts automatically with your server and runs continuously.

The program is a simple "ticker" which simply logs the current time every 10 seconds. You can use the following Python program for this:


#!/usr/bin/python3

import time
import signal
import sys
from datetime import datetime

# global variable for controlling shutting down
running = True

# function which is called when term signal is sent
def handle_sigterm(signum, frame):
    global running
    running = False
    print("Ticker service shutting down", flush=True)


def main():
    print("Ticker daemon starting up", flush=True)

    # register our sigterm handler
    signal.signal(signal.SIGTERM, handle_sigterm)

    # keep running until the sigterm is given
    while running:
        print("Tick:", datetime.now(), flush=True)
        time.sleep(10)
    print("Daemon exited", flush=True)

main()

The program runs until it receives the "TERM" signal, at which point it exits. We will learn more about signals in the coming weeks.

Start by just downloading this program and running it with the "python3" command:

$ python3 ticker.py

The program should print out info every 10 seconds until you hit Ctrl-C.


 

Making it a Service

Systemd service files live in /etc/systemd/system. You should create a file in this directory called ticker.service. Look at some of the other .service files in this directory to get a feel for what they look like.

Your service file needs at minimum three things:

  1. A Description field, under the [Unit] section.
  2. An ExecStart field, under the [Service] section. For this, make sure you use absolute paths.
  3. A WantedBy filed, under the [Install] section. This is what will link your service to a run level.

Once you've created the service file, you should be able to reference it with systemctl and journalctl commands.

Do the following:

  1. Enable your service so it starts at boot.
  2. Start your service.
  3. Check the status to make sure it's running.

 

Submitting

When you're done, run the systemctl command to show that the ticker service is currently enabled and running, and the journalctl command to show its output. Then, take a screenshot of your terminal and submit that to Canvas.