How to do pprof for gRPC service

  sonic0002        2021-01-29 23:11:33       4,885        0    

gRPC is a RPC framework based on HTTP and is frequently used for communications among micro service inside the same organization network. However,  the service functions cannot be accessed via normal HTTP URL as it's not a WEB framework. In this case, how to do pprof on a gRPC service?

The trick is starting a HTTP server asynchronously while starting the gRPC service. This HTTP server can be accessed to run prrof debug.

go func(){
	http.ListenAndServe(":10001", nil)
}()

Since it uses the default ServerMux, the pprof related routes will be registered automatically after importing the package net/http/pprof.

import _ "net/http/pprof"

If you are using customized ServerMux, can register below routes in your code.

r.HandleFunc("/debug/pprof/", pprof.Index)
r.HandleFunc("/debug/pprof/heap", pprof.Index)
r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
r.HandleFunc("/debug/pprof/profile", pprof.Profile)
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
r.HandleFunc("/debug/pprof/trace", pprof.Trace)

The complete code logic structure looks like:

func main () {
  go func() {
    http.ListenAndServe(":10001", nil)
  }()
  
  lis, err := net.Listen("tcp", 10000)
  grpcServer := grpc.NewServer()
  pb.RegisterRouteGuideServer(grpcServer, &routeGuideServer{})
  grpcServer.Serve(lis)
}

Now once the service is started, can access {server_ip}:10001/debug/pprof/profile to trigger pprof generation. 

With this, you can check CPU usage and other metrics.

Reference: Golang程序性能分析(三)用pprof分析gRPC服务的性能 (qq.com)

GOLANG  PPROF  GRPC 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

OOP in reality