Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제

전에 쓴 글에,

C# - (.NET Core 2.2부터 가능한) 프로세스 내부에서 CLR ETW 이벤트 수신
; https://www.sysnet.pe.kr/2/0/12474

GCHeapStats_V1, GCHeapStats_V2 이벤트를,

GCHeapStats_V2 Event
; https://learn.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcheapstats_v2-event

받으려고 다음과 같이 소스코드를 작성했습니다.

using System;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;

class Program
{
    static MyEventListener _listener;

    static Program()
    {
        _listener = new MyEventListener(DotnetRuntimeKeyword.GCKEYWORD, 
            new PrimitiveEnum[] { GCEvent.GCHeapStats_V2 });
    }

    static void Main(string[] args)
    {
        Console.WriteLine(Environment.Version);
        Console.WriteLine(System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription); // .NET Core 3.0.0-preview4.19113.15

        Console.WriteLine(Assembly.GetEntryAssembly().GetCustomAttribute<TargetFrameworkAttribute>().FrameworkName);
        Console.WriteLine(Assembly.GetEntryAssembly().GetName().Version);
        Console.WriteLine("In-proc ETW Enabled on .NET Core 2.2 or later");

        while (true)
        {
            string result = Console.ReadLine();

            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        }
    }
}

public enum DotnetRuntimeKeyword : long
{
    GCKEYWORD = 0x01,
}

public enum GCEvent
{
    GCStart_V1 = 1,
    GCEnd_V1 = 2,

    GCHeapStats_V1 = 4,
    GCHeapStats_V2 = 4, // https://learn.microsoft.com/en-us/dotnet/framework/performance/garbage-collection-etw-events#gcheapstats_v2-event

    GCCreateSegment_V1 = 5,
    GCFreeSegment_V1 = 6,
    GCRestartEEBegin_V1 = 7,
    GCRestartEEEnd_V1 = 3,
    GCSuspendEE_V1 = 9,
    GCSuspendEEEnd_V1 = 8,

    GCAllocationTick_V2 = 10,
    GCAllocationTick_V3 = 10,

    GCFinalizersBegin_V1 = 14,
    GCFinalizersEnd_V1 = 13,
    GCCreateConcurrentThread_V1 = 11,
    GCTerminateConcurrentThread_V1 = 12,
}

internal class MyEventListener : EventListener
{
    // https://docs.microsoft.com/en-us/dotnet/framework/performance/clr-etw-keywords-and-levels

    EventSource _eventSource;
    long _filterKeyword;
    int[] _filterEventId;

    public MyEventListener(DotnetRuntimeKeyword filterKeyword, PrimitiveEnum[] filterEventId = null)
    {
        this._filterKeyword = (long)filterKeyword;
        this._filterEventId = filterEventId?.Select((elem) => (int)elem).ToArray();
        this.EventSourceCreated += MyEventListener_EventSourceCreated;
    }

    private void MyEventListener_EventSourceCreated(object sender, EventSourceCreatedEventArgs e)
    {
        if (e.EventSource.Name == "Microsoft-Windows-DotNETRuntime")
        {
            _eventSource = e.EventSource;
            e.EventSource.EventCommandExecuted += EventSource_EventCommandExecuted;
            EnableEvents(e.EventSource, EventLevel.Informational, (EventKeywords)this._filterKeyword);
        }
    }

    private void EventSource_EventCommandExecuted(object sender, EventCommandEventArgs e)
    {
        if (e.Command == EventCommand.Enable)
        {
            // e.DisableEvent((int)ExceptionEvent.ExceptionThrown_V1);
            // e.DisableEvent((int)ExceptionEvent.ExceptionCatchStart);
            // e.DisableEvent((int)ExceptionEvent.ExceptionCatchStop);
            // e.DisableEvent((int)ExceptionEvent.ExceptionFinallyStart);
            // e.DisableEvent((int)ExceptionEvent.ExceptionFinallyStop);
            // e.DisableEvent((int)ExceptionEvent.ExceptionFilterStart);
            // e.DisableEvent((int)ExceptionEvent.ExceptionFilterStop);
            // e.DisableEvent((int)ExceptionEvent.ExceptionThrownStop);

           FilterEventId(_eventSource, e);
        }
    }

    private void FilterEventId(EventSource eventSource, EventCommandEventArgs e)
    {
        Type type = eventSource.GetType();
        FieldInfo fi = type.GetField("m_eventData", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        if (fi != null)
        {
            object objMetadataArray = fi.GetValue(eventSource); // System.Diagnostics.Tracing.EventSource.EventMetadata []
            System.Collections.IEnumerable enumerator = objMetadataArray as System.Collections.IEnumerable;

            foreach (object objItem in enumerator)
            {
                object descriptor = GetDescriptor(objItem);
                if (descriptor == null)
                {
                    continue;
                }

                (long keyword, int eventId) = GetKeywordAndEventId(descriptor);

                if (((long)keyword & this._filterKeyword) == this._filterKeyword)
                {
                    if (_filterEventId?.Contains(eventId) == false)
                    {
                        e.DisableEvent(eventId);
                    }
                }
            }
        }
    }

    private (long, int) GetKeywordAndEventId(object descriptor)
    {
        object keyword = GetPropertyReflect(descriptor, "Keywords");
        object eventValue = GetPropertyReflect(descriptor, "EventId");

        if (keyword == null || eventValue == null)
        {
            return (0, 0);
        }

        return ((long)keyword, (int)eventValue);
    }

    private object GetDescriptor(object objItem)
    {
        return GetFieldReflect(objItem, "Descriptor");
    }

    object GetPropertyReflect(object obj, string propertyName)
    {
        Type type = obj.GetType();
        PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
        if (pi != null)
        {
            return pi.GetValue(obj);
        }

        return null;
    }

    object GetFieldReflect(object obj, string fieldName)
    {
        Type type = obj.GetType();
        FieldInfo fi = type.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance);
        if (fi != null)
        {
            return fi.GetValue(obj);
        }

        return null;
    }

    protected override void OnEventWritten(EventWrittenEventArgs eventData)
    {
        if (((long)eventData.Keywords & _filterKeyword) == _filterKeyword)
        {
            if (eventData.EventId == (int)GCEvent.GCHeapStats_V2)
            {
                Console.WriteLine($"{DateTime.Now}: {eventData.EventName}, {eventData.EventId}");
            }
        }
    }
}

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

위의 경우에는 테스트가 잘 되었는데, 이상하게도 저 MyEventListener 클래스를 .NET Core 2.2 + ASP.NET Core Web Application 환경에서 돌리면 그때부터 GCHeapStats_V2 이벤트가 수신되지 않습니다.

이거저거 살펴본 결과 ^^; (ASP.NET의 경우 설정 파일에 명시하고 있는) 서버 유형의 GC 모드가 동작하는 환경에서는 그런 문제가 발생했습니다. 그래서 위의 예제 코드에 "runtimeconfig.template.json" 파일을 추가해 다음과 같은 설정을 추가하면,

{
    "configProperties": {
        "System.GC.Server": true
    }
}

그 후부터 .NET Core 2.2 런타임에서는 동일한 현상이 재현됩니다. 재미있는 것은, .NET Core 3.0부터는 정상적으로 이벤트가 수신됩니다.

사실 .NET Core 2.2를 이제는 거의 사용하지 않을 것이므로 이제는 그냥 역사 속으로 묻힐 시행 착오에 불과한 이야기가 되는군요. ^^




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







[최초 등록일: ]
[최종 수정일: 10/27/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)
13181정성태12/3/20224767Linux: 54. 리눅스/WSL - hello world 어셈블리 코드 x86/x64 (nasm)
13180정성태12/2/20224945.NET Framework: 2074. C# - 스택 메모리에 대한 여유 공간 확인하는 방법파일 다운로드1
13179정성태12/2/20224366Windows: 216. Windows 11 - 22H2 업데이트 이후 Terminal 대신 cmd 창이 뜨는 경우
13178정성태12/1/20224868Windows: 215. Win32 API 금지된 함수 - IsBadXxxPtr 유의 함수들이 안전하지 않은 이유파일 다운로드1
13177정성태11/30/20225598오류 유형: 829. uwsgi 설치 시 fatal error: Python.h: No such file or directory
13176정성태11/29/20224518오류 유형: 828. gunicorn - ModuleNotFoundError: No module named 'flask'
13175정성태11/29/20226145오류 유형: 827. Python - ImportError: cannot import name 'html5lib' from 'pip._vendor'
13174정성태11/28/20224711.NET Framework: 2073. C# - VMMap처럼 스택 메모리의 reserve/guard/commit 상태 출력파일 다운로드1
13173정성태11/27/20225400.NET Framework: 2072. 닷넷 응용 프로그램의 스레드 스택 크기 변경
13172정성태11/25/20225208.NET Framework: 2071. 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법파일 다운로드1
13171정성태11/25/20224824Windows: 214. 윈도우 - 스레드 스택의 "red zone"
13170정성태11/24/20225137Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20225717Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20225000제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20225036.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20224763개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224669개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225569개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225519개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226588.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20225808.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20225756.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20228975.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225232오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20225900.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20226804.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...