컴퓨터구조

systemd 를 통해 service 를 stop 시킬 때, 주의해야할 점

hayz 2023. 4. 1. 00:58

systemd 는 리눅스 에서 부팅부터 서비스 관리, 로그 등 시스템을 다루는데 있어서 백그라운드로 실행되어야 할 프로세스들을 관리해주는 프로세스입니다. 우리가 주로 사용하는 systemctl 이 이러한 systemd 를 관리하는 도구인 것이죠. 

 

항상 띄어야하는 프로세스가 있을 때 우리는 이 systemd 를 이용하여 service 를 만들고, 설정해둡니다. 아래 예시를 보면 

# service 파일 예시
[Unit]
Description=Cleanup old Foo data

[Service]
Type=oneshot
ExecStart=/usr/sbin/foo-cleanup

[Install]
WantedBy=multi-user.target

 

그리고 등록한 service 를 systemd status {service 이름} 을 통해 확인할 수 있습니다. 

출처: https://codingdog.tistory.com/entry/systemctl-status-%EC%84%9C%EB%B9%84%EC%8A%A4%EC%9D%98-%EC%83%81%ED%83%9C%EB%A5%BC-%EB%B3%B8%EB%8B%A4

 

service 를 보다 정교하게 이용하기 위해서는 여러 옵션들을 활용할 수 있습니다. 대표적으로 ExecStart=, ExecStop=, EnvironmentFile= 등이 있는데요. 이번 글에서 자세히 볼 부분은 "ExecStop=" 입니다. ExecStop 은 말 그대로 service 를 stop 하고자 할 때 즉, systemctl stop {service} 를 할 때 어떤 동작이 이루어지는지를 명시하는 부분입니다. 만약 이 부분을 지워두게 되면, 해당 service 와 관련된 process 들을 모두 SIGTERM 명령으로 지우게 됩니다. 

 

[본문 인용]
Since no ExecStop= was specified, systemd will send SIGTERM to all processes started from this service, and after a timeout also SIGKILL. This behavior can be modified, see systemd.kill(5) for details.

 - https://www.freedesktop.org/software/systemd/man/systemd.service.html#Examples 

 

여기서 "해당 service 와 관련된" 의 기준은 무엇일까요? 바로 같은 control group 에 속했는가 입니다. 이 control group 은 cgroup 이라고도 하며 위 systemctl status 명령을 통해 상세 정보를 보면 CGroup 이라는 필드로 여러 프로세스가 포함되어있는 것을 확인할 수 있습니다. 그러면 service 를 종료할 때 항상 이 CGroup 에 속한 프로세스를 모두 종료시켜야 할까요? 

 

service 를 정의할 때 이러한 옵션을 "KillMode=" 를 통해서 설정할 수 있습니다. KillMode= 는 control-group, mixed, process, none 중에 하나를 설정할 수가 있는데 각각 아래와 같은 특징을 가지고 있습니다. 

 

control-group (default) service 와 같은 control-group 에 속한 프로세스 들을 모두 종료합니다.
mixed SIGTERM 시그널은 main 프로세스에 전송되고 이후 SIGKILL 시그널은 나머지 모든 프로세스에 전송됩니다.
process main 프로세스만 종료합니다.  (not recommend!)
none 어떤 프로세스도 종료하지 않습니다.  (not recommend!)

                                                             [표] KillMode= 관련 옵션 

 

[본문 인용]
If set to control-group, all remaining processes in the control group of this unit will be killed on unit stop (for services: after the stop command is executed, as configured with ExecStop=). If set to mixed, the SIGTERM signal (see below) is sent to the main process while the subsequent SIGKILL signal (see below) is sent to all remaining processes of the unit's control group. If set to process, only the main process itself is killed (not recommended!). If set to none, no process is killed (strongly recommended against!). In this case, only the stop command will be executed on unit stop, but no process will be killed otherwise. Processes remaining alive after stop are left in their control group and the control group continues to exist after stop unless empty.

- https://www.freedesktop.org/software/systemd/man/systemd.kill.html#KillMode= 

 

 

기본적으로 service 는 하나의 unit 으로 관리 되어, 제공되고 있는 기본 기능들이 있으니, service 를 관리할 때 참고하시기 바랍니다.