hashicorp / go-plugin

Golang plugin system over RPC.
Mozilla Public License 2.0
5.29k stars 457 forks source link

how do debug plugin #194

Closed huahuayu closed 1 year ago

huahuayu commented 2 years ago

Hi, since the plugin is invoked by the base project in different and run in different PID, so it become harder to debug. I tried https://www.jetbrains.com/help/go/attach-to-running-go-processes-with-debugger.html#attach-to-a-process-on-a-remote-machine but didn't success, could you please give an exmaple how to do it?

PGoski commented 2 years ago

It's possible to do with delve. Here are steps that I used to launch a plugin in debug mode:

  1. create a launcher wrapper runDebug.sh:
#set magicCookie=magicValue environemnt  variables from HandshakeConfig
export TEST_PLUGIN=cookie_value
#set plugin vars
export PLUGIN_MIN_PORT=10000
export PLUGIN_MAX_PORT=25000
export PLUGIN_PROTOCOL_VERSIONS=1

#make sure plugin output is "original" without debugger messages by passing log-dest & tty arguments
dlv --listen=:40000 --headless=true --api-version=2 --accept-multiclient \
  --log-dest "dlv.log"  \
  --tty="" \
    exec /full/path/to/plugin.bin -- "$@"
  1. main.go
cmd := exec.Command("/bin/sh", "/full/path/to/runDebug.sh")
client := plugin.NewClient(&plugin.ClientConfig{
    HandshakeConfig: adapter.HandshakeConfig,
    Plugins:         pluginMap,
    Cmd:             cmd,
})
  1. in Goland create go Remote debugger with 40000 port

  2. Profit

fairclothjm commented 2 years ago

Alternatively,

  1. Build the plugin binary for debugging

    go build -gcflags="all=-N -l" -o ~/my-plugin main.go
  2. Invoke the base project that spawns the plugin process.

  3. Then attach to the running plugin process

    dlv attach $(pgrep my-plugin)