Microsoft MVP성태의 닷넷 이야기
.NET Framework: 447. w3wp.exe AppPool 재생(recycle)하는 방법 정리 [링크 복사], [링크+제목 복사],
조회: 15531
글쓴 사람
정성태 (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)
13333정성태4/28/20233790Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233877Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233922오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233575Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233764Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233446VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233851VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235289.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234589스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234422.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234336개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235130VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233959개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233908개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234367개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234217개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234289오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233590오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233804Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233939개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20234009개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20234025Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234521C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234139C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234285.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234185스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...