1
0
mirror of https://github.com/google/gops.git synced 2024-11-24 08:22:25 +02:00
gops/agent/agent.go

238 lines
5.8 KiB
Go
Raw Normal View History

2016-11-04 07:43:04 +02:00
// Copyright 2016 The Go Authors. All rights reserved.
2016-11-04 05:59:53 +02:00
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package agent provides hooks programs can register to retrieve
// diagnostics data by using gops.
package agent
import (
"fmt"
"io"
2016-11-15 08:59:09 +02:00
"io/ioutil"
2016-11-04 05:59:53 +02:00
"net"
"os"
2016-11-04 09:54:41 +02:00
gosignal "os/signal"
2016-11-04 05:59:53 +02:00
"runtime"
2016-11-14 06:04:40 +02:00
"runtime/pprof"
2017-01-20 23:09:45 +02:00
"runtime/trace"
2016-11-15 08:59:09 +02:00
"strconv"
"sync"
2016-11-14 06:38:17 +02:00
"time"
2016-11-04 09:54:41 +02:00
2017-03-02 21:51:14 +02:00
"bufio"
2016-11-15 09:07:31 +02:00
"github.com/google/gops/internal"
"github.com/google/gops/signal"
2017-03-02 21:51:14 +02:00
"github.com/kardianos/osext"
2016-11-04 05:59:53 +02:00
)
const defaultAddr = "127.0.0.1:0"
var (
mu sync.Mutex
portfile string
listener net.Listener
units = []string{" bytes", "KB", "MB", "GB", "TB", "PB"}
)
// Options allows configuring the started agent.
type Options struct {
// Addr is the host:port the agent will be listening at.
// Optional.
Addr string
// NoShutdownCleanup tells the agent not to automatically cleanup
// resources if the running process recieves an interrupt.
// Optional.
NoShutdownCleanup bool
}
// Listen starts the gops agent on a host process. Once agent started, users
// can use the advanced gops features. The agent will listen to Interrupt
// signals and exit the process, if you need to perform further work on the
// Interrupt signal use the options parameter to configure the agent
// accordingly.
//
2016-11-15 08:59:09 +02:00
// Note: The agent exposes an endpoint via a TCP connection that can be used by
// any program on the system. Review your security requirements before starting
// the agent.
func Listen(opts *Options) error {
mu.Lock()
defer mu.Unlock()
if opts == nil {
opts = &Options{}
}
if portfile != "" {
return fmt.Errorf("gops: agent already listening at: %v", listener.Addr())
}
2016-11-15 09:07:31 +02:00
gopsdir, err := internal.ConfigDir()
2016-11-15 08:59:09 +02:00
if err != nil {
return err
}
err = os.MkdirAll(gopsdir, os.ModePerm)
if err != nil {
return err
}
if !opts.NoShutdownCleanup {
gracefulShutdown()
}
2016-11-15 08:59:09 +02:00
addr := opts.Addr
if addr == "" {
addr = defaultAddr
}
ln, err := net.Listen("tcp", addr)
2016-11-15 08:59:09 +02:00
if err != nil {
return err
}
listener = ln
port := listener.Addr().(*net.TCPAddr).Port
portfile = fmt.Sprintf("%s/%d", gopsdir, os.Getpid())
err = ioutil.WriteFile(portfile, []byte(strconv.Itoa(port)), os.ModePerm)
2016-11-04 05:59:53 +02:00
if err != nil {
return err
2016-11-04 05:59:53 +02:00
}
2016-11-04 09:54:41 +02:00
go listen()
return nil
}
2016-11-04 09:54:41 +02:00
func listen() {
buf := make([]byte, 1)
for {
fd, err := listener.Accept()
if err != nil {
fmt.Fprintf(os.Stderr, "gops: %v", err)
if netErr, ok := err.(net.Error); ok && !netErr.Temporary() {
break
2016-11-04 05:59:53 +02:00
}
continue
}
if _, err := fd.Read(buf); err != nil {
fmt.Fprintf(os.Stderr, "gops: %v", err)
continue
2016-11-04 05:59:53 +02:00
}
if err := handle(fd, buf); err != nil {
fmt.Fprintf(os.Stderr, "gops: %v", err)
continue
}
fd.Close()
}
}
func gracefulShutdown() {
c := make(chan os.Signal, 1)
gosignal.Notify(c, os.Interrupt)
go func() {
// cleanup the socket on shutdown.
<-c
Close()
os.Exit(1)
2016-11-04 05:59:53 +02:00
}()
}
// Close closes the agent, removing temporary files and closing the TCP listener.
// If no agent is listening, Close does nothing.
func Close() {
mu.Lock()
defer mu.Unlock()
if portfile != "" {
os.Remove(portfile)
portfile = ""
}
if listener != nil {
listener.Close()
}
}
func formatBytes(val uint64) string {
var i int
var target uint64
for i = range units {
target = 1 << uint(10*(i+1))
if val < target {
break
}
}
if i > 0 {
return fmt.Sprintf("%0.2f%s (%d bytes)", float64(val)/(float64(target)/1024), units[i], val)
}
return fmt.Sprintf("%d bytes", val)
}
func handle(conn io.Writer, msg []byte) error {
2016-11-04 05:59:53 +02:00
switch msg[0] {
2016-11-06 08:46:11 +02:00
case signal.StackTrace:
return pprof.Lookup("goroutine").WriteTo(conn, 2)
2016-11-04 07:32:46 +02:00
case signal.GC:
2016-11-04 06:08:37 +02:00
runtime.GC()
_, err := conn.Write([]byte("ok"))
return err
2016-11-04 08:28:51 +02:00
case signal.MemStats:
var s runtime.MemStats
runtime.ReadMemStats(&s)
fmt.Fprintf(conn, "alloc: %v\n", formatBytes(s.Alloc))
fmt.Fprintf(conn, "total-alloc: %v\n", formatBytes(s.TotalAlloc))
fmt.Fprintf(conn, "sys: %v\n", formatBytes(s.Sys))
2016-11-04 08:28:51 +02:00
fmt.Fprintf(conn, "lookups: %v\n", s.Lookups)
fmt.Fprintf(conn, "mallocs: %v\n", s.Mallocs)
fmt.Fprintf(conn, "frees: %v\n", s.Frees)
fmt.Fprintf(conn, "heap-alloc: %v\n", formatBytes(s.HeapAlloc))
fmt.Fprintf(conn, "heap-sys: %v\n", formatBytes(s.HeapSys))
fmt.Fprintf(conn, "heap-idle: %v\n", formatBytes(s.HeapIdle))
fmt.Fprintf(conn, "heap-in-use: %v\n", formatBytes(s.HeapInuse))
fmt.Fprintf(conn, "heap-released: %v\n", formatBytes(s.HeapReleased))
2016-11-04 08:28:51 +02:00
fmt.Fprintf(conn, "heap-objects: %v\n", s.HeapObjects)
fmt.Fprintf(conn, "stack-in-use: %v\n", formatBytes(s.StackInuse))
fmt.Fprintf(conn, "stack-sys: %v\n", formatBytes(s.StackSys))
fmt.Fprintf(conn, "next-gc: when heap-alloc >= %v\n", formatBytes(s.NextGC))
lastGC := "-"
if s.LastGC != 0 {
lastGC = fmt.Sprint(time.Unix(0, int64(s.LastGC)))
}
fmt.Fprintf(conn, "last-gc: %v\n", lastGC)
fmt.Fprintf(conn, "gc-pause: %v\n", time.Duration(s.PauseTotalNs))
2016-11-04 08:28:51 +02:00
fmt.Fprintf(conn, "num-gc: %v\n", s.NumGC)
fmt.Fprintf(conn, "enable-gc: %v\n", s.EnableGC)
fmt.Fprintf(conn, "debug-gc: %v\n", s.DebugGC)
2016-11-04 07:53:07 +02:00
case signal.Version:
fmt.Fprintf(conn, "%v\n", runtime.Version())
2016-11-14 06:04:40 +02:00
case signal.HeapProfile:
pprof.WriteHeapProfile(conn)
2016-11-14 06:04:40 +02:00
case signal.CPUProfile:
2016-11-14 06:38:17 +02:00
if err := pprof.StartCPUProfile(conn); err != nil {
return err
2016-11-14 06:38:17 +02:00
}
time.Sleep(30 * time.Second)
pprof.StopCPUProfile()
2017-01-03 11:15:13 +02:00
case signal.Stats:
2016-11-14 21:07:06 +02:00
fmt.Fprintf(conn, "goroutines: %v\n", runtime.NumGoroutine())
fmt.Fprintf(conn, "OS threads: %v\n", pprof.Lookup("threadcreate").Count())
fmt.Fprintf(conn, "GOMAXPROCS: %v\n", runtime.GOMAXPROCS(0))
fmt.Fprintf(conn, "num CPU: %v\n", runtime.NumCPU())
2017-03-02 21:51:14 +02:00
case signal.BinaryDump:
path, err := osext.Executable()
if err != nil {
return err
}
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
_, err = bufio.NewReader(f).WriteTo(conn)
return err
2017-01-20 23:09:45 +02:00
case signal.Trace:
trace.Start(conn)
time.Sleep(5 * time.Second)
trace.Stop()
2016-11-04 05:59:53 +02:00
}
return nil
}