1

Right now, I profile Go applications using go tool pprof like this:

go tool pprof http://localhost:8080/debug/pprof/profile

I want to use the pprof tool on an arbitrary Go process which is running a http server on an unknown port. The only information I have about the process is its PID. I need to do one of two things:

  • Get the Go processes port number from its PID.
  • Profile the running process directly. For example, something like go tool pprof 10303 where the PID is 10303.

Would either of these work?

Ben Sandler
  • 2,223
  • 5
  • 26
  • 36

1 Answers1

0

Service Discovery is designed to resolve problems like this. A simple solution is to create a tmp file for every PID, writing each port to the according file. and read the port when you need go tool pprof.

http.ListenAndServe("localhost:" + PORT, nil)
tmpFilePath := filePath.Join(os.TempDir(), "myport_" + strconv.FormatInt(os.Getpid(), 10))
f, _ := os.OpenFile(tmpFilePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
f.Write(byte[](strconv.FormatInt(PORT, 10)))
f.Close()

in go tool prof bash: go tool http://localhost:`cat /tmp/myport_10303`/debug/pprof/profile

not tested in real, maybe some syntax error

UPDATE:

another way not change go source is, use bash command like netstat/lsof to find out the listening port of the go process. like:

netstat -antp | grep 10303| grep LISTEN | awk '{ print $4 }' | awk -F: '{print $2}'

not best bash script I think, just for reference.

Jiang YD
  • 3,205
  • 1
  • 14
  • 20
  • This isn't really what I am looking for. I want to profile an arbitrary Go process (not necessarily one I create). – Ben Sandler Jul 08 '15 at 01:03
  • 1
    you must not know how pprof work. you can not profile a go process if there is no pprof server embedded in. means you can not profile an arbitrary Go process. – Jiang YD Jul 08 '15 at 01:29
  • I know that the process exposes a pprof endpoint. I want to find the local port that process is running at. Your suggestion is possible, but it would require me to change the code of many Go applications. – Ben Sandler Jul 08 '15 at 01:38
  • That's a good idea. The only issue is that those commands require sudo (which I will not be able to use). Do you have any idea of how to do it without sudo? – Ben Sandler Jul 08 '15 at 02:21
  • run the go process in same user would help – Jiang YD Jul 08 '15 at 02:25
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/82659/discussion-between-ben-sandler-and-jiang-yd). – Ben Sandler Jul 08 '15 at 04:47