经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Docker » 查看文章
Docker 中的 .NET 异常了怎么抓 Dump
来源:cnblogs  作者:一线码农  时间:2023/6/28 8:50:44  对本文有异议

一:背景

1. 讲故事

有很多朋友跟我说,在 Windows 上看过你文章知道了怎么抓 Crash, CPU爆高,内存暴涨 等各种Dump,为什么你没有写在 Docker 中如何抓的相关文章呢?瞧不上吗?

哈哈,在DUMP的分析旅程中,跑在 Docker 中的 .NET 占比真的不多,大概10个dump有 1-2 个是 docker 中的,市场决定了我的研究方向,为了弥补这一块的空洞,决定写一篇文章来分享下这三大异常下的捕获吧。

二:Docker 下的三大异常捕获

1. crash dump 捕获

前不久我写了一篇 Linux 上的 .NET 崩溃了怎么抓 Dump (https://www.cnblogs.com/huangxincheng/p/17440153.html) 的文章,使用了微软推荐的环境变量方式,其实这在 Docker 中是一样适用的。

为了让 webapi 崩溃退出,我故意造一个栈溢出异常,参考代码如下:

  1. public class Program
  2. {
  3. public static void Main(string[] args)
  4. {
  5. var builder = WebApplication.CreateBuilder(args);
  6. builder.Services.AddAuthorization();
  7. var app = builder.Build();
  8. app.UseAuthorization();
  9. //1. crash
  10. Task.Factory.StartNew(() =>
  11. {
  12. Test("a");
  13. });
  14. app.Run();
  15. }
  16. public static string Test(string a)
  17. {
  18. return Test("a" + a.Length);
  19. }
  20. }

有了代码之后,接下来写一个 Dockerfile,主要就是把三个环境变量塞进去。

  1. FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtime
  2. WORKDIR /app
  3. COPY ./ ./
  4. # 1. 使用中科大镜像源
  5. RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list
  6. ENV COMPlus_DbgMiniDumpType 4
  7. ENV COMPlus_DbgMiniDumpName /dumps/%p-%e-%h-%t.dmp
  8. ENV COMPlus_DbgEnableMiniDump 1
  9. ENTRYPOINT ["dotnet", "AspNetWebApi.dll"]

这里有一个细节,为了能够让 Docker 中的 webapi 能够访问到,将 localhost 设置为 * ,修改 appsettings.json 如下:

  1. {
  2. "urls": "http://*:5001",
  3. "Logging": {
  4. "LogLevel": {
  5. "Default": "Information",
  6. "Microsoft.AspNetCore": "Warning"
  7. }
  8. },
  9. "AllowedHosts": "*"
  10. }

有了这些基础最后就是 docker build & docker run 啦。

  1. [root@localhost data]# docker build -t aspnetapp .
  2. [+] Building 0.3s (9/9) FINISHED
  3. => [internal] load build definition from Dockerfile 0.0s
  4. => => transferring dockerfile: 447B 0.0s
  5. => [internal] load .dockerignore 0.0s
  6. => => transferring context: 2B 0.0s
  7. => [internal] load metadata for mcr.microsoft.com/dotnet/aspnet:6.0 0.3s
  8. => [1/4] FROM mcr.microsoft.com/dotnet/aspnet:6.0@sha256:a2a04325fdb2a871e964c89318921f82f6435b54 0.0s
  9. => [internal] load build context 0.0s
  10. => => transferring context: 860B 0.0s
  11. => CACHED [2/4] WORKDIR /app 0.0s
  12. => CACHED [3/4] COPY ./ ./ 0.0s
  13. => CACHED [4/4] RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list 0.0s
  14. => exporting to image 0.0s
  15. => => exporting layers 0.0s
  16. => => writing image sha256:be69203995c0e5423b2af913549e618d7ee8306fff3961118ff403b1359ae571 0.0s
  17. => => naming to docker.io/library/aspnetapp 0.0s
  18. [root@localhost data]# docker run -itd -p 5001:5001 --privileged -v /data2:/dumps --name aspnetcore_sample aspnetapp
  19. ca34c9274d998096f8562cbef3a43a7cbd9aa5ff2923e0f3e702b159e0b2f447
  20. [root@localhost data]# docker ps -a
  21. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  22. ca34c9274d99 aspnetapp "dotnet AspNetWebApi…" 20 seconds ago Exited (139) 9 seconds ago aspnetcore_sample
  23. [root@localhost data]# docker logs ca34c9274d99
  24. ...
  25. at AspNetWebApi.Program.Test(System.String)
  26. at AspNetWebApi.Program.Test(System.String)
  27. at AspNetWebApi.Program.Test(System.String)
  28. at AspNetWebApi.Program.Test(System.String)
  29. at AspNetWebApi.Program+<>c.<Main>b__0_0()
  30. at System.Threading.Tasks.Task.InnerInvoke()
  31. at System.Threading.Tasks.Task+<>c.<.cctor>b__272_0(System.Object)
  32. at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(System.Threading.Thread, System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
  33. at System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef, System.Threading.Thread)
  34. at System.Threading.Tasks.Task.ExecuteEntryUnsafe(System.Threading.Thread)
  35. at System.Threading.ThreadPoolWorkQueue.Dispatch()
  36. at System.Threading.PortableThreadPool+WorkerThread.WorkerThreadStart()
  37. at System.Threading.Thread.StartCallback()
  38. [createdump] Gathering state for process 1 dotnet
  39. [createdump] Crashing thread 0017 signal 6 (0006)
  40. [createdump] Writing full dump to file /dumps/1-dotnet-ca34c9274d99-1687746929.dmp
  41. [createdump] Written 261320704 bytes (63799 pages) to core file
  42. [createdump] Target process is alive
  43. [createdump] Dump successfully written
  44. [root@localhost data2]# cd /data2
  45. [root@localhost data2]# ls -ln
  46. total 255288
  47. -rw-------. 1 0 0 261414912 Jun 26 10:35 1-dotnet-ca34c9274d99-1687746929.dmp

上面的脚本已经写的非常清楚了,这里有几个注意点提一下:

  • --privileged

一定要加上特殊权限,否则生成 dump 的时候会提示无权限。

  • -v /data2:/dumps

防止dump丢失,记得挂载到宿主机目录 或者 共享容器 中。

2. 内存暴涨 dump 捕获

要想对 docker 中的 .NET 程序内存 进行监控,我一直都是极力推荐 procdump,目前最新的是版本是 1.5, github官网地址: https://github.com/Sysinternals/ProcDump-for-Linux 鉴于现在访问 github 太慢,大家可以把 procdump_1.5-16239_amd64.deb 下载到本地,为什么下载它,是因为容器中是 debain 系统。

下载好了之后放到项目中,使用默认代码骨架:

  1. public class Program
  2. {
  3. public static void Main(string[] args)
  4. {
  5. var builder = WebApplication.CreateBuilder(args);
  6. builder.Services.AddAuthorization();
  7. var app = builder.Build();
  8. app.UseAuthorization();
  9. app.Run();
  10. }
  11. }

接下来就是写 dockerfile 了,这里有一个细节,就是如何在 Docker 中开启多进程,这里用 start.sh 脚本的方式开启,参考代码如下:

  1. FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtime
  2. WORKDIR /app
  3. COPY ./ ./
  4. # 1. 使用中科大镜像源
  5. RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list
  6. # 2. 安装 gdb & procdump
  7. RUN apt-get update && apt-get install -y gdb
  8. RUN dpkg -i procdump.deb
  9. RUN echo "#!/bin/bash \nprocdump -m 30 -w dotnet /dumps & \ndotnet \$1 \n" > ./start.sh
  10. RUN chmod +x ./start.sh
  11. ENTRYPOINT ["./start.sh", "AspNetWebApi.dll"]

有了这些设置后,接下来就是 publish 代码用 docker 构建啦,为了方便演示,这里就用 前台模式 开启了哈。

  1. [root@localhost data]# docker build -t aspnetapp .
  2. [+] Building 11.5s (13/13) FINISHED
  3. [root@localhost data]# docker rm -f aspnetcore_sample
  4. aspnetcore_sample
  5. [root@localhost data]# docker run -it --rm -p 5001:5001 --privileged -v /data2:/dumps --name aspnetcore_sample aspnetapp
  6. ProcDump v1.5 - Sysinternals process dump utility
  7. Copyright (C) 2023 Microsoft Corporation. All rights reserved. Licensed under the MIT license.
  8. Mark Russinovich, Mario Hewardt, John Salem, Javid Habibi
  9. Sysinternals - www.sysinternals.com
  10. Monitors one or more processes and writes a core dump file when the processes exceeds the
  11. specified criteria.
  12. [02:57:34 - INFO]: Waiting for processes 'dotnet' to launch
  13. [02:57:34 - INFO]: Press Ctrl-C to end monitoring without terminating the process(es).
  14. Process Name: dotnet
  15. CPU Threshold: n/a
  16. Commit Threshold: >=30 MB
  17. Thread Threshold: n/a
  18. File Descriptor Threshold: n/a
  19. Signal: n/a
  20. Exception monitor Off
  21. Polling Interval (ms): 1000
  22. Threshold (s): 10
  23. Number of Dumps: 1
  24. Output directory: /dumps
  25. [02:57:34 - INFO]: Starting monitor for process dotnet (9)
  26. info: Microsoft.Hosting.Lifetime[14]
  27. Now listening on: http://[::]:5001
  28. info: Microsoft.Hosting.Lifetime[0]
  29. Application started. Press Ctrl+C to shut down.
  30. info: Microsoft.Hosting.Lifetime[0]
  31. Hosting environment: Production
  32. info: Microsoft.Hosting.Lifetime[0]
  33. Content root path: /app/
  34. [02:57:35 - INFO]: Trigger: Commit usage:48MB on process ID: 9
  35. [createdump] Gathering state for process 9 dotnet
  36. [createdump] Writing full dump to file /dumps/dotnet_commit_2023-06-26_02:57:35.9
  37. [createdump] Written 254459904 bytes (62124 pages) to core file
  38. [createdump] Target process is alive
  39. [createdump] Dump successfully written
  40. [02:57:35 - INFO]: Core dump 0 generated: /dumps/dotnet_commit_2023-06-26_02:57:35.9
  41. [02:57:36 - INFO]: Stopping monitors for process: dotnet (9)
  42. [root@localhost data2]# ls -lh
  43. total 243M
  44. -rw-------. 1 root root 243M Jun 26 10:57 dotnet_commit_2023-06-26_02:57:35.9

从脚本信息看,当内存到了 48MB 的时候触发的 dump 生成,也成功的进入了 /dumps 目录中,太棒了。

3. cpu爆高 dump 捕获

抓 cpu 爆高的dump最好的方式就是多抓几个,比如说:当 CPU >20% 连续超过 5s 抓 2个dump,这种方式抓的dump很容易就能找到真凶,为了方便演示,让两个 cpu 直接打满,参考代码如下:

  1. public static void Main(string[] args)
  2. {
  3. var builder = WebApplication.CreateBuilder(args);
  4. builder.Services.AddAuthorization();
  5. var app = builder.Build();
  6. app.UseAuthorization();
  7. //3. cpu
  8. app.MapGet("/cpu", (HttpContext httpContext) =>
  9. {
  10. Task.Factory.StartNew(() => { bool b = true; while (true) { b = !b; } });
  11. Task.Factory.StartNew(() => { bool b = true; while (true) { b = !b; } });
  12. return new WeatherForecast();
  13. });
  14. app.Run();
  15. }

接下来就是修改 dockerfile,因为我的虚拟机是 8 核心,如果两个核心被打满,那应该会占用大概 24% 的 cpu 利用率,所以脚本中就设置 20% 吧。

  1. FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS runtime
  2. WORKDIR /app
  3. COPY ./ ./
  4. # 1. 使用中科大镜像源
  5. RUN sed -i 's/deb.debian.org/mirrors.ustc.edu.cn/g' /etc/apt/sources.list
  6. # 2. 安装 wget
  7. RUN apt-get update && apt-get install -y gdb
  8. RUN dpkg -i procdump.deb
  9. RUN echo "#!/bin/bash \nprocdump -c 20 -n 2 -s 5 -w dotnet /dumps & \ndotnet \$1 \n" > ./start.sh
  10. RUN chmod +x ./start.sh
  11. ENTRYPOINT ["./start.sh", "AspNetWebApi.dll"]

最后就是 docker 构建。

  1. [root@localhost data]# docker build -t aspnetapp .
  2. [+] Building 0.4s (13/13) FINISHED
  3. [root@localhost data]# docker run -it --rm -p 5001:5001 --privileged -v /data2:/dumps --name aspnetcore_sample aspnetapp
  4. ProcDump v1.5 - Sysinternals process dump utility
  5. Copyright (C) 2023 Microsoft Corporation. All rights reserved. Licensed under the MIT license.
  6. Mark Russinovich, Mario Hewardt, John Salem, Javid Habibi
  7. Sysinternals - www.sysinternals.com
  8. Monitors one or more processes and writes a core dump file when the processes exceeds the
  9. specified criteria.
  10. [03:35:56 - INFO]: Waiting for processes 'dotnet' to launch
  11. [03:35:56 - INFO]: Press Ctrl-C to end monitoring without terminating the process(es).
  12. Process Name: dotnet
  13. CPU Threshold: >= 20%
  14. Commit Threshold: n/a
  15. Thread Threshold: n/a
  16. File Descriptor Threshold: n/a
  17. Signal: n/a
  18. Exception monitor Off
  19. Polling Interval (ms): 1000
  20. Threshold (s): 5
  21. Number of Dumps: 2
  22. Output directory: /dumps
  23. [03:35:56 - INFO]: Starting monitor for process dotnet (8)
  24. info: Microsoft.Hosting.Lifetime[14]
  25. Now listening on: http://[::]:5001
  26. info: Microsoft.Hosting.Lifetime[0]
  27. Application started. Press Ctrl+C to shut down.
  28. info: Microsoft.Hosting.Lifetime[0]
  29. Hosting environment: Production
  30. info: Microsoft.Hosting.Lifetime[0]
  31. Content root path: /app/

看输出是正在监控,接下来我们访问下网址: http://192.168.17.129:5001/cpu
稍等片刻之后就会生成两个dump 文件。

三:总结

虽然Docker中的 .NET 程序占比较少,但把经验总结出来还是很值得的,以后有人问怎么抓,可以把这篇文章直接丢过去啦!

图片名称

原文链接:https://www.cnblogs.com/huangxincheng/p/17505313.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号