Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - Generic Host를 이용해 .NET 5로 리눅스 daemon 프로그램 만드는 방법

지난번에는 별다른 의존성 없이 단순하게 만드는 방법을 소개했는데요,

C# - .NET Core Console로 리눅스 daemon 프로그램 만드는 방법
; https://www.sysnet.pe.kr/2/0/11958

이번에는 ASP.NET Core의 Generic host를 이용한 방법으로 작성해 보겠습니다. 이에 대해서는 마이크로소프트의 문서에 친절하게 설명하고 있으니,

.NET Generic Host in ASP.NET Core
; https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host

위의 내용을 보셔도 충분합니다. ^^




시작은 .NET 5 Console 프로그램으로 만듭니다. 그다음 Generic Host를 위한 관련 패키지를 추가하면 되는데요, 혹은 그냥 간단하게 ".NET Core 콘솔 프로젝트에서 Kestrel 호스팅 방법" 글에서 설명한 것처럼 Console csproj 파일의 Sdk 항목을 "Microsoft.NET.Sdk.Web"으로 변경해도 됩니다.

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

</Project>

이제 Program.cs의 Main 메서드를 다음과 같이 작성하고,

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace testd
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var host = new HostBuilder()
                .ConfigureServices((hostContext, services) => services.AddHostedService<ShutdownService>())
                .UseConsoleLifetime()
                .Build();

            await host.RunAsync();
        }
    }
}

실질적인 서비스 코드는 별도의 ShutdownService.cs 파일을 만들어 다음과 같이 만들어 두면 됩니다.

using Microsoft.Extensions.Hosting;
using System.Threading;
using System.Threading.Tasks;

namespace testd
{
    class ShutdownService : IHostedService
    {
        private bool pleaseStop;
        private Task BackgroundTask;
        private readonly IHostApplicationLifetime applicationLifetime;

        public ShutdownService(IHostApplicationLifetime applicationLifetime)
        {
            this.applicationLifetime = applicationLifetime;
        }

        public Task StartAsync(CancellationToken _)
        {
            Console.WriteLine("[testd] Starting service");

            BackgroundTask = Task.Run(async () =>
            {
                while (!pleaseStop)
                {
                    await Task.Delay(50);
                }

                Console.WriteLine("[testd] Background task gracefully stopped");
            });

            return Task.CompletedTask;
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("[testd] Stopping service");

            pleaseStop = true;
            await BackgroundTask;

            Console.WriteLine("[testd] Service stopped");
        }
    }
}

당연히, BackgroundTask 속성에 할당한 Task.Run 코드에는 여러분이 원하는 코드를 넣어야 합니다. 사실상 위의 코드가 전부이고 나머지 팁/트릭은 ".NET Generic Host in ASP.NET Core" 글의 내용을 참고해 멋을 좀 더 부리시면 됩니다.




편의상, 서비스 등록/해제를 위한 코드를 "C# - .NET Core Console로 리눅스 daemon 프로그램 만드는 방법" 글에서 소개한 방법처럼 사용해도 됩니다.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace testd
{
    class Program
    {
        static async Task Main(string[] args)
        {
            if (args.Length >= 1)
            {
                string netDllPath = typeof(Program).Assembly.Location;

                if (args[0] == "--install" || args[0] == "-i")
                {
                    InstallService(netDllPath, true);
                }

                else if (args[0] == "--uninstall" || args[0] == "-u")
                {
                    InstallService(netDllPath, false);
                }

                return;
            }

            var host = new HostBuilder()
                .ConfigureServices((hostContext, services) => services.AddHostedService<ShutdownService>())
                .UseConsoleLifetime()
                .Build();

            await host.RunAsync();
        }


        static int InstallService(string netDllPath, bool doInstall)
        {
            // 2021-04-22 업데이트
            // KillSignal=SIGINT 제거
            // KillMode=mixed 추가
            string serviceFile = @"
[Unit]
Description={0} running on {1}

[Service]
WorkingDirectory={2}
ExecStart={3} {4}
SyslogIdentifier={5}
KillMode=mixed

[Install]
WantedBy=multi-user.target
";
            // ...[생략]...
        }

        static int ControlService(string serviceName, string mode)
        {
            // ...[생략]...
        }
    }
}

이후 서비스 등록/해제 및 systemctl 관련 명령어를 다음과 같이 수행할 수 있습니다.

[서비스 등록]
sudo dotnet ./testd.dll --install

[서비스 해제]
sudo dotnet ./testd.dll --uninstall

[서비스 시작]
sudo systemctl start dotnet-testd

[서비스 중지-1 SIGINT]
sudo systemctl stop dotnet-testd

[서비스 중지-2 SIGTERM]
sudo systemctl kill dotnet-testd

// 기타 Ctrl + '\'키로 발생하는 SIGQUIT

확인을 위해 서비스 등록을 하고 "tail -F /var/log/syslog"로 보면 다음과 같은 로그가 찍혀 있습니다.

Apr 21 22:27:48 testnix systemd[1]: Started testd.dll running on Unix 5.8.0.48.
Apr 21 22:27:48 testnix dotnet-testd[758407]: [testd] Starting service

그리고 서비스 중지(systemctl kill)를 하면 이렇게 로그가 남고!

Apr 21 22:28:30 testnix dotnet-testd[758407]: [testd] Stopping service
Apr 21 22:28:30 testnix dotnet-testd[758407]: [testd] Background task gracefully stopped
Apr 21 22:28:30 testnix dotnet-testd[758407]: [testd] Service stopped
Apr 21 22:28:30 testnix systemd[1]: dotnet-testd.service: Succeeded.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




그나저나, 제가 이 글을 쓴 이유는 ".NET Core 콘솔 프로젝트에서 Kestrel 호스팅 방법" 글에 달린 덧글 때문입니다. ^^;

현재 .NET 5로 해당 프로그램을 만들면 Ctrl + C에 대해 잘 반응을 하지만 daemon으로 등록해 두면 systemctl stop(SIGINT)에 대해 반응하지 않고 곧바로 프로세스가 종료됩니다. 종료가 된다는 것은 다행이지만 Console.CancelKeyPress 이벤트 핸들러가 실행되지 않으므로 아쉽게도 프로세스 종료 시 수행해야 할 특정 작업이 있다면 더 이상 실행이 되지 않습니다.

그래서 혹시나 마이크로소프트 측에서 만든 서비스 관련 코드라면 이에 대한 반응을 준비하지 않았나 싶어 Generic Host를 이용해 다시 한번 동일한 daemon 예제 코드를 작성해 본 것인데요, 마찬가지로 "systemctl stop"에는 반응하지 않았습니다. (즉,"Background task gracefully stopped" 등의 로그가 남지 않습니다.)

혹시 이 원인에 대해 리눅스 환경 및 닷넷 코어를 잘 아시는 분은 덧글 부탁드립니다. ^^




2021-04-22 업데이트: 덧글에 주신 의견에 따라, 서비스 등록 시 기존의 KillSignal=SIGINT를 제외하고 KillMode=mixed를 추가하면 systemctl stop/kill에 대해 SIGTERM 신호를 받을 수 있어 ProcessExit 이벤트가 실행됩니다. (당분간이라고 해야 할지 모르겠지만) 일단은 이런 방법으로 stop/kill에 대해 수행할 코드가 있다면 대처하시면 되겠습니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/26/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-04-21 11시12분
아래의 글은 Generic Host와 docker 환경에서의 종료 관계를 설명하고 있습니다.

Graceful Shutdown C# Apps
; https://medium.com/@rainer_8955/gracefully-shutdown-c-apps-2e9711215f6d
정성태
2021-04-22 11시12분
[----] 글의 아래 부분이 잘못된 내용이라 댓글 남깁니다.

> [서비스 중지-1 SIGINT]
> sudo systemctl stop dotnet-testd

> [서비스 중지-2 SIGTERM]
> sudo systemctl kill dotnet-testd

https://www.freedesktop.org/software/systemd/man/systemd.kill.html#Options 를 참고했을때,

systemctl 의 기본 KillMode는 control-group입니다. 제가 이해한 바, 이 경우 `systemctl stop`이 실행되었을때 다음이 실행됩니다.

1. ExecStop 에 명시된 명령을 실행
2. 이후 종료되지 않은 프로세스가 있다면 프로세스를 강제 종료

아래 인용에 의해, systemctl 의 KillMode를 mixed로 변경하면 이 글의 문제가 해결될것으로 추측합니다.

> 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

또한 systemctl stop 과 systemctl kill 의 차이는 http://0pointer.de/blog/projects/systemd-for-admins-4.html 의 아래 인용이 잘 설명해주고 있으니 참고하시면 될 것 같습니다.

> How does this relate to systemctl stop? kill goes directly and sends a signal to every process in the group, however stop goes through the official configured way to shut down a service, i.e. invokes the stop command configured with ExecStop= in the service file. Usually stop should be sufficient.
[guest]
2021-04-22 11시22분
[----] 제 댓글 중 오해를 부를 수 있는 문장이 있어 다시 댓글 남깁니다.
> systemctl 의 KillMode를 mixed로 변경하면 이 글의 문제가 해결될것으로 추측합니다.

위는

"dotnet-testd 서비스의 KillMode를 mixed로 변경하면 이 글의 문제가 해결될것으로 추측합니다."

로 수정되야 합니다.
[guest]
2021-04-22 05시21분
의견 정말 감사합니다. 테스트를 해보니, 기존의 dotnet-testd.service 파일에 있던 KillSignal=SIGINT를 지우고 KillMode=mixed를 추가해 ProcessExit 이벤트가 모두 실행이 되는 것을 확인했습니다.

한 가지 의문이 있는데요, 아래와 같이 제가 주석을 달았던 것은,

> [서비스 중지-1 SIGINT]
> sudo systemctl stop dotnet-testd

stop 명령어의 경우 다음의 문서 내용과 함께,

systemd.service — Service unit configuration
; https://www.freedesktop.org/software/systemd/man/systemd.service.html

"
ExecStop =

If this option is not specified, the process is terminated by sending the signal specified in KillSignal= or RestartKillSignal= when service stop is requested.
"

이 글의 원래 시작이었던 daemon 소스 코드를 보면,

C# - .NET Core Console로 리눅스 daemon 프로그램 만드는 방법
; https://www.sysnet.pe.kr/2/0/11958

ExecStop은 비어 있고, KillSignal=SIGINT로 설정했기 때문에 "systemctl stop" 명령은 SIGINT를 보내는 것이 맞습니다. 실제로 동일한 소스 코드를 .NET Core 3.1 이하의 환경에서 실행하면 SIGINT (Ctrl+C)에 반응해 Console.CancelKeyPress 이벤트 핸들러가 잘 실행이 됩니다.

즉, 원칙적으로 보면 KillMode의 mixed/control-group 설정에 관계없이 (.NET Core 3.1 이하에서 그랬듯이) 잘 동작해야 하는 것이 아닌가... 라는 것이 의문입니다.
정성태
2021-04-22 06시38분
[----] > C# - .NET Core Console로 리눅스 daemon 프로그램 만드는 방법
> ; https://www.sysnet.pe.kr/2/0/11958

> 즉, 원칙적으로 보면 KillMode의 mixed/control-group 설정에 관계없이 (.NET Core 3.1 이하에서 그랬듯이) 잘 동작해야 하는 것이 아닌가... 라는 것이 의문입니다.

과연 그렇네요, 제가 "C# - .NET Core Console로 리눅스 daemon 프로그램 만드는 방법" 글을 보지 않아 KillSignal=SIGINT 로 되어 있다는 사실을 몰랐네요. 성태님의 말씀이 옳습니다.

https://github.com/dotnet/runtime/issues/51221#issuecomment-823043104 에 이 글과 유사한 문제제기가 있네요.

> Feels like this should be reverted to 3.1 behavior and focus on this #50527 for signal handling improvements. Using SIGTERM to shutdown currently in .NET Core requires more code and blocking code in process exit in order to let other code run (and can result in deadlocks if done incorrectly).


좋은 글 올려주셔서 늘 감사해하고 있습니다. 감사합니다.
[guest]
2021-04-22 09시24분
저도 감사드립니다. ^^
정성태
2021-05-29 05시54분
아래의 이슈가 해결되었다고 나옵니다.

.NET 5 apps can no longer intercept SIGINT signals (receive CancelKeyPress events) when running under Docker #51221
https://github.com/dotnet/runtime/issues/51221

따라서, 다음 버전의 .NET 5 업그레이드에서는 아마도 이 글에서 다룬 문제가 해결될 것입니다.
정성태
2022-06-30 10시19분
Running .NET Core Applications as a Windows Service
; https://code-maze.com/aspnetcore-running-applications-as-windows-service/

Story about graceful termination with modern .NET
; https://blog.kbegiedza.eu/dotnet-and-story-about-graceful-termination
정성태
2023-02-03 09시01분
A Noob Introduction to Hosted Services in ASP.NET Core
; https://mbarkt3sto.hashnode.dev/a-noob-introduction-to-hosted-services-in-aspnet-core

How to start using .NET Background Services
; https://blog.jetbrains.com/dotnet/2023/05/09/dotnet-background-services/

--------------------

Concurrent Hosted Service in .NET 8 | .NET Conf 2023
; https://youtu.be/sD_-XwauabE
정성태

... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11934정성태6/7/201921177VC++: 133. typedef struct와 타입 전방 선언으로 인한 C2371 오류파일 다운로드1
11933정성태6/7/201919541VC++: 132. enum 정의를 C++11의 enum class로 바꿀 때 유의할 사항파일 다운로드1
11932정성태6/7/201918718오류 유형: 544. C++ - fatal error C1017: invalid integer constant expression파일 다운로드1
11931정성태6/6/201919258개발 환경 구성: 441. C# - CairoSharp/GtkSharp 사용을 위한 프로젝트 구성 방법
11930정성태6/5/201919790.NET Framework: 842. .NET Reflection을 대체할 System.Reflection.Metadata 소개 [1]
11929정성태6/5/201919326.NET Framework: 841. Windows Forms/C# - 클립보드에 RTF 텍스트를 복사 및 확인하는 방법 [1]
11928정성태6/5/201918118오류 유형: 543. PowerShell 확장 설치 시 "Catalog file '[...].cat' is not found in the contents of the module" 오류 발생
11927정성태6/5/201919296스크립트: 15. PowerShell ISE의 스크립트를 복사 후 PPT/Word에 붙여 넣으면 한글이 깨지는 문제 [1]
11926정성태6/4/201919892오류 유형: 542. Visual Studio - pointer to incomplete class type is not allowed
11925정성태6/4/201919699VC++: 131. Visual C++ - uuid 확장 속성과 __uuidof 확장 연산자파일 다운로드1
11924정성태5/30/201921312Math: 57. C# - 해석학적 방법을 이용한 최소 자승법 [1]파일 다운로드1
11923정성태5/30/201920966Math: 56. C# - 그래프 그리기로 알아보는 경사 하강법의 최소/최댓값 구하기파일 다운로드1
11922정성태5/29/201918504.NET Framework: 840. ML.NET 데이터 정규화파일 다운로드1
11921정성태5/28/201924348Math: 55. C# - 다항식을 위한 최소 자승법(Least Squares Method)파일 다운로드1
11920정성태5/28/201916014.NET Framework: 839. C# - PLplot 색상 제어
11919정성태5/27/201920256Math: 54. C# - 최소 자승법의 1차 함수에 대한 매개변수를 단순 for 문으로 구하는 방법 [1]파일 다운로드1
11918정성태5/25/201921124Math: 53. C# - 행렬식을 이용한 최소 자승법(LSM: Least Square Method)파일 다운로드1
11917정성태5/24/201922081Math: 52. MathNet을 이용한 간단한 통계 정보 처리 - 분산/표준편차파일 다운로드1
11916정성태5/24/201919918Math: 51. MathNET + OxyPlot을 이용한 간단한 통계 정보 처리 - Histogram파일 다운로드1
11915정성태5/24/201923044Linux: 11. 리눅스의 환경 변수 관련 함수 정리 - putenv, setenv, unsetenv
11914정성태5/24/201921978Linux: 10. 윈도우의 GetTickCount와 리눅스의 clock_gettime파일 다운로드1
11913정성태5/23/201918749.NET Framework: 838. C# - 숫자형 타입의 bit(2진) 문자열, 16진수 문자열 구하는 방법파일 다운로드1
11912정성태5/23/201918676VS.NET IDE: 137. Visual Studio 2019 버전 16.1부터 리눅스 C/C++ 프로젝트에 추가된 WSL 지원
11911정성태5/23/201917462VS.NET IDE: 136. Visual Studio 2019 - 리눅스 C/C++ 프로젝트에 인텔리센스가 동작하지 않는 경우
11910정성태5/23/201927118Math: 50. C# - MathNet.Numerics의 Matrix(행렬) 연산 [1]파일 다운로드1
11909정성태5/22/201921130.NET Framework: 837. C# - PLplot 사용 예제 [1]파일 다운로드1
... 76  77  78  79  [80]  81  82  83  84  85  86  87  88  89  90  ...