Skip to content

Creating and Managing Daemon Services in Linux using Systemd Shreyas Matade Shreyas Matade

· Follow

8 min read · Jun 21, 2023

Introduction In this article, we’ll dive into a critical component of Linux systems management — the creation of a Daemon Service using systemd. Whether you’re an experienced Linux user or new to the ecosystem, understanding daemons, particularly how to create and manage them, is a fundamental skill that can significantly enhance your Linux journey.

What is a Daemon Service? In the realm of Unix and Unix-like operating systems like Linux, a daemon is a background process or program that is designed to perform tasks without any direct user intervention. In simpler terms, daemons are the silent workhorses of your Linux system, carrying out important tasks in the background while you interact with the user-friendly interface at the front.

These tasks can include anything from starting applications/scripts on system startup, running scheduled tasks, listening for incoming network connections, and more. When your system boots up, it’s the daemon services that are working tirelessly behind the scenes to ensure everything starts up and runs smoothly.

Why does one need Daemon Services? Imagine having to manually start your web server every time your host server restarts, or having to personally initiate system backups at regular intervals. Not only would this be highly inefficient, it would also be near-impossible to handle as the number of tasks increases.

This is where daemon services shine. By automating these tasks and allowing them to run in the background, daemon services free us from the need to micromanage these processes. They enhance system efficiency, help in resource management, and let us focus on more important tasks at hand.

In the following sections, we’ll explore different initialization (init) systems in Linux, will se some basics around systemd (the most widely used init system today), and walk you through creating a sample daemon service step-by-step. This knowledge will empower you to take full control of your Linux system’s background processes, enhancing your overall mastery of Linux system administration.

I hope by the end of this guide, you’ll have a firm grasp on how to create and manage daemon services using systemd.

Understanding Different Init Systems The Linux ecosystem is diverse, and so are the ways it handles its initialization processes — the steps it takes from when you press the power button until you see the login prompt.

History of Init Systems in Linux In the beginning, there was the Unix System V init system (SysV), one of the oldest init systems in the Linux world. Named after the Unix version it originated from, SysV init processes tasks sequentially, waiting for each to complete before moving to the next.

Another noteworthy init system is Upstart, introduced by Ubuntu in 2006. It aimed to address some of SysV’s limitations, introducing event-driven capabilities that allowed simultaneous execution of some startup tasks.

Systemd vs. SysV vs. Upstart Each of these init systems have their own strengths. SysV’s scripts are straightforward and written in shell script, making it relatively easy to manage and understand. However, handling dependencies can be quite a chore with SysV. Upstart improved on this with its event-driven approach, but it wasn’t without its complexities.

Then came systemd in 2010, which sought to address many of the shortcomings of its predecessors. As an init system and service manager, systemd is designed to provide a more efficient way of handling system startup and service management.

Why is systemd widely used today? Systemd is now the default init system for many major Linux distributions, such as Ubuntu, Fedora, RHEL, Debian, and others. Its popularity is due to several reasons:

Speed: By using parallelization, systemd starts services faster and more efficiently. Configuration: Systemd uses declarative configuration files that are easier to manage and understand. Dependencies: Systemd handles dependencies more efficiently, ensuring that services start in the correct order. Control: Systemd provides tools that give admins comprehensive control over system services and resources. Concept of systemd units and available unit types At the heart of systemd is the concept of "units". Units encapsulate various system resources that systemd knows how to manage. Units are categorized into several types, each represented by a file type and responsible for a specific aspect of system functionality:

Service unit (.service): This represents a system service. Target unit (.target): This is a group of systemd units. Automount unit (.automount): This manages a filesystem automount point. Device unit (.device): This represents a device recognized by the kernel. Mount unit (.mount): This manages a filesystem mount point. Path unit (.path): This unit type is used for path-based activation. Socket unit (.socket): This is used for inter-process communication. Understanding these unit types is key to managing system resources with systemd.

In the following section, We will focus on Service Unit and see a step-by-step guide to creating a daemon service using systemd, leveraging this knowledge of init systems and their evolution.

Creating a Daemon Service with systemd Prerequisites: Before we begin, make sure you have the following:

An Ubuntu system with systemd installed (Systemd is the default init system on most Ubuntu versions).

Basic knowledge of Linux command-line interface.

Creating a daemon service with systemd involves writing a script (one can have application as well) for the daemon process and creating a service file for systemd to manage it.

What is a systemd service file? A systemd service file is a unit configuration file that defines how systemd starts and manages a certain background service. This includes instructions on how to start, stop, or restart the service, under what conditions to do so, and what to do if the service fails.

Understanding the basic structure of a systemd service file A systemd service file is composed of various sections, each serving a specific purpose:

[Unit]: This section includes metadata like a human-readable description and dependencies. [Service]: This section specifies how the service should behave, including the command to start the service, the user to run it, and what to do if it fails. [Install]: This section defines the service's behavior regarding the systemctl enable and disable commands. Step-by-step guide to creating a systemd service Let’s create a daemon service. For this example, we’ll create a simple time tracker service (timetracker) that logs the current date and time to a file every minute.

Write a script (timetracker.sh as an example) As I mentioned we can "daemonize" a script as well as an application. For simplicity we will take example of a script. Create a file called timetracker.sh and open it with a text editor:

!/bin/bash

while true do date >> /var/log/timetracker.log sleep 60 done This script will append the current date and time to the timetracker.log file every 60 seconds.

Make the script executable and move it to the appropriate directory To make the script executable, use the chmod command:code

chmod +x timetracker.sh Next, move it to /usr/local/bin (or another directory in your PATH), so it's easily accessible:

mv timetracker.sh /usr/local/bin Create the service file (.service file) Now, we’ll create the systemd service file. This should be placed in the /etc/systemd/system directory, which is where systemd looks for service files. Let's call it timetracker.service:

[Unit] Description=Time Tracker [Service] ExecStart=/usr/local/bin/timetracker.sh [Install] WantedBy=multi-user.target Explanation of various sections and parameters in the service file Description: Under the [Unit] section, Description gives a human-readable description of the service. ExecStart: Under the [Service] section, ExecStart specifies the command that systemd will run to start the service. WantedBy: Under the [Install] section, WantedBy specifies that the service should start when the system reaches the multi-user target, i.e., when the system has finished booting. While this example unit file is basic, it’s essential to understand that systemd is an incredibly powerful tool, capable of accommodating a wide variety of daemon requirements. Should you need to explore more sophisticated configurations, the systemd.service man page is your comprehensive guide. This manual, as with all man pages, provides detailed documentation about the service unit, including all the configurable options.

Accessing this wealth of information is straightforward: simply open a terminal and input the following command:

man systemd.service

Manage (start, stop, enable, disable) the service Once your service file is created and saved, you can use systemctl to manage your service:

systemctl enable timetracker: This sets the time tracker service to start on boot. systemctl start timetracker: This starts the time tracker service immediately. systemctl stop timetracker: This stops the time tracker service. systemctl disable timetracker: This prevents the service from starting on boot. By creating and managing a systemd service, you can automate tasks and ensure they run reliably in the background on your Linux system.

Tracking logs for your systemd services can be done using journalctl, a utility that allows you to query and display messages from the systemd journal.

Tracking logs using journalctl To view the logs for a specific service, you use the -u (or --unit) option followed by the name of the service. For our timetracker service, the command would be:

journalctl -u timetracker This will display all the logs from the timetracker service starting from the oldest. If you want to see the newest entries last, you can add the -e (or --pager-end) option:

journalctl -e -u timetracker In addition, if you want to follow the logs in real-time, you can use the -f (or --follow) option:

journalctl -f -u timetracker If you’re only interested in entries since the last boot, you can use the -b (or --boot) option:

journalctl -b -u timetracker journalctl provides many more options for filtering and displaying log entries. For more information, you can refer to the man page (man journalctl).

Remember, journalctl provides a centralized method to access and manage logs from different systemd units. It's a powerful tool for troubleshooting and system auditing. With journalctl in your Linux toolkit, you can effectively manage and track logs for your systemd services.

Conclusion Understanding and creating daemon services is a fundamental aspect of Linux system administration. They automate and manage key system tasks that run in the background, enhancing the efficiency and performance of the system.

Through this guide, we have taken a very brief view of the world of daemon services using systemd. We’ve explored different init systems, their evolution, and why systemd has emerged as the most widely used init system in modern Linux distributions. We also ventured into the anatomy of a systemd service file, creating our own sample service along the way.

Remember, practice is the key to mastering any skill, and Linux system administration is no different. Create different services, experiment with systemd’s advanced features, and don’t shy away from tackling more complex tasks. Your persistence will be rewarded with a firm grasp over the Linux ecosystem, setting you up for success in your Linux journey.


Sử dụng journalctl để đọc và phân tích Systemd Logs POSTED ON 09/12/2020 BY NGUYỄN ANH KIỆT 09 Th12 Chia sẻ Bài viết này nói về những chức năng cơ bản của công cụ journalctl cùng với những câu lệnh đi kèm nó. Bạn có thể dùng những câu lệnh này trong quá trình sửa lỗi của máy Desktop cũng như server chạy Linux. Sau đây là hướng dẫn dùng journalctl để đọc và phân tích Systemd Logs với những ví dụ khác nhau

Mục lục [Ẩn]

Giới thiệu journald – systemd journal daemon File cấu hình của journald Nơi journald lưu trữ các files log Sử dụng journalctl để đọc và phân tích Systemd Logs Câu lệnh journald cơ bản Câu lệnh journald theo múi giờ Chỉ xem errors, warnings, vv Xem journal logs cho một lần boot cụ thể Xem journal logs cho một thời gian, khoảng thời gian cụ thể Xem journal logs về phần nhân (Kernel) Xem journal logs của một serivce, PID Xem journal logs của một user,group Xem journal logs của một thực thi Giới thiệu Nhiều quan điểm cho rằng systemd không thực sự tốt, nó làm cho hệ thống trở nên nặng nề và đây vẫn là một vấn đề còn luôn gây ra sự tranh cãi. Nhưng bạn không thể phủ nhận rằng nó cũng cấp một loạt công cụ để quản lí cũng như gỡ rối trên hệ thống. Lấy ví dụ hệ thống của bạn bị hỏng phần GUI, hay như bạn có thể lẫn lộn giữa boot và GRUB. Nếu kịch bản đó xảy ra, bạn có thể boot từ chế độ LIVE, mount phân vùng Linux và đọc logs của Systemd để tìm cách xử lí vấn đề này Systemd có ba thành phần chính như sau

systemd: Quản lí hệ thống và dịch vụ cho hệ điều hành Linux systemctl: Câu lệnh để kiểm soát tình trạng của systemd và quản lí các dịch vụ systemd-analyze: Cung cấp các thống kê về hiệu năng khởi động của hệ thống cũng như kiểm tra các trạng thái còn lại và thu thập thông tin từ hệ thống và bộ quản lí dịch vụ Ngoài ba thành phần trên, có các dịch vụ khác mà systemd cung cấp như journald, logind, networkd. Trong bài viết này chúng ta sẽ nói về journald

journald – systemd journal daemon Lợi ích của việc ghi lại các sự kiện một cách tập trung là, các vấn đề trong hệ thống có rất nhiều. Và chúng được lưu dưới dạng mã nhị phân, túc là bạn có thể phiên dịch nó ra text, JSON objects hoặc rất nhiều dạng khác mà bạn muốn. Vì vậy, cực kì đơn giản để có thể tìm ra một sự kiện nhỏ dựa vào thời gian của Logs Nhớ rằng các files log mà journald thu thật được có hàng nghìn dòng và nó được cập nhật mỗi khi có một sự kiện nhỏ nào xảy ra, vì vậy nếu bạn có một hệ thống sử dụng đã lâu, kích cỡ của files đó có thể lên tới hàng GB. Vì vậy chúng ta nên biết những câu lệnh cơ bản để có thể dễ dàng tìm hiểu về các vấn đề của hệ thống hơn

File cấu hình của journald File cấu hình của journald được lưu ở đường dẫn /etc/systemd/journald.conf. Nó rất nhiều tham số để cho chúng ta biết quá trình logging diễn ra như thế nào, bạn không nên chỉnh sửa files này trừ khi bạn biết chắc mình đang làm việc gì

Nơi journald lưu trữ các files log journald lưu trữ các files log ở dạng mã nhị phân, nó được lưu trữ ở đường dẫn /var/log/journal. Đừng dùng công cụ nano, cat hay vi để xem hay sửa những files này vì nó đang ở dạng nhị phân và sẽ không được hiển thị đúng cách

Sử dụng journalctl để đọc và phân tích Systemd Logs Câu lệnh journald cơ bản Câu lệnh cơ bản để đọc logs của journal daemon là

journalctl

Bạn sẽ được cung cấp toàn bộ những mục như lỗi, cảnh báo, vv từ tất cả các ứng dụng và tiến trình. Nó sẽ xuất ra danh sách từ những log cũ nhất phía trên và dòng logs mới nhất ở dưới cuối. bạn có thể bấm Enter hoặc phím PAGE UP và PAGE DOWN để cuộn. Bấm phím q để thoát

Câu lệnh journald theo múi giờ Mặc định, journalctl hiển thị log time theo múi giờ hiện tại của bạn. Tuy nhiên, bạn có thể dễ dàng yêu cầu chương trình hiển thị theo múi giờ bạn chỉ định, ví dụ để xem ở múi giờ UTC, dùng câu lệnh dưới đây

journalctl --utc

Chỉ xem errors, warnings, vv The logs that a system generates have different priorities. Some logs may be a warning which can be ignored or some may be critical errors. You might want to look at only errors, not warnings. That is also possible using the below command. Logs mà hệ thống xuất ra có những mức ưu tiên khác nhau. Nhiều Logs chỉ là cảnh báo bạn có thể không cần quan tâm, nhưng một số logs là mỗi nghiêm trọng. Bạn chỉ cần lọc ra những lỗi, không phải cảnh báo. Điều này hoàn toàn có thể khi sử dụng câu lệnh dưới

journalctl -p 0 Error Code như sau

0: emergency 1: alerts 2: critical 3: errors 4: warning 5: notice 6: info 7: debug Xem journal logs cho một lần boot cụ thể Để xem danh sách các lần khởi động kèm thời gian, bạn gõ lệnh sau

journalctl --list-boots

Cột đầu tiên hiển thị số thứ tự Boot Track Number của lần Boot Cột thứ hai là Boot ID Cột tiếp theo là về thời gian boot Để xem journal logs cho một lần boot cụ thể. Bạn thực hiện lệnh sau

journalctl -b -Boot Track Number journalctl -b Boot ID

Bạn có thê rthêm tham số -x để được giải thích về từng lỗi mà đang gặp phải. Ví dụ

journalctl -xb -p 3

Xem journal logs cho một thời gian, khoảng thời gian cụ thể Bạn có thể dùng tham số --since với các giá tị như "yesterday", "today", "tomorrow", "now". Hoặc với khoảng thời gian cụ thể theo định dạng "YYYY-MM-DD HH:MM:SS" Một số ví dụ

journalctl --since "2020-12-04 06:00:00" journalctl --since "2020-12-03" --until "2020-12-05 03:00:00" journalctl --since yesterday journalctl --since 09:00 --until "1 hour ago"

Xem journal logs về phần nhân (Kernel) Các bạn sử dụng câu lệnh với tham số -k

journalctl -k Xem journal logs của một serivce, PID Các bạn sử dụng câu lệnh với tham số -u

journalctl -u NetworkManager.service Nếu bạn chưa nắm được tên service, bạn có thể sử dụng câu lệnh sau để tìm

systemctl list-units --type=service

Xem journal logs của một user,group Các bạn dùng câu lệnh id -u để tìm ID của user/group đó id -u debugpoint Sau đó dùng tham số _UID cho User và _GID cho Group để xem journalctl _UID=1000 –since today

Xem journal logs của một thực thi Bạn sử dụng câu lệnh

journalctl /usr/bin/gnome-shell --since today

https://cloudzone.vn/su-dung-journalctl-de-doc-va-phan-tich-systemd-logs/