使用dotnet-monitor sidecar模式 dump docker运行的dotnet程序.

前情概要

随着容器和云技术的发展, 大量的应用运行在云上的容器中, 它们的好处是毋庸置疑的, 例如极大的提高了我们的研发部署速度, 快速的扩缩容等等, 但是也存在一些小小的问题, 例如难以调试.
基于VM的部署我们可以通过安全的方式登录到主机上做一些你想做的事情, 但是云上的容器那就是不太方便了(目前AWS的ECS已经有类似docker exec的方式直接进入容器中了, 其他的云未作了解).
但是就算能进入容器也不意味着调试就好做了, 通常来说使用的镜像都是经过优化和精简的(如果要调式可能需要安装大量的组件).

所以, 接下来介绍一下使用dotnet-monitor 来内存转储(memory dump)运行在容器中的 dotnet 程序.

需要提前知晓的一些知识点

什么是 dotnet-monitor?

Announcing dotnet monitor in .NET 6 官方博客的原文:

Running a .NET application in diverse environments can make collecting diagnostics artifacts (e.g., logs, traces, process dumps) challenging. dotnet monitor is a tool that provides an unified way to collect these diagnostic artifacts regardless of whether running you’re running on your desktop machine or in a kubernetes cluster.

There are two different mechanisms for collection of these diagnostic artifacts:

An HTTP API for on demand collection of artifacts. You can call these API endpoints when you already know your application is experiencing an issue and you are interested in gathering more information.
Triggers for rule-based configuration for always-on collection of artifacts. You may configure rules to collect diagnostic artifacts when a desired condition is met, for example, collect a process dump when you have sustained high CPU.

google翻译:

在不同的环境中运行 .NET 应用程序会使收集诊断工件(例如,日志、跟踪、进程转储)具有挑战性。dotnet monitor是一个工具,它提供了一种统一的方式来收集这些诊断工件,无论您是在台式机上运行还是在 kubernetes 集群中运行。

收集这些诊断工件有两种不同的机制:

用于按需收集工件的HTTP API 。当您已经知道您的应用程序遇到问题并且您有兴趣收集更多信息时,您可以调用这些 API 端点。
基于规则的配置触发器,用于始终在线收集工件。您可以配置规则以在满足所需条件时收集诊断工件,例如,当您持续使用高 CPU 时收集进程转储。

dotnet-monitor工作在什么位置?

借用官方博客中的一张图说明一下dotnet-monitor工作在什么地方

dotnet-monitor是如何能对我们的目标程序进行操作的?

dotnet-monitor 可以连接到dotnet运行时公开的一个诊断端口(diagnostic port)(3.0新提供的新功能), 并通过自定义协议(ipc protocol)与运行时交互,

更多调试知识和工具例如ETW, eventpipe, lldb, dotnet-trace, dotent-counters 等可以查看 dotnet diagnostics.

目标应用程序容器准备

首先, 我们得让我们被调试的目标程序公开这个诊断端口, 因为默认情况下这个诊断端口只能由运行这个程序的用户或者root用户来访问, 显然sidecar 模式启动的dotnet-monitor是不可能和目标程序用的是同一个用户的.

未作特别声明的话, 后文给出的实验都是基于AWS FargateLinux 配置.

#添加环境变量
DOTNET_DiagnosticPorts=/my_diagnostic_volume/diag.sock,suspend,connect

/my_diagnostic_volume/diag.sockUnix Domain Socket 文件路径, my_diagnostic_volume 是挂载的一个volume.
suspend 意思是让运行时等待dotnet-monitor 连接进来之后在执行托管代码.
connect 接受dotnet-monitor连接, 详细解释看这里diagnostic ports
上述配置的完整语法结构是 address[,(listen|connect)][,(suspend|nosuspend)]
详情请查看文档configure additional diagnostic ports

如果我们的需要dump内存文件, 可能会遇到WriteDumpAsync failed - HRESULT: 0x00000000 issues 1783这样的错误, 是因为权限问题.
比如我在AWS Fargate中遇到的就是 /dump API 返回400错误 Write dump failed - HRESULT: 0x00000000, 目标程序输出日志 ptrace(ATTACH, 1) FAILED Operation not permitted.
解决这个需要吧SYS_PTRACE权限给到目标程序. AWS Fargate 是编辑任务定义的json文件增加这一部分, docker 启动是通过增加--cap-add=SYS_PTRACE 参数.

{
    "linuxParameters": {
        "capabilities": {
            "add": [
                "SYS_PTRACE"
            ]
        }
    }
}

最后, 配置目标程序容器依赖dotnet-monitor容器, 这样可以先让dotnet-monitor容器启动后, 在启动目标程序容器.
到此, 目标程序容器的配置就完成了, 接下来配置dotnet-monitor

dotnet-monitor容器准备

  • 增加 Docker image 作为目标容器的sidecar 容器.
  • 暴露端口52323 #dotnet-monitor映射端口.
  • 增加容器启动命令参数 --no-auth # 简单粗暴的让所有的API都不要鉴权.
  • 添加环境变量
    • DOTNETMONITOR_DiagnosticPort__ConnectionMode=Listen # 必须的.
    • DOTNETMONITOR_DiagnosticPort__EndpointName=/my_diagnostic_volume/diag.sock # 目标容器配置的DOTNET_DiagnosticPorts中的address.
    • DOTNETMONITOR_Storage__DumpTempFolder=/my_diagnostic_volume/dump_files # dump内存是用的目录.
    • DOTNETMONITOR_Urls=//+:52323 # dotnet-monitor要提供服务在什么端口上. dotnet-monitor默认用的就是52323.

详细的文档解释看这里

至此, 所有的配置就都完成了.

使用dotnet-monitor 来dump目标容器的内存文件

Get 请求 /dump endpoint 即可下载内存转储文件.

wget ip:52323/dump -O my_target_application_memory_dump.dmp

当前可以用API’s列表, 详情请看这里API’s

| Route            | Description                                                        | Version Introduced |
| ---------------- | ------------------------------------------------------------------ | ------------------ |
| /processes       | Gets detailed information about discoverable processes.            | 6.0                |
| /dump            | Captures managed dumps of processes without using a debugger.      | 6.0                |
| /gcdump          | Captures GC dumps of processes.                                    | 6.0                |
| /trace           | Captures traces of processes without using a profiler.             | 6.0                |
| /metrics         | Captures metrics of a process in the Prometheus exposition format. | 6.0                |
| /livemetrics     | Captures live metrics of a process.                                | 6.0                |
| /stacks          | [Experimental] Gets the current callstacks of all .NET threads.    | 7.0                |
| /logs            | Captures logs of processes.                                        | 6.0                |
| /info            | Gets info about dotnet monitor.                                    | 6.0                |
| /operations      | Gets egress operation status or cancels operations.                | 6.0                |
| /collectionrules | Gets the current state of collection rules.                        | 6.3                |

在之后的对内存文件的分析可以使用dotnet-dump, lldb等程序.
更多高级用法请查看, 例如可以配置内存每增加100Mb就触发dump内存文件.

相关链接

//learn.microsoft.com/zh-cn/dotnet/core/diagnostics/dotnet-monitor
//learn.microsoft.com/zh-cn/dotnet/core/diagnostics/dotnet-dump
//learn.microsoft.com/zh-cn/dotnet/core/diagnostics/diagnostic-port
//github.com/dotnet/dotnet-monitor/blob/main/README.md
//devblogs.microsoft.com/dotnet/announcing-dotnet-monitor-in-net-6/