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)
13423정성태10/6/20233063스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233204닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233243닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235327스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233092스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233760닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233336닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233152오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233639닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233390디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233582닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236853닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233364Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234863닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233722닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233714Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233473닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233426VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233841닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233364오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233190오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233250닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233526닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233351오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/20233374닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/20234135스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...