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

container에 실행 중인 Golang 프로세스를 디버깅하는 방법

관련해서는 이미 설명이 잘 나와 있습니다.

Attach to a process in the Docker container
; https://www.jetbrains.com/help/go/attach-to-running-go-processes-with-debugger.html#attach-to-a-process-in-the-docker-container

Attach to a process on a remote machine
; https://www.jetbrains.com/help/go/attach-to-running-go-processes-with-debugger.html#attach-to-a-process-on-a-remote-machine

가만 보니까, Golang에서의 delve 도구가 debugger 기능도 있지만, 닷넷 환경과 비교하면 sos.dll 확장 기능도 갖고 있는 식입니다. 그래서 빠르게 디버깅을 하는 경우라면 위의 링크에서와 같이 GoLand 등의 IDE를 빌리지 않고 그냥 container 내에서 delve 도구를 이용한 진단을 하는 것이 더 간편합니다.

자, 그럼 우선 delve를 container 내에 복사해야 하는데요, 간단하게는 다음과 같이 빌드할 수 있습니다.

go-delve/delve (Installation)
; https://github.com/go-delve/delve/tree/master/Documentation/installation

# pwd
/root

# git clone https://github.com/go-delve/delve
# cd delve
# go install github.com/go-delve/delve/cmd/dlv

그럼 아래의 경로에 설치가 됩니다.

# find / -name dlv 2>/dev/null
/root/delve/cmd/dlv
/root/go/bin/dlv

// wsl
# find / -path /mnt -prune -o -name dlv 2>/dev/null

이후부터는, dlv를 이용해 현재 실행 중인 Go 프로세스를 연결해,

Golang: debugging a running process
; https://joonas.fi/today-i-learned/2022/golang-debugging-a-running-process/

go-delve/delve
  - Configuration and Command History
; https://github.com/go-delve/delve/blob/master/Documentation/cli/README.md

디버깅할 수 있습니다. 대상이 되는 프로세스의 PID를 먼저 알아내고,

// apt-get install -y procps

# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
...[생략]...
root       139     1  2 Jul21 ?        02:47:00 /usr/local/...생략].../test_go
root     12816     0  0 02:34 pts/0    00:00:00 bash
root     23870 12816  0 05:13 pts/0    00:00:00 ps -ef

연결한 다음,

# dlv attach 139
Type 'help' for list of commands.
(dlv) 

dlv가 지원하는 명령어를 이용해 필요한 정보를 얻어내면 됩니다. 가령, 현재 실행 중인 모든 go routine을 이렇게 열거할 수 있습니다.

// 만약 go routine들의 호출 스택을 함께 얻고 싶다면: "goroutines -t"

(dlv) goroutines
  Goroutine 1 - User: /usr/local/go/src/net/fd_unix.go:173 net.(*netFD).accept (0x4dc195) [IO wait 456216h2m14.227784133s]
  Goroutine 2 - User: /usr/local/go/src/runtime/proc.go:367 runtime.gopark (0x436f36) [force gc (idle) 456216h2m14.227809372s]
  Goroutine 3 - User: /usr/local/go/src/runtime/proc.go:367 runtime.gopark (0x436f36) [GC sweep wait]
  Goroutine 4 - User: /usr/local/go/src/runtime/proc.go:367 runtime.gopark (0x436f36) [GC scavenge wait]
  Goroutine 5 - User: /app/testapp/main.go:24 main.main.func1 (0x55239f) [chan receive 456216h2m14.227837918s]
  Goroutine 6 - User: /usr/local/go/src/runtime/time.go:193 time.Sleep (0x4608ee) [sleep]
  Goroutine 8 - User: /usr/local/go/src/net/fd_posix.go:56 net.(*netFD).Read (0x4db089) [IO wait]
  Goroutine 18 - User: /usr/local/go/src/runtime/proc.go:367 runtime.gopark (0x436f36) [finalizer wait]
  Goroutine 19 - User: /usr/local/go/src/runtime/proc.go:367 runtime.gopark (0x436f36) [select 456216h2m14.227877433s]
  Goroutine 20 - User: /usr/local/go/src/runtime/sigqueue.go:169 os/signal.signal_recv (0x4604d8) (thread 111)
  Goroutine 25 - User: /usr/local/go/src/net/fd_posix.go:56 net.(*netFD).Read (0x4db089) [IO wait]
  Goroutine 166 - User: /usr/local/go/src/runtime/proc.go:367 runtime.gopark (0x436f36) [GC worker (idle) 456216h2m14.227913564s]
...[생략]...
  Goroutine 330 - User: /usr/local/go/src/runtime/proc.go:367 runtime.gopark (0x436f36) [GC worker (idle)]
[51 goroutines]

이후 특정 go routine을 선택하거나,
(dlv) goroutine 6
Switched from 0 to 6 (thread 1054)

혹은 그것의 호출 스택을 확인하는 것도 가능합니다.

(dlv) goroutine 6 stack
0  0x0000000000436f36 in runtime.gopark
   at /usr/local/go/src/runtime/proc.go:367
1  0x00000000004608ee in time.Sleep
   at /usr/local/go/src/runtime/time.go:193
2  0x000000000054a8dc in testapp/testapp.myfunc
   at /app/testapp/network_manager.go:118
3  0x000000000054e6b2 in testapp/testapp.mymain·dwrap·1
   at /app/testapp/mymain.go:58
4  0x0000000000463a61 in runtime.goexit
   at /usr/local/go/src/runtime/asm_amd64.s:1581

프로그램을 계속 진행하려면, continue 명령을 사용하고, 다시 디버그 모드로 진입하려면 Ctrl+C 키를 누릅니다.

(dlv) continue

// Ctrl + C 

received SIGINT, stopping process (will not forward signal)
> runtime.futex() /usr/local/go/src/runtime/sys_linux_amd64.s:520 (PC: 0x465823)
Warning: debugging optimized function
   515:         CMPQ    AX, $0xfffffffffffff001
   516:         JLS     2(PC)
   517:         MOVL    $0xf1, 0xf1  // crash
   518:         RET
   519:
=> 520: // Call the function stored in _cgo_munmap using the GCC calling convention.
   521: // This must be called on the system stack.
   522: TEXT runtime·callCgoMunmap(SB),NOSPLIT,$16-16
   523:         MOVQ    addr+0(FP), DI
   524:         MOVQ    n+8(FP), SI
   525:         MOVQ    _cgo_munmap(SB), AX
(dlv) 

대충 감이 오시죠? ^^




그런데, 문제는 container 환경에서는 기본적으로 attach 권한이 없다는 점입니다. 그래서 이런 오류가 발생하는데요,

# dlv attach 139
Could not attach to pid 139: this could be caused by a kernel security setting, try writing "0" to /proc/sys/kernel/yama/ptrace_scope

검색해 보면,

after upgrade gdb won't attach to process
; https://askubuntu.com/questions/41629/after-upgrade-gdb-wont-attach-to-process

Could not attach to pid:#### this could be caused by a kernel security setting, try writing "0" to /proc/sys/kernel/yama/ptrace_scope
; https://github.com/microsoft/vscode-go/issues/3098

ptrace_scope의 값을 바꾸면 해결할 수 있다고 하는데,

# echo 0 | tee /proc/sys/kernel/yama/ptrace_scope
tee: /proc/sys/kernel/yama/ptrace_scope: Read-only file system
0

저렇게 "Read-only file system"이라는 오류 메시지와 함께 설정이 안 됩니다. 왜냐하면 container 환경 자체가 권한이 부족한 체로 실행되는데 이를 위해 run 단계에서부터 --privileged 옵션을 줘야 합니다.

$ docker run --privileged -ti b5eddc1a9465 /bin/bash

간혹 "docker exec" 시에 줘도 되는 것처럼 답변하는 것들이 있는데 소용없습니다. "run" 단계에서부터 적용돼 있어야 합니다.




그래서, docker run 단계에서 신경 쓰지 않았다면 dlv를 이용해 디버깅을 할 수 없습니다. 만약, 특정 버그가 자주 발생하는 거라면 상관없겠지만 어쩌다 발생하는 거라면 container를 다시 실행해봐야 한다는 것이 아쉬울 수 있는데요, 다행히 "Golang: debugging a running process" 글을 보면 재미있는 팁이 나옵니다.

즉, 그런 경우에도 그냥 container를 다시 시작하지 말고 "kill" 명령을 사용해 프로세스를 종료시키면,

$ kill -QUIT [...pid...]

최소한 해당 프로세스가 실행 중인 "go routines"들의 호출 스택을 "SIGQUIT: quit" 메시지와 함께 stderr 출력을 통해 얻을 수 있습니다.

goroutine 53 [running]:
SIGQUIT: quit
PC=0x465821 m=0 sigcode=0

goroutine 0 [idle]:
runtime.futex()
        /usr/local/go/src/runtime/sys_linux_amd64.s:519 +0x21
runtime.futexsleep(0x7fff2b570cf0, 0x442fd3, 0xc00002f800)
        /usr/local/go/src/runtime/os_linux.go:44 +0x36
runtime.notesleep(0x6ce730)
        /usr/local/go/src/runtime/lock_futex.go:160 +0x87
runtime.mPark()
        /usr/local/go/src/runtime/proc.go:1441 +0x2a
runtime.stoplockedm()
        /usr/local/go/src/runtime/proc.go:2602 +0x65
runtime.schedule()
        /usr/local/go/src/runtime/proc.go:3299 +0x3d
runtime.park_m(0xc000187040)
        /usr/local/go/src/runtime/proc.go:3516 +0x14d
runtime.mcall()
        /usr/local/go/src/runtime/asm_amd64.s:307 +0x43

goroutine 1 [IO wait, 1624 minutes]:
...[생략]...

goroutine 34 [syscall, 1624 minutes]:
...[생략]...

goroutine 53 [IO wait]:
internal/poll.runtime_pollWait(0x7fe654115dd0, 0x72)
        /usr/local/go/src/runtime/netpoll.go:234 +0x89
internal/poll.(*pollDesc).wait(0xc000268180, 0xc00027e000, 0x0)
        /usr/local/go/src/internal/poll/fd_poll_runtime.go:84 +0x32
internal/poll.(*pollDesc).waitRead(...)
        /usr/local/go/src/internal/poll/fd_poll_runtime.go:89
internal/poll.(*FD).Read(0xc000268180, {0xc00027e000, 0x1000, 0x1000})
        /usr/local/go/src/internal/poll/fd_unix.go:167 +0x25a
net.(*netFD).Read(0xc000268180, {0xc00027e000, 0x40e234, 0x13})
        /usr/local/go/src/net/fd_posix.go:56 +0x29
net.(*conn).Read(0xc00021c0b0, {0xc00027e000, 0x7fe67b5e3108, 0x18})
        /usr/local/go/src/net/net.go:183 +0x45
bufio.(*Reader).fill(0xc000208420)
        /usr/local/go/src/bufio/bufio.go:101 +0x103
bufio.(*Reader).ReadByte(0xc000208420)
        /usr/local/go/src/bufio/bufio.go:253 +0x2c
...[생략]...

goroutine 1448716 [IO wait]:
...[생략]...

goroutine 1448561 [sleep]:
...[생략]...

rax    0xca
rbx    0x0
rcx    0x465823
rdx    0x0
rdi    0x6ce730
rsi    0x80
rbp    0x7fff2b570cc0
rsp    0x7fff2b570c78
r8     0x0
r9     0x0
r10    0x0
r11    0x286
r12    0x43d5c0
r13    0x0
r14    0x6ce200
r15    0x7fe654ac2403
rip    0x465821
rflags 0x286
cs     0x33
fs     0x0
gs     0x0

"Golang: debugging a running process" 글에서는 stderr에 대한 출력이 어떻게 redirection 되었는지 확인 방법도 나옵니다.

# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 10:57 ?        00:00:00 /bin/bash -c /test
root        52     1  0 10:57 ?        00:00:04 /usr/local/lib/testapp
root       554     0  0 11:11 pts/0    00:00:00 /bin/bash
root       568   554  0 11:11 pts/0    00:00:00 ps -ef

# ls -al /proc/52/fd/2
lrwx------ 1 root root 64 Jul 26 11:11 /proc/52/fd/2 -> /tmp/test.log

해당 Go Process를 "kill -QUIT ..."으로 종료시키면 바로 저곳으로 출력이 되는 것입니다. 게다가 stderr을 /dev/null과 같은 출력으로 우회시킨 경우에도 strace 등의 도구를 이용해 API 수준에서 가로채기를 한 후,

// apt-get install -y strace

# strace -p 52 -s 512 -ewrite 2> /tmp/strace_52.log

다른 shell을 띄워 해당 프로세스를 종료하고 지정한 로그 파일을,

# kill -QUIT 52

# cat /tmp/strace_52.log
strace: Process 52 attached
--- SIGQUIT {si_signo=SIGQUIT, si_code=SI_USER, si_pid=927, si_uid=0} ---
write(2, "SIGQUIT: quit", 13)           = 13
write(2, "\n", 1)                       = 1
write(2, "PC=", 3)                      = 3
write(2, "0x465821", 8)                 = 8
write(2, " m=", 3)                      = 3
write(2, "0", 1)                        = 1
write(2, " sigcode=", 9)                = 9
write(2, "0", 1)                        = 1
write(2, "\n", 1)                       = 1
...[생략]...

API 호출 단위로 확인할 수 있습니다. 출력이 너무 원시적이어서 확인이 좀 어려운데, 이것에 대해 새롭게 포매팅해주는 스크립트를 이용하면,

psobot/format_stacktrace_from_strace.py
; https://gist.github.com/psobot/6814658

import sys
import re

output = sys.stdin.readlines()
r = re.compile(r'write\(2, "(.+?)", \d+\)\s+= \d+')
print "".join([x.replace(r'\n', "\n").replace(r'\t', "\t") for x in sum([r.findall(o) for o in output], [])])

다시 아래와 같은 식의 출력으로 정제할 수 있습니다.

SIGQUIT: quit
PC=0x464ce1 m=0 sigcode=0

goroutine 0 [idle]:
runtime.futex()
    /usr/local/go/src/runtime/sys_linux_amd64.s:552 +0x21
...[생략]...




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







[최초 등록일: ]
[최종 수정일: 4/18/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2023-04-04 11시53분
[강성일] 감사합니다 :)
[guest]

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13601정성태4/19/2024214닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024283닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024315닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024347닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024415닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024788닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024912닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241018닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241050닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241207C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241169닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241073Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241197닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241156오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241297Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241049개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241420Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241588개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241137닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241629닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241876닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...