-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadmin.go
378 lines (341 loc) · 9.36 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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Package admin implements an HTTP server providing useful information & tools about this server.
package admin
import (
"expvar"
"fmt"
"net/http"
"net/http/pprof"
"os"
"path"
"reflect"
"runtime"
"sort"
"strings"
"sync"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/net/trace"
"gopkg.in/op/go-logging.v1"
)
var log Logger = logging.MustGetLogger("admin")
// Top level groups for the Sidebar nav
var (
ProcessInfoGroup = "Process Info"
PerfProfileGroup = "Performance Profile"
UtilitiesGroup = "Utilities"
MetricsGroup = "Metrics"
)
// Well known paths
var (
RootPath = "/"
AdminPath = "/admin"
ClientsPath = AdminPath + "/clients/"
ServersPath = AdminPath + "/servers/"
FilesPath = AdminPath + "/files/"
)
// Route represents a path and a handler, making it possible to display a menu of routes in the UI.
type Route struct {
path string
prefix bool
handler http.Handler
alias string
group string
includeInIndex bool
method string
}
// Opts is all flags associated with the admin HTTP server.
type Opts struct {
Disabled bool `long:"disabled" description:"If true, the admin server will never start." env:"ADMIN_DISABLE_HTTP"`
Host string `long:"host" description:"The host to listen on."`
Port int `long:"port" default:"9990" description:"The port to listen on."`
Logger Logger `no-flag:"true"`
LogInfo LoggerInfo `no-flag:"true"`
}
// DefaultAdminHTTPServer is the global admin http server.
var DefaultAdminHTTPServer = &HTTPServer{}
var routes = []Route{
{
path: RootPath,
handler: RedirectHandler(AdminPath, http.StatusTemporaryRedirect),
alias: "Admin Redirect",
includeInIndex: false,
},
{
path: AdminPath,
handler: http.HandlerFunc(SummaryHandler),
alias: "Summary",
includeInIndex: true,
},
{
path: AdminPath + "/",
handler: RedirectHandler(AdminPath, http.StatusTemporaryRedirect),
alias: "Admin Redirect",
includeInIndex: false,
},
{
path: "/admin/ping",
handler: http.HandlerFunc(PingHandler),
alias: "Ping",
includeInIndex: true,
group: UtilitiesGroup,
},
{
path: "/admin/gc",
handler: http.HandlerFunc(gcHandler),
alias: "Garbage Collect",
includeInIndex: true,
group: UtilitiesGroup,
},
{
path: "/admin/logging",
handler: http.HandlerFunc(LoggingHandler),
alias: "Logging",
group: UtilitiesGroup,
includeInIndex: true,
},
{
path: "/admin/logging",
handler: http.HandlerFunc(UpdateLoggingHandler),
method: http.MethodPost,
includeInIndex: false,
},
{
path: "/admin/metrics",
handler: http.HandlerFunc(MetricQueryHandler),
alias: "Metrics",
includeInIndex: true,
group: MetricsGroup,
},
{
path: "/debug/pprof/",
handler: http.HandlerFunc(pprof.Index),
alias: "PProf",
includeInIndex: true,
group: PerfProfileGroup,
},
{
path: "/debug/pprof/cmdline",
handler: http.HandlerFunc(pprof.Cmdline),
alias: "CmdLine",
includeInIndex: true,
group: PerfProfileGroup,
},
{
path: "/debug/pprof/profile",
handler: http.HandlerFunc(pprof.Profile),
alias: "Profile",
includeInIndex: true,
group: PerfProfileGroup,
},
{
path: "/debug/pprof/symbol",
handler: http.HandlerFunc(pprof.Symbol),
alias: "Symbol",
includeInIndex: true,
group: PerfProfileGroup,
},
{
path: "/debug/pprof/trace",
handler: http.HandlerFunc(pprof.Trace),
alias: "Trace",
includeInIndex: true,
group: PerfProfileGroup,
},
{
path: "/debug/pprof/",
prefix: true,
handler: http.HandlerFunc(pprof.Index),
includeInIndex: false,
},
{
path: "/debug/events",
handler: http.HandlerFunc(trace.Events),
alias: "Event Traces",
includeInIndex: true,
group: UtilitiesGroup,
},
{
path: "/debug/requests",
handler: http.HandlerFunc(trace.Traces),
alias: "Request Traces",
includeInIndex: true,
group: UtilitiesGroup,
},
{
path: "/debug/vars",
handler: expvar.Handler(),
alias: "Vars",
includeInIndex: true,
group: ProcessInfoGroup,
},
{
path: "/metrics",
handler: promhttp.HandlerFor(
prometheus.Gatherers{Gatherer},
promhttp.HandlerOpts{}),
includeInIndex: false,
alias: "Metrics",
},
{
path: "/favicon.ico",
handler: ResourceHandler("/", "img"),
alias: "Favicon",
includeInIndex: false,
},
{
path: FilesPath,
prefix: true,
handler: ResourceHandler(FilesPath, ""),
includeInIndex: false,
alias: "Files",
},
}
// PingHandler serves a very simple response that can be used as a health check.
func PingHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(path.Base(os.Args[0])))
}
// RedirectHandler avoids the default behaviour of writing random html into the response.
func RedirectHandler(url string, code int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writeContentType(w, "text/plain;charset=UTF-8")
http.Redirect(w, r, url, code)
})
}
// ResourceHandler returns the asset, relative to the given paths.
func ResourceHandler(baseRequestPath, baseResourcePath string) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
urlPath := strings.TrimPrefix(request.URL.Path, baseRequestPath)
writeContentType(writer, detectTypeFromExtension(urlPath))
assetPath := path.Join(baseResourcePath, urlPath)
if contents, err := Asset(assetPath); err != nil {
log.Warningf("Resource %s not found (for %s)", assetPath, request.URL.Path)
writer.WriteHeader(http.StatusNotFound)
} else {
writer.Write(contents)
}
})
}
func gcHandler(w http.ResponseWriter, r *http.Request) {
log.Infof("Forcing GC...")
runtime.GC()
log.Infof("GC completed")
w.Write([]byte("GC complete"))
}
// HTTPServer is a holder for the router and server involved in serving the admin UI.
type HTTPServer struct {
adminHTTPMuxer *mux.Router
allRoutes []Route
}
func (a *HTTPServer) addAdminRoutes(newRoutes ...Route) {
for _, r := range newRoutes {
method := r.method
if method == "" {
r.method = http.MethodGet
}
a.allRoutes = append(a.allRoutes, r)
}
a.updateMuxer()
}
func (a *HTTPServer) updateMuxer() {
r := mux.NewRouter()
for _, route := range a.allRoutes {
handler := &indexView{
title: route.alias,
next: route.handler,
entries: func() entrySlice {
return a.indexEntries()
},
}
if route.prefix {
r.PathPrefix(route.path).Handler(handler).Methods(route.method).Name(route.alias)
} else {
r.Path(route.path).Handler(handler).Methods(route.method).Name(route.alias)
}
}
endpoints := make(sort.StringSlice, 0, len(a.allRoutes))
for _, route := range a.allRoutes {
endpoints = append(endpoints, fmt.Sprintf("\t%s => %s", route.path, getFunctionName(route.handler)))
}
sort.Sort(endpoints)
log.Debugf("AdminHttpServer Muxer endpoints:\n%s", strings.Join(endpoints, "\n"))
a.adminHTTPMuxer = r
}
func (a *HTTPServer) indexEntries() []entry {
entries := make([]entry, 0)
// TODO(mike): Add clients, servers here
entries = append(entries, a.localRoutes()...)
return entries
}
func (a *HTTPServer) localRoutes() []entry {
routes := make([]Route, 0)
for _, r := range a.allRoutes {
if r.includeInIndex {
routes = append(routes, r)
}
}
results := make([]entry, 0, len(routes))
grouped := groupRoutesByGroup(routes)
for g, routes := range grouped {
links := make(entrySlice, 0, len(routes))
for _, r := range routes {
links = append(links, link{ID: r.alias, HRef: r.path, Method: r.method})
}
if g == "" {
results = append(results, links...)
} else {
results = append(results, group{
Name: g,
Links: links,
})
}
}
return results
}
func groupRoutesByGroup(routes []Route) map[string][]Route {
results := make(map[string][]Route)
for _, r := range routes {
existing, ok := results[r.group]
if !ok {
results[r.group] = []Route{r}
} else {
results[r.group] = append(existing, r)
}
}
return results
}
func (a *HTTPServer) startServer(opts Opts) {
if opts.Logger != nil {
log = opts.Logger
}
if opts.LogInfo != nil {
loggerInfo = opts.LogInfo
}
if opts.Disabled {
log.Infof("Not starting admin http")
return
}
log.Infof("Serving admin http on %s:%d", opts.Host, opts.Port)
log.Errorf("Failed to serve admin HTTP: %s", http.ListenAndServe(fmt.Sprintf("%s:%d", opts.Host, opts.Port), a.adminHTTPMuxer))
}
func getFunctionName(i interface{}) string {
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.String:
return v.String()
default:
return runtime.FuncForPC(v.Pointer()).Name()
}
}
var once sync.Once
// Serve starts the HTTPServer.
func Serve(opts Opts) {
DefaultAdminHTTPServer.addAdminRoutes(routes...)
DefaultAdminHTTPServer.startServer(opts)
}
// ServeOnce starts the HTTPServer, but only once.
func ServeOnce(opts Opts) {
once.Do(func() {
Serve(opts)
})
}