For case 2 we can set the program to wait for some signal (SIGUSR1) and attach debugger during this wait.
The code of main.go can be like this:
package main
import (
"os"
"os/signal"
"syscall"
"fmt"
"github.com/my/repo/cmd"
)
const (
waitForSignalEnv = "WAIT_FOR_DEBUGGER"
debuggerPort = "4321"
)
func main() {
// Waiting for debugger attach in case if waitForSignalEnv!=""
if os.Getenv(waitForSignalEnv) != "" {
sigs := make(chan os.Signal, 1)
goOn := make(chan bool, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR1)
go func() {
sig := <-sigs
if sig == syscall.SIGUSR1 {
goOn <- true
} else if (sig == syscall.SIGTERM || sig == syscall.SIGINT ){
fmt.Printf("Exiting ...")
os.Exit(0)
}
}()
fmt.Printf("%s env is set, waiting SIGUSR1.\nYou can run remote debug in vscode and attach dlv debugger:\n\n", waitForSignalEnv)
pid := os.Getpid()
fmt.Printf("dlv attach --continue --accept-multiclient --headless --listen=:%s %d\n", debuggerPort, pid)
fmt.Printf("\nLaunch remote debugger in vscode to port %d and then give SIGUSR1 to the process\n", debuggerPort)
fmt.Printf("kill -SIGUSR1 %d\n", pid)
<-goOn
fmt.Printf("Continue ...")
}
cmd.Execute()
}
launch.json of vscode:
{
"name": "myprog-remote-debug",
"type": "go",
"request": "launch",
"remotePath": "${env:GOPATH}/src/github.com/my/repo",
"mode": "remote",
"port": 4321,
"host": "127.0.0.1",
"program": "${env:GOPATH}/src/github.com/my/repo",
"showLog": true,
"trace": "verbose"
}
Explanation:
we launch the program with env WAIT_FOR_DEBUGGER=true, for example
export WAIT_FOR_DEBUGGER=true
./myprog -f values.yaml
It will output dlv attach ...
command and kill -SIGUSR <pid>
:
WAIT_FOR_DEBUGGER env is set, waiting SIGUSR1.
You can run remote debug in vscode and attach dlv debugger:
dlv attach --continue --accept-multiclient --headless --listen=:4321 556127
Launch remote debugger in vscode to port 4321 and then give SIGUSR1 to the process
kill -SIGUSR1 556127
Run the dlv attach ...
above
Then go to VS Code and run myprog-remote-debug. Set breakpoints before
Then give him kill -SIGUSR1 556127
and breakpoints will work