Tuesday, August 14, 2018

How to create your own system.d service


If you explore latest Red Hat linux, you will see that the  traditional init scripts are gone. It's much easier to use rather then SysVinit, it reduces system startup time because the processes are running in parallel. It has also very nice logging mechanism. Let's write simple examples for CentOS7

Create a bash file:
 touch /usr/local/sbin/{launcher_name}.sh

It's a simple bash file that launches java application.
#!/bin/bash
java -jar /root/{name}.jar

Add execution permission
chmod +x {launcher_name}.sh

Create service:
touch /etc/systemd/system/{service_name}.service

Configuration:
[Unit]
Description=Application launcher service

[Service]
Type=simple
ExecStart=/usr/local/sbin/{launcher_name}.sh
TimeoutStartSec=0

[Install]
WantedBy=default.target

Set permissions:
chmod 664  {service_name}.service

Reload daemon
 systemctl daemon-reload 

Usage:
systemctl enable {service_name}
systemctl start {service_name}

We can create the same using init instead of sytstem.d. We shiuld just create configuration to the following locataion: /etc/init.d


#! /bin/sh
# /etc/init.d/{service_name}
### BEGIN INIT INFO
# Provides:           {service_name}
# Default-Start:      2 3 4 5
# Default-Stop:       0 1 6
# Short-Description:  Example of init service.
### END INIT INFO
# Actions provided to make it LSB-compliant
case "$1" in
  start)
    export DISPLAY=:0
    sh {launcher_name}.sh
    ;;
  stop)
    echo "Stopping"
    ...
    ;;
  restart)
    echo "Restarting"
    ;;
  force-reload)
    echo "Reloading"
    ...
    ;;
  status)
    echo "Status"
    ...
    ;;
  *)
    echo "Usage: /etc/init.d/{service_name} 
        {start|stop|restart|force-reload|status}"
    exit 1
    ;;
esac
exit 0 



How to allow non-root users to control system.d services/utilities that needs root permissions.

How to allow non-root users to control system.d services/utilities that needs root permissions.

By default sudo is not installed on debian. So, install sudo
apt-get install sudo -y

Add current user to sodoers list
usermod -a -G sudo vq

Change editor for visudo (I love vim).
update-alternatives --config editor

Let's give user perrmision to reboot without password. First off all we should change configuration in /etc/sudoers file. In order to edit the fiole  use visudo:
vq ALL=NOPASSWD:/sbin/reboot

Usage (password is not required)
sudo reboot

Now let's allow user to access concrete system.d service without password. For example let's do it for firewalld service.

Create file
cd /etc/sudoers.d
touch vq
vim vq

Add the following configuration
%vq ALL= NOPASSWD: /bin/systemctl start firewalld
%vq ALL= NOPASSWD: /bin/systemctl stop firewalld
%vq ALL= NOPASSWD: /bin/systemctl status firewalld

Usage (password is not required)
sudo systemctl start firewalld
sudo systemctl stop firewalld
sudo systemctl status firewalld

Note that my user and group is called vq

.