-
Notifications
You must be signed in to change notification settings - Fork 19
/
admin.go
225 lines (198 loc) · 5.94 KB
/
admin.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// Copyright 2020 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
// Package admin implements an http.Server which can be used for operations
// and monitoring tools. It's designed to be shipped (and ran) inside
// an existing Go service.
package admin
import (
"context"
"fmt"
"net"
"net/http"
"net/http/pprof"
"os"
"runtime"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type Opts struct {
Addr string
Timeout time.Duration
}
// New returns an admin.Server instance that handles Prometheus metrics and pprof requests.
// Callers can use ':0' to bind onto a random port and call BindAddr() for the address.
func New(opts Opts) (*Server, error) {
timeout, _ := time.ParseDuration("45s")
if opts.Timeout >= 0*time.Second {
timeout = opts.Timeout
}
var listener net.Listener
var err error
if opts.Addr == "" || opts.Addr == ":0" {
listener, err = net.Listen("tcp", "127.0.0.1:0")
} else {
listener, err = net.Listen("tcp", opts.Addr)
}
if err != nil {
return nil, fmt.Errorf("listening on %s failed: %v", opts.Addr, err)
}
router := handler()
svc := &Server{
router: router,
listener: listener,
svc: &http.Server{
Addr: listener.Addr().String(),
Handler: router,
ReadTimeout: timeout,
WriteTimeout: timeout,
IdleTimeout: timeout,
},
}
svc.AddHandler("/live", svc.livenessHandler())
svc.AddHandler("/ready", svc.readinessHandler())
return svc, nil
}
// Server represents a holder around a net/http Server which
// is used for admin endpoints. (i.e. metrics, healthcheck)
type Server struct {
router *mux.Router
svc *http.Server
listener net.Listener
liveChecks []*healthCheck
readyChecks []*healthCheck
}
// BindAddr returns the server's bind address. This is in Go's format so :8080 is valid.
func (s *Server) BindAddr() string {
if s == nil || s.svc == nil {
return ""
}
return s.listener.Addr().String()
}
func (s *Server) SetReadTimeout(timeout time.Duration) {
if s == nil || s.svc == nil {
return
}
s.svc.ReadTimeout = timeout
}
func (s *Server) SetWriteTimeout(timeout time.Duration) {
if s == nil || s.svc == nil {
return
}
s.svc.WriteTimeout = timeout
}
func (s *Server) SetIdleTimeout(timeout time.Duration) {
if s == nil || s.svc == nil {
return
}
s.svc.IdleTimeout = timeout
}
// Listen brings up the admin HTTP server. This call blocks until the server is Shutdown or panics.
func (s *Server) Listen() error {
if s == nil || s.svc == nil || s.listener == nil {
return nil
}
return s.svc.Serve(s.listener)
}
// Shutdown unbinds the HTTP server.
func (s *Server) Shutdown() {
if s == nil || s.svc == nil {
return
}
s.svc.Shutdown(context.TODO())
}
// AddHandler will append an http.HandlerFunc to the admin Server
func (s *Server) AddHandler(path string, hf http.HandlerFunc) {
s.router.HandleFunc(path, hf)
}
// AddVersionHandler will append 'GET /version' route returning the provided version
func (s *Server) AddVersionHandler(version string) {
s.AddHandler("/version", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(version))
})
}
// Subrouter creates and returns a subrouter with the specific prefix.
//
// The returned subrouter can use middleware without impacting
// the parent router. For example:
//
// svr, err := New(Opts{
// Addr: ":9090",
// })
//
// subRouter := svr.Subrouter("/prefix")
// subRouter.Use(someMiddleware)
// subRouter.HandleFunc("/resource", ResourceHandler)
//
// Here, requests for "/prefix/resource" would go through someMiddleware while
// the liveliness and readiness routes added to the parent router by New()
// would not.
func (s *Server) Subrouter(pathPrefix string) *mux.Router {
return s.router.PathPrefix(pathPrefix).Subrouter()
}
// profileEnabled returns if a given pprof handler should be
// enabled according to pprofHandlers and the PPROF_* environment
// variables.
//
// These profiles can be disabled by setting the appropriate PPROF_*
// environment variable. (i.e. PPROF_ALLOCS=no)
//
// An empty string, "yes", or "true" enables the profile. Any other
// value disables the profile.
func profileEnabled(name string) bool {
k := fmt.Sprintf("PPROF_%s", strings.ToUpper(name))
v := strings.ToLower(os.Getenv(k))
return v == "" || v == "yes" || v == "true"
}
// Handler returns an http.Handler for the admin http service.
// This contains metrics and pprof handlers.
//
// No metrics specific to the handler are recorded.
//
// We only want to expose on the admin servlet because these
// profiles/dumps can contain sensitive info (raw memory).
func Handler() http.Handler {
return handler()
}
func handler() *mux.Router {
r := mux.NewRouter()
// prometheus metrics
r.Path("/metrics").Handler(promhttp.Handler())
// always register index and cmdline handlers
r.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
r.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
if profileEnabled("profile") {
r.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
}
if profileEnabled("symbol") {
r.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
}
if profileEnabled("trace") {
r.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
}
// Register runtime/pprof handlers
if profileEnabled("allocs") {
r.Handle("/debug/pprof/allocs", pprof.Handler("allocs"))
}
if profileEnabled("block") {
runtime.SetBlockProfileRate(1)
r.Handle("/debug/pprof/block", pprof.Handler("block"))
}
if profileEnabled("goroutine") {
r.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine"))
}
if profileEnabled("heap") {
r.Handle("/debug/pprof/heap", pprof.Handler("heap"))
}
if profileEnabled("mutex") {
runtime.SetMutexProfileFraction(1)
r.Handle("/debug/pprof/mutex", pprof.Handler("mutex"))
}
if profileEnabled("threadcreate") {
r.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate"))
}
return r
}