Microsoft MVP성태의 닷넷 이야기
닷넷: 2274. IIS - (프로세스 종료 없는) AppDomain Recycle [링크 복사], [링크+제목 복사],
조회: 7149
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 7개 있습니다.)
.NET Framework: 174. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법
; https://www.sysnet.pe.kr/2/0/841

.NET Framework: 447. w3wp.exe AppPool 재생(recycle)하는 방법 정리
; https://www.sysnet.pe.kr/2/0/1704

개발 환경 구성: 246. IIS 작업자 프로세스의 20분 자동 재생(Recycle)을 끄는 방법
; https://www.sysnet.pe.kr/2/0/1774

.NET Framework: 643. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/11145

개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
; https://www.sysnet.pe.kr/2/0/13514

닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
; https://www.sysnet.pe.kr/2/0/13516

닷넷: 2274. IIS - (프로세스 종료 없는) AppDomain Recycle
; https://www.sysnet.pe.kr/2/0/13672




IIS - (프로세스 종료 없는) AppDomain Recycle

보통 IIS Recycling은 특정 조건을 만족하면 프로세스(EXE) 자체가 재실행되는 방식으로 이뤄집니다. 그런데, 상황에 따라서는 AppDomain 단위로도 수행이 되는데요,

Application Pool vs Application Domain Recycling in Asp.net?
; https://stackoverflow.com/questions/60105130/application-pool-vs-application-domain-recycling-in-asp-net

대략 다음의 조건에서 그렇다고 하니,

  1. Modification to web.config or Global.asax
  2. Change to the contents of the application's bin directory
  3. Change to the physical path of the virtual directory
  4. Deletion of the subdirectory of the application
  5. The number of re-compilations (aspx, ascx or asax) exceeds the limit specified by the setting in machine.config or web.config (default of 15)

실제로 테스트를 해볼까요? ^^

이를 위해 .NET Framework의 기본 Web Application 프로젝트를 하나 만들고 Global.asax.cs 파일에 다음과 같은 코드를 추가합니다.

using System;
using System.Diagnostics;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;

namespace WebApplication1
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            System.Diagnostics.Trace.WriteLine("===== Global.asax - Application_Start =====");
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        void Application_End(object sender, EventArgs e)
        {
            System.Diagnostics.Trace.WriteLine("===== Global.asax - Application_End =====");
        }
    }
}

이후, IIS 10이 설치된 Windows Server 2022에서 호스팅하면 최초 페이지 방문 시 다음과 같은 로그가 찍히는 것을 (DebugView를 이용해) 확인할 수 있습니다.

[7696] ===== Global.asax - Application_Start ===== 

그 상태에서 IIS Recycle을 하면 End 메시지가 뜨고,

[7696] ===== Global.asax - Application_End ===== 

다시 웹 페이지를 방문하면 Process ID가 바뀐 Start 로그가 나옵니다.

[7932] ===== Global.asax - Application_Start ===== 




자, 그럼 첫 번째 항목(Modification to web.config or Global.asax)을 테스트해 볼까요? ^^

우선 web.config에서 적당한 내용을 수정해 볼 텐데요, 음... Antlr3.Runtime의 oldVersion을 0.0.0.0에서 1.0.0.0으로 바꾸고 저장해 봅니다.

...[생략]...
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="1.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      ...[생략]...
    </assemblyBinding>
  </runtime>
...[생략]...

저장하는 동시에, 디버그 화면에는 End 메시지가 뜨고, 웹 페이지를 방문하면 Process ID가 바뀌지 않은 채로 Start 메시지가 찍힙니다.

[7932] ===== Global.asax - Application_End ===== 
[7932] ===== Global.asax - Application_Start ===== 

마찬가지로 Global.asax 파일 역시, 마땅히 수정할 것이 없으니 그냥 공백 문자 하나 추가한 다음 저장하면 역시나 Process ID가 바뀌지 않는 Recycle이 발생합니다.

[7932] ===== Global.asax - Application_End ===== 
[7932] ===== Global.asax - Application_Start ===== 




그다음 조건은 /bin 디렉터리의 변경입니다. 일례로 "test.txt" 파일을 만들면 그와 동시에 End가 뜨고 웹 페이지를 방문하면 Start가 나옵니다. 역시나 이번에도 Process ID는 그대로입니다.

[7932] ===== Global.asax - Application_End ===== 
[7932] ===== Global.asax - Application_Start ===== 

3번째 조건인 virtual directory의 경로를 바꾸는 것은, 당연히 recycle이 될 테니 넘어가고...

4번째 조건인 subdirectory 삭제는, 현재 Visual Studio에서 빌드한 그대로 IIS에 올렸으니, /obj/Debug 디렉터리를 삭제해 보면 될 텐데요, 음... Recycle 메시지가 안 나옵니다. /obj 디렉터리를 삭제해도 마찬가지고, 임의로 /test 디렉터를 만들고 삭제해도 아무런 변화가 없습니다.

사용하지 않는 App_Data, App_Start, Properties 디렉터리를 삭제해도 마찬가지인데, 각종 css, map 파일을 가지고 있던 "Content" 디렉터리나 "Scripts\WebForms\MSAjax" 디렉터리를 삭제했더니 Recycle이 발생했습니다. 아마도, 사용 중인 자원을 담은 디렉터리가 없어지면 Recycle이 발생하는 것으로 보입니다.

마지막 조건의 경우, numRecompilesBeforeAppRestart를 초과하는 aspx, ascx, asax 파일에 대한 수정으로 (기본 값이 15회라고 알려진) 재컴파일 횟수가 넘어가면 Recycle이 발생한다는 건데요, 테스트를 위해 "d.aspx"라는 파일을 추가한 다음, 메모장으로 열어 아무 내용이나 넣고 15번을 수정하면 Recycle이 발생합니다.

이때 중요한 것은, 내용만 바꿔서 저장하는 것뿐만 아니라, 그 바뀐 내용을 ASP.NET 엔진이 컴파일할 수 있도록 요청해야 한다는 점입니다. 그랬을 때에만 14번째 요청 후, 15번째 파일 내용을 변경해 저장하는 순간 Recycle이 발생합니다.




참고로, Application Pool에 설정할 수 있는 "Generate Recycle Event Log Entry"의 경우,

iis_apppool_recycle_event_log_1.png

AppDomain Recycle 시에는 적용되지 않습니다. 해당 항목을 보더라도,

  • Application Pool Configuration Changed (default: No) - Event is logged when the application pool recycles due to a change in its configuration
  • ISAPI Reported Unhealthy (default: No) - Event is logged because an ISAPI extension has reported itself as unhealthy
  • Manual Recycle (default: No) - Event is logged when the application pool has been manually recycled
  • Private Memory Limit Exceeded (default: Yes) - Event is logged when the application pool recycles after exceeding its private memory limit
  • Regular Time Interval (default: Yes) - Event is logged when the application pool recycles on its scheduled interval
  • Request Limit Exceeded (default: Yes) - Event is logged when the application pool recycles after exceeding its request limit
  • Specific Time (default: Yes) - Event is logged when the application pool recycles at a scheduled time
  • Virtual Memory Limit Exceeded (default: Yes) - Event is logged when the application pool recycles after exceeding its virtual memory limits

AppDomain Recycle의 조건에 해당하는 것이 없습니다. 즉, 이번 글에서 테스트한 Recycle의 경우에는 이벤트 로그에 전혀 남지 않습니다.

해당 원인을 알고 싶다면, 예전에 설명한 대로,

작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/11145#code

Application_End에 HttpRuntime 인스턴스의 Reflection을 통해 _shutDownMessage를 가져오면 됩니다. 오랜만에 .NET Framework 4.8 환경에서 테스트했더니 여전히 해당 소스코드는 잘 동작합니다. ^^

약간 callstack의 깊이는 달라졌지만 web.config을 변경하는 경우 다음과 같은 메시지를 가져올 수 있고,

_shutDownMessage=CONFIG change 
HostingEnvironment initiated shutdown 
HostingEnvironment caused shutdown 
 
_shutDownStack=   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) 
   at System.Environment.get_StackTrace() 
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal() 
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand() 
   at System.Web.HttpRuntime.ShutdownAppDomain(String stackTrace) 
   at System.Web.Configuration.HttpConfigurationSystem.OnConfigurationChanged(Object sender, InternalConfigEventArgs e) 
   at System.Configuration.Internal.InternalConfigRoot.OnConfigChanged(InternalConfigEventArgs e) 
   at System.Configuration.BaseConfigurationRecord.OnStreamChanged(String streamname) 
   at System.Web.DirectoryMonitor.FireNotifications() 
   at System.Web.Util.WorkItem.CallCallbackWithAssert(WorkItemCallback callback) 
   at System.Web.Util.WorkItem.OnQueueUserWorkItemCompletion(Object state) 
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() 
   at System.Threading.ThreadPoolWorkQueue.Dispatch() 

또는, web.config의 numRecompilesBeforeAppRestart 옵션을 3으로 설정한 다음,

<compilation debug="true" targetFramework="4.8" numRecompilesBeforeAppRestart="3" />

aspx 파일을 3번 수정해 발생한 Recycle에서는 이런 메시지가 나옵니다.

_shutDownMessage=Recompilation limit of 3 reached 
HostingEnvironment initiated shutdown 
HostingEnvironment caused shutdown 
 
_shutDownStack=   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) 
   at System.Environment.get_StackTrace() 
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal() 
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand() 
   at System.Web.HttpRuntime.ShutdownAppDomain(String stackTrace) 
   at System.Web.Compilation.DiskBuildResultCache.ShutdownCallBack(Object state) 
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() 
   at System.Threading.ThreadPoolWorkQueue.Dispatch() 

물론, 코드를 좀 더 추가해 EventLog.WriteEntry를 호출한다면 얼마든지 EventLog에도 로그를 남길 수 있습니다.




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







[최초 등록일: ]
[최종 수정일: 8/6/2024]

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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
13237정성태1/30/202314282.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/202313038개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/202312519개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/202314919개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/202316124오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/202312030스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/202311248오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/202312015개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/202313883.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/202314430.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/202313325개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/202312306.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/202311631개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/202312131Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/202312061오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/202311908개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/202312106Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/202311749오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/202311388Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/202311264VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/202311981디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/202311900디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/202314911Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/202313785.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/202312168오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/202313550기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...