Microsoft MVP성태의 닷넷 이야기
.NET Framework: 447. w3wp.exe AppPool 재생(recycle)하는 방법 정리 [링크 복사], [링크+제목 복사],
조회: 15530
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 6개 있습니다.)
.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




w3wp.exe AppPool 재생(recycle)하는 방법 정리

사실 w3wp.exe에 대한 재생 방법은 검색해 보면 많은 글이 나옵니다.

Restarting (Recycling) an Application Pool
; http://stackoverflow.com/questions/249927/restarting-recycling-an-application-pool

IIS 7 이상이라면 간단하게 Microsoft.Web.Administration.dll 어셈블리에서 제공하는 ServerManager 객체를 이용할 수 있습니다.

ServerManager svr = new ServerManager(); 
ApplicationPool appPool = svr.ApplicationPools[appPoolId]; // appPoolId == IIS AppPools에 등록된 Application Pool 이름

if (appPool != null)
{
    appPool.Recycle();
}

하지만 IIS 6 이하에서는 Directory Services를 이용해 처리해야 합니다.

string appPoolPath = "IIS://localhost/W3SVC/AppPools/" + appPool;

using (DirectoryEntry appPoolEntry = new DirectoryEntry(appPoolPath))
{
    appPoolEntry.Invoke("Recycle", null);
    appPoolEntry.Close();
}

위의 방법은 IIS 7이상에서도 잘 동작하지만 한 가지 제약이 있습니다. 다음과 같이 "IIS 6 Management Compatibility" 옵션이 켜져있어야 하는데, 생각보다 이 옵션이 켜져 있는 IIS 7(+) 시스템이 많지 않습니다.

recycle_app_pool_1.png

그래서 안전하게 하고 싶다면 IIS 6과 7을 구분해서 각각의 recycle 명령을 호출하도록 바꿔야 합니다.

public static bool IsVistaOrLater
{
    get { return Environment.OSVersion.Version.Major >= 6; }
}

참고로 "HttpRuntime.UnloadAppDomain();" 메서드가 recycle과 유사한 효과를 내긴 합니다. 하지만 이 메서드는 w3wp.exe에 대한 재생을 하는 것은 아니고 내부의 웹 가상 응용 프로그램에 대한 AppDomain만 내렸다가 다시 올립니다. 말로만 듣던 프로세스(EXE) 내부의 Application Domain 격리 효과를 직접 눈으로 볼 수 있는 몇 안되는 사례입니다.




그런데 ServerManager를 사용하면 한가지 문제가 있습니다. 바로 GAC에 등록된 Microsoft.Web.Administration.dll 어셈블리를 로드하는 방법입니다. 제 컴퓨터에 보니 7.0.0.0 버전과 7.9.0.0 버전이 있는데, 향후 지원을 생각한다면 버전을 고정할 수도 없고... 다소 애매합니다. (사실 쓸데없는 걱정일 수 있습니다. 윈도우 2008부터 2012까지 모두 7.0.0.0 버전이 등록되어 있습니다.)

그래서 제가 찾아봤던 것이 다음의 방법입니다.

Assembly.Load를 이용해 GAC에 등록된 어셈블리를 로드하는 방법
; https://www.sysnet.pe.kr/2/0/1703

이 방법을 이용해서 .NET Reflection과 결합해 다음과 같이 자연스럽게 문제를 해결하는 듯 했습니다. ^^

try
{
    string gacAsmName = GetAssemblyPath("Microsoft.Web.Administration"); // 7.9.0.0 버전의 어셈블리 로드
    Assembly asm = Assembly.LoadFrom(gacAsmName);
    if (asm == null)
    {
        return;
    }

    System.Type targetType = asm.GetType("Microsoft.Web.Administration.ServerManager");
    if (targetType == null)
    {
        return;
    }

    object objValue = Activator.CreateInstance(targetType);
    if (objValue == null)
    {
        return;
    }

    PropertyInfo apProps = targetType.GetProperty("ApplicationPools", BindingFlags.Instance | BindingFlags.Public);
    if (apProps == null)
    {
        return;
    }

    object appPoolColl = apProps.GetValue(objValue, null);

    if (appPoolColl == null)
    {
        return;
    }

    object appPoolElem = null;
    foreach (PropertyInfo prop in appPoolColl.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
    {
        foreach (ParameterInfo propParam in prop.GetIndexParameters())
        {
            if (propParam.ParameterType.FullName == "System.String")
            {
                appPoolElem = prop.GetValue(appPoolColl, new object[] { appPoolId });
                break;
            }
        }
    }

    if (appPoolElem == null)
    {
        return;
    }

    MethodInfo recycleMethod = appPoolElem.GetType().GetMethod("Recycle");
    recycleMethod.Invoke(appPoolElem, null);
}
catch { }

그런데 IIS + ASP.NET에서 실행했더니 다음과 같은 예외가 발생합니다.

System.Reflection.TargetInvocationException was caught
  Message=Exception has been thrown by the target of an invocation.
  Source=mscorlib
  StackTrace:
       at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
       at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)

  InnerException: System.IO.FileNotFoundException
       Message=Filename: redirection.config
Error: Cannot read configuration file

문제 범위를 축소하기 위해 .NET Reflection이 아닌 ServerManager 객체를 곧바로 사용해 보았는데, ApplicationPools 객체를 반환받는 과정에서 오류가 나는 것을 확인했습니다.

ServerManager svr = new ServerManager();

ApplicationPoolCollection apPools = svr.ApplicationPools; // 예외 발생

foreach (var item in appPools)
{
    Console.WriteLine(item.Name);
}

System.IO.FileNotFoundException occurred
  HResult=-2147024894
  Message=Filename: redirection.config
Error: Cannot read configuration file

  Source=""
  StackTrace:
       at Microsoft.Web.Administration.Interop.AppHostWritableAdminManager.GetAdminSection(String bstrSectionName, String bstrSectionPath)
       at Microsoft.Web.Administration.Configuration.GetSectionInternal(ConfigurationSection section, String sectionPath, String locationPath)
  InnerException: 

아니... 뜬금없이 redirection.config 파일을 찾을 수 없다고 나옵니다. 좀 더 문제 범위를 축소하기 위해 IIS + ASP.NET이 아닌 단순 콘솔 프로그램을 만들어 테스트 했는데, 이번에는 문제 없이 잘 동작해서 다음과 같은 출력 결과를 얻었습니다.

Clr4IntegratedAppPool
Clr4ClassicAppPool
Clr2IntegratedAppPool
Clr2ClassicAppPool
UnmanagedClassicAppPool

오호~~~ 그런데 이상하군요. 콘솔에서 잘 동작하는 것은 둘째치고, 출력 결과로 나온 AppPool의 목록이 IIS 서버의 것이 아닌 IIS Express의 것처럼 보였습니다. 확인을 위해 "%USERPROFILE%\My Documents\IISExpress\config\applicationhost.config" 파일을 열고 appPool 목록을 확인하니 일치했습니다.

더욱 재미있는 것은, 7.0.0.0 버전의 Microsoft.Web.Administration.dll 어셈블리를 참조하는 경우 정상적으로 IIS 서버의 것을 가져왔다는 점입니다.

DefaultAppPool
Classic .NET AppPool
.NET v2.0 Classic
.NET v2.0
.NET v4.5 Classic
.NET v4.5

현상을 정리해 보면, 7.9.0.0 버전의 Microsoft.Web.Administration.dll 어셈블리를 IIS에서 직접 호스팅하는 웹 애플리케이션(ASP.NET)의 페이지(.aspx)에서 테스트하면 오류가 발생하고 7.0.0.0 버전의 경우에는 동작을 합니다.

이에 기반해서 검색을 해보니 답이 나오더군요. ^^

Microsoft.Web.Administration.ServerManager looking in wrong directory for IISExpress applicationHost.config
; http://stackoverflow.com/questions/11208270/microsoft-web-administration-servermanager-looking-in-wrong-directory-for-iisexp

아래의 글이 눈에 띄는데요.

How are you trying to get the application pools? Are you using MWH (Microsoft.Web.Administration) APIs?
1.Full IIS ships with Microsoft.Web.Administration.dll (version 7.0.0.0). 
2.IIS Express ships with a different version of Microsoft.Web.Administration.dll (version 7.9.0.0). 

Microsoft.Web.Administration (MWA) version 7.9.0.0 is shipped with IIS Express 7.5 and it is only used by IIS Express. 

한마디로, Microsoft.Web.Administration.dll 어셈블리의 7.0.0.0 버전은 "IIS 서버"를 위한 것이고, 7.9.0.0 버전은 "IIS Express"를 위한 것입니다. 이후에 나온 IIS Express 7.5는 Microsoft.Web.Administration 어셈블리 사용에 대한 동작을 자연스럽게 일치시키기 위해 aspnet.config 파일에 다음과 같이 7.0.0.0을 7.9.0.0으로 사용하도록 bindingRedirect를 지정한다는 설명도 나옵니다.

<dependentAssembly>
  <assemblyIdentity name="Microsoft.Web.Administration"
                    publicKeyToken="31bf3856ad364e35"
                    culture="neutral" />
  <bindingRedirect oldVersion="7.0.0.0"
                   newVersion="7.9.0.0" />
  <codeBase version="7.9.0.0" 
            href="FILE://%FalconBin%/Microsoft.Web.Administration.dll" />
</dependentAssembly>

여기까지 보고 나니 모든 상황이 이해가 되었습니다. 제가 7.9.0.0 버전에 포함된 ServerManager를 테스트했던 웹 사이트는 "Local SYSTEM"에서 구동했기 때문에 "%USERPROFILE%" 경로가 "C:\Windows\system32\config\systemprofile"로 설정되었고, 그 하위의 "\Documents\IISExpress\config" 폴더에서 redirection.config 파일을 찾으니 그와 같은 예외가 발생한 것입니다.

redirection.config 파일은 IIS Express 설정 폴더에는 제공되지만 IIS 서버에는 제공되지 않습니다.

반면, 7.0.0.0은 무조건 IIS 서버를 바라보기 때문에 redirection.config같은 것은 찾지 않으므로 정상 동작하는 것이었고!

결국, 최신 버전의 Microsoft.Web.Administration.dll을 사용하도록 배려한 것이 잘못된 결과를 가져왔습니다. IIS 서버를 위해서는 7.0.0.0 버전으로 고정해서 어셈블리를 사용해야만 하는 제약이 생긴 것입니다. 과연... 마이크로소프트가 향후 이 2가지 기능의 Microsoft.Web.Administration 어셈블리 파일을 어떤 식으로 버전 개정을 해나갈지 기대(?)가 되는군요. ^^





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







[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 




1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13512정성태1/4/20242168개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242193닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242119닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242168오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242215오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242856닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232442닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232972닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232563닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232428Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232543닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232316개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232405디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233080닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232491오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232469Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232411Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232573Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232687닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232365개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232267Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232396개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232174개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232107오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232410개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232225개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...