Microsoft MVP성태의 닷넷 이야기
.NET Framework: 815. CER(Constrained Execution Region)이란? [링크 복사], [링크+제목 복사]
조회: 12725
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

CER(Constrained Execution Region)이란?

현재 CER에 대해 가장 잘 설명하고 있는 문서는 무려 2005년에 나온 다음의 글입니다.

2005년 10월 MSDN Magazine
Keep Your Code Running with the Reliability Features of the .NET Framework
; https://learn.microsoft.com/en-us/archive/msdn-magazine/2005/october/using-the-reliability-features-of-the-net-framework

CHM
; http://download.microsoft.com/download/3/a/7/3a7fa450-1f33-41f7-9e6d-3aa95b5a6aea/MSDNMagazineOctober2005en-us.chm

이참에 정리를 한번 해볼까요? ^^

우선 이 기능이 도입된 배경 설명이 나오는데요, CER이 .NET 2.0에 도입될 당시 SQL 서버에 닷넷 CLR을 호스팅하면서 필요해졌다고 합니다. SQL 서버의 특성상 장애를 최소화해야 하고 이를 위해 이전에 회피 불가능한 3가지 예외(OutOfMemoryException, StackOverflowException, ThreadAbortException)에 대한 처리 능력이 필요하게 된 것입니다. (문서에서는 해당 예외들을 Asynchronous exceptions로 지칭합니다.) 가령 StackOverflowException이 .NET 코드에서 발생했다고 해서 SQL 서버 프로세스가 종료되어서는 안 된다는 것입니다.

참고로, 일반적인 .NET Framework 응용 프로그램에서는 저런 처리 능력이 100% 갖춰져 있지는 않습니다. 왜냐하면 CLR 호스팅 시 정책적으로 관련 옵션들을 설정해야 하는데 SQL 서버의 호스팅 환경에서만 저 정책들이 켜져 있기 때문입니다.

일례로, 일반적인 .NET Framework 응용 프로그램에서는 ThreadAbortException이 finally 절을 처리하는 도중에는 발생하지 못합니다. 왜냐하면 thread abort 작업이 gracful한 방식으로 종료하기 때문입니다. 실제로 CER을 사용하지 않고도 다음의 코드는 finally 절이라는 이유만으로 절대 Abort가 발생하지 않으므로 무한 대기 상태에 빠지게 됩니다.

using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(threadFunc);
            t.Start();
            Thread.Sleep(1000);

            {
                Console.WriteLine("Aborting...");
                t.Abort();
                Console.WriteLine("Aborted.");
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }

        private static void threadFunc()
        {
            try { }
            finally
            {
                Thread.Sleep(-1);
            }
        }
    }
}

반면, 위와 같은 상황이 SQL 서버에서 호스팅되면 finally 절임에도 thread abort가 발생할 수 있습니다. 만약 그런 환경에서도 finally 절의 코드가 실행되는 것을 보장받고 싶다면 CER이 되도록 RuntimeHelpers.PrepareConstrainedRegions(); 코드를 사용해야 합니다.




다음으로 문제가 되는 2가지 예외(OutOfMemoryException, StackOverflowException)에 CER의 재미있는 사례를 다음의 코드에서 볼 수 있습니다.

.NET Internals Cookbook Part 2 - GC-related things
; https://blog.adamfurmanek.pl/2019/02/23/net-internals-cookbook-part-2/

예제 코드를,


using System;
using System.Threading;

class Program
{
    static void Main(string[] args)
    {
        var cerThread = new Thread(() =>
        {
            try
            {
                Do();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        });

        cerThread.Start();
        cerThread.Join();
    }

    private static void Do()
    {
        Console.WriteLine("Can you see this message?");
        try
        {
            OutOfMemory();
            Console.WriteLine("Do Something");
        }
        finally
        {
            Console.WriteLine("In finally: " + DateTime.Now);
        }
    }

    static void OutOfMemory()
    {
        Big big;
    }
}

unsafe struct Big
{
    public fixed byte Bytes[int.MaxValue]; // fixed를 썼지만, CER 내에서 계산할 때는 GC Heap을 대상으로 판단
}

실행하면 다음과 같은 결과가 나옵니다.

Can you see this message?
In finally: 2019-03-19 오전 10:45:56
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at Program.OutOfMemory()
   at Program.Do() in c:\cer_jitted\ConsoleApp1\ConsoleApp2\Program.cs:line 30
   at Program.<>c.<Main>b__0_0() in c:\cer_jitted\ConsoleApp1\ConsoleApp2\Program.cs:line 12

일반적으로 우리가 예상할 수 있는 결과입니다. 하지만 이것을 CER 영역에서 실행하면,

private static void DoCER()
{
    Console.WriteLine("Can you see this message?");
    RuntimeHelpers.PrepareConstrainedRegions();
    try
    {
    }
    finally // RuntimeHelpers.PrepareConstrainedRegions + finally는 CER로 처리
    {
        Console.WriteLine("In finally: " + DateTime.Now);
        OutOfMemory();
        Console.WriteLine("Do Something");
    }
}

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
static void OutOfMemory()
{
    Big big;
}

다음과 같은 출력 결과를 보게 됩니다.

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at Program.DoInCER()
   at Program.<>c.<Main>b__0_0() in c:\cer_jitted\ConsoleApp1\ConsoleApp3\Program.cs:line 15

보다시피 finally 내의 Console.WriteLine 코드가 전혀 실행되지 않았습니다. 즉, CLR은 CER 내의 코드를 미리 JIT 컴파일하게 되고 그 와중에 OutOfMemoryException 예외가 미리 발생해 CER 내의 코드가 부분적으로 실행하다 마는 문제를 최소화하는 것입니다.

물론, 이러한 처리가 CLR의 Jitter에 의해 이뤄지는 것이므로 런타임 시에 발생하는 메모리 할당까지 알 수는 없습니다. 가령 코드 내에서 다음과 같은 상황으로 발생하는 OutOfMemoryException은 어쩔 수 없이 코드 실행 중에 발생하게 됩니다.

  • explicit allocations
  • boxing
  • virtual method calls (unless the target of the virtual method call has already been prepared)
  • method calls through reflection
  • use of Monitor.Enter (or the lock keyword in C# and SyncLock in Visual Basic)
  • isinst and castclass instructions on COM objects
  • field access through transparent proxies, serialization, and multidimensional array accesses.

결국 이런 수준의 제약을 만족하는 코드는 복잡할 수 없으므로, 상대적으로 적은 코드의 영역을 대상으로 CER 제약을 가하는 것이 권장됩니다.




코드가 CER 내에서 실행되는 조건은, 다음과 같이 try 바로 직전에 PrepareConstrainedRegions 메서드 호출 코드를 넣은 경우 catch와 finally 절로 제한됩니다.

... // will not be prepared
RuntimeHelpers.PrepareConstrainedRegions();
try 
{
    ... // will not be prepared
} 
/*
catch, fault, and filter blocks will be prepared.
*/
finally
{
    ... // will be prepared. your noninterruptible code here
}
... // will not be prepared

또한 CER 내에서의 중첩 함수 호출은 ReliabilityContract가,

ReliabilityContractAttribute(Consistency, Cer)
; https://learn.microsoft.com/en-us/dotnet/api/system.runtime.constrainedexecution.reliabilitycontractattribute.-ctor?view=netframework-4.7.2

다음의 3가지로 설정되어 있는 경우에만 Jitter의 CER 처리를 받게 됩니다.

[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]

* 지정되지 않은 경우의 기본값이, "Consistency.MayCorruptProcess, Cer.None"이므로 CER 처리 대상에서 제외됨

// Consistency: what kind of state corruption could result from asynchronous exceptions being thrown during the method's execution, 
public enum Consistency
{
    MayCorruptProcess,
    MayCorruptAppDomain,
    MayCorruptInstance,
    WillNotCorruptState
}

// Cer: what kind of completion guarantees the method can make if it were to run in a CER.
[Serializable]
public enum Cer
{
    None,
    MayFail,
    Success
}

/*
A Cer value of MayFail is used to signal that when faced with asynchronous exceptions, 
the code may not complete in an expected fashion. 
Since thread aborts are being delayed over constrained execution regions, 
this really means that your code is doing something that may cause memory to be allocated or that might result in a stack overflow.
*/

따라서 위의 예제 코드에서 OutOfMemory 메서드의 ReliabilityContract를 다른 값으로 바꿔보면 finally 절의 Console.WriteLine이 실행되는 것을 확인할 수 있습니다.




하지만 CER로 지정되었다고 해서 무조건 안정성을 보장받는다고 할 수는 없습니다. 일례로, .NET Framework 응용 프로그램에서는 CER 내에서 StackOverflowException이 발생하면 응용 프로그램이 비정상 종료하게 됩니다. 예를 들어, 위에서 든 예제 코드 중 Big 타입의 Bytes 필드를 다음과 같이 바꾸면,

unsafe struct Big
{
    public fixed byte Bytes[1_048_576];  // fixed를 썼지만, CER 내에서 계산할 때는 GC Heap을 대상으로 판단
                                         // 따라서 CER에 걸리지 않고 실행되므로 (기본값인 경우 스택 메모리의 크기가 1MB라서) StackOverflowException 발생
}

CER을 명시했음에도 일반적인 .NET 응용 프로그램에서는 비정상 종료하게 됩니다. 반면 CLR 호스팅 정책을 바꾼 SQL 서버에서는 비정상 종료를 하지 않는다고 합니다.




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

정리해 보면, .NET Framework 환경에서는 CER을 사용해도 중간 정도의 애매한 안정성을 확보하게 됩니다. 만약 여러분들이 만드는 응용 프로그램이 SQL 서버와 같은 고-안정성을 필요로 한다면 직접 호스팅 코드를 만들어 Asynchronous exceptions 관련 정책들을 설정해야 합니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/1/2022]

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)
13178정성태12/1/20224849Windows: 215. Win32 API 금지된 함수 - IsBadXxxPtr 유의 함수들이 안전하지 않은 이유파일 다운로드1
13177정성태11/30/20225574오류 유형: 829. uwsgi 설치 시 fatal error: Python.h: No such file or directory
13176정성태11/29/20224504오류 유형: 828. gunicorn - ModuleNotFoundError: No module named 'flask'
13175정성태11/29/20226116오류 유형: 827. Python - ImportError: cannot import name 'html5lib' from 'pip._vendor'
13174정성태11/28/20224684.NET Framework: 2073. C# - VMMap처럼 스택 메모리의 reserve/guard/commit 상태 출력파일 다운로드1
13173정성태11/27/20225372.NET Framework: 2072. 닷넷 응용 프로그램의 스레드 스택 크기 변경
13172정성태11/25/20225180.NET Framework: 2071. 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법파일 다운로드1
13171정성태11/25/20224792Windows: 214. 윈도우 - 스레드 스택의 "red zone"
13170정성태11/24/20225100Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20225685Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20224976제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20225018.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20224742개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224644개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225544개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225484개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226568.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20225791.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20225740.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20228945.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225222오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20225878.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20226774.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226279디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/20225752.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/20227036.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...