github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/hack/debug (about) 1 #!/bin/bash 2 3 ## Installs delve, then runs it as a headless server 4 ## Keeps running until killed 5 ## Also adds some goodies: delve servers ignore interrupts, which is annoying... 6 ## and also once a debugging session is done, the server just hangs there, which 7 ## is equally annoying. 8 ## This script takes care of both these things 9 10 SUBSHELL_PID= 11 DLV_PID_FILE= 12 RUNNING=true 13 14 main() { 15 [ "$1" ] || usage 16 17 ensure_delve_installed || exit $? 18 19 local PORT="$DOCKER_SWARMKIT_DELVE_PORT" 20 [ "$PORT" ] || PORT=2345 21 22 local DLV_CMD="dlv test --accept-multiclient --headless --listen=:$PORT --api-version=2 --log $@" 23 echo $DLV_CMD 24 25 trap handle_interrupt INT 26 27 DLV_PID_FILE=$(mktemp /tmp/dlv.XXXXXX.pid) 28 local DLV_OUTPUT_FILE=$(mktemp /tmp/dlv.XXXXXX.out) 29 30 # the weird regex is because we keep the output colored 31 local HALTING_REGEX='^\e\[37mDEBU\e\[0m\[[0-9]+\] halting\s+\e\[37mlayer\e\[0m=debugger' 32 while $RUNNING; do 33 # using `script` to keep colored output, and `exec` to get the PID from the 34 # subshell 35 script --flush --quiet "$DLV_OUTPUT_FILE" --command 'printf $$ > '"$DLV_PID_FILE && exec $DLV_CMD" & 36 SUBSHELL_PID=$! 37 38 # wait for either the subshell to die, or for the "halting" line to appear 39 # in the output 40 tail --follow --pid="$SUBSHELL_PID" --sleep-interval=0.1 "$DLV_OUTPUT_FILE" 2> /dev/null | grep --perl-regex --line-buffered "$HALTING_REGEX" | ( read && kill_delve ) 41 42 wait "$SUBSHELL_PID" 43 done 44 45 rm -f "$DLV_PID_FILE" "$DLV_OUTPUT_FILE" 46 } 47 48 handle_interrupt() { 49 RUNNING=false 50 kill_delve 51 } 52 53 kill_delve() { 54 if [ -r "$DLV_PID_FILE" ]; then 55 local DLV_PID=$(cat "$DLV_PID_FILE") 56 [ "$DLV_PID" ] && kill "$DLV_PID" &> /dev/null 57 fi 58 59 [ "$SUBSHELL_PID" ] && kill $SUBSHELL_PID &> /dev/null 60 } 61 62 ensure_delve_installed() { 63 which dlv &> /dev/null || go get -u github.com/derekparker/delve/cmd/dlv 64 } 65 66 usage() { 67 echo "Usage: $0 name/of/go/package [additional dlv test options]" 68 exit 1 69 } 70 71 main "$@"