forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restful-cpuprofiler-service.go
65 lines (58 loc) · 2 KB
/
restful-cpuprofiler-service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"github.com/emicklei/go-restful"
"io"
"log"
"os"
"runtime/pprof"
)
// ProfilingService is a WebService that can start/stop a CPU profile and write results to a file
// GET /{rootPath}/start will activate CPU profiling
// GET /{rootPath}/stop will stop profiling
//
// NewProfileService("/profiler", "ace.prof").AddWebServiceTo(restful.DefaultContainer)
//
type ProfilingService struct {
rootPath string // the base (root) of the service, e.g. /profiler
cpuprofile string // the output filename to write profile results, e.g. myservice.prof
cpufile *os.File // if not nil, then profiling is active
}
func NewProfileService(rootPath string, outputFilename string) *ProfilingService {
ps := new(ProfilingService)
ps.rootPath = rootPath
ps.cpuprofile = outputFilename
return ps
}
// Add this ProfileService to a restful Container
func (p ProfilingService) AddWebServiceTo(container *restful.Container) {
ws := new(restful.WebService)
ws.Path(p.rootPath).Consumes("*/*").Produces(restful.MIME_JSON)
ws.Route(ws.GET("/start").To(p.startProfiler))
ws.Route(ws.GET("/stop").To(p.stopProfiler))
container.Add(ws)
}
func (p *ProfilingService) startProfiler(req *restful.Request, resp *restful.Response) {
if p.cpufile != nil {
io.WriteString(resp.ResponseWriter, "[restful] CPU profiling already running")
return // error?
}
cpufile, err := os.Create(p.cpuprofile)
if err != nil {
log.Fatal(err)
}
// remember for close
p.cpufile = cpufile
pprof.StartCPUProfile(cpufile)
io.WriteString(resp.ResponseWriter, "[restful] CPU profiling started, writing on:"+p.cpuprofile)
}
func (p *ProfilingService) stopProfiler(req *restful.Request, resp *restful.Response) {
if p.cpufile == nil {
io.WriteString(resp.ResponseWriter, "[restful] CPU profiling not active")
return // error?
}
pprof.StopCPUProfile()
p.cpufile.Close()
p.cpufile = nil
io.WriteString(resp.ResponseWriter, "[restful] CPU profiling stopped, closing:"+p.cpuprofile)
}
func main() {} // exists for example compilation only