forked from q3k/statusz
/
statusz.go
240 lines (214 loc) · 5.95 KB
/
statusz.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
// Copyright 2018 Serge Bazanski
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Based off github.com/youtube/doorman/blob/master/go/status/status.go
// Copyright 2016 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package statusz
import (
"bytes"
"context"
"crypto/sha256"
"fmt"
"html"
"html/template"
"io"
"net/http"
"os"
"os/user"
"path/filepath"
"sync"
"time"
"github.com/golang/glog"
"github.com/shirou/gopsutil/load"
)
var (
binaryName = filepath.Base(os.Args[0])
binaryHash string
hostname string
username string
serverStart = time.Now()
lock sync.Mutex
sections []section
tmpl = template.Must(reparse(nil))
funcs = make(template.FuncMap)
DefaultMux = true
RpcPage = "/debug/requests"
Favicon = ""
)
type section struct {
Banner string
Fragment string
F func() interface{}
}
var statusHTML = `<!DOCTYPE html>
<html>
<head>
<title>Status for {{.BinaryName}}</title>
{{ if not (eq .Favicon "") }}
<link rel="shortcut icon" href="{{.Favicon}}">
{{ end }}
<style>
body {
font-family: sans-serif;
background: #fff;
}
h1 {
clear: both;
width: 100%;
text-align: center;
font-size: 120%;
background: #eeeeff;
}
.lefthand {
float: left;
width: 80%;
}
.righthand {
text-align: right;
}
</style>
</head>
<h1>Status for {{.BinaryName}}</h1>
<div>
<div class=lefthand>
Started at {{.StartTime}}<br>
Current time {{.CurrentTime}}<br>
SHA256 {{.BinaryHash}}<br>
</div>
<div class=righthand>
Running as {{.Username}} on {{.Hostname}}<br>
Load {{.LoadAvg}}<br>
View <a href=/debug/status>status</a>,
<a href={{.RpcPage}}>requests</a>
</div>
</div>`
func reparse(sections []section) (*template.Template, error) {
var buf bytes.Buffer
io.WriteString(&buf, `{{define "status"}}`)
io.WriteString(&buf, statusHTML)
for i, sec := range sections {
fmt.Fprintf(&buf, "<h1>%s</h1>\n", html.EscapeString(sec.Banner))
fmt.Fprintf(&buf, "{{$sec := index .Sections %d}}\n", i)
fmt.Fprintf(&buf, `{{template "sec-%d" call $sec.F}}`+"\n", i)
}
fmt.Fprintf(&buf, `</html>`)
io.WriteString(&buf, "{{end}}\n")
for i, sec := range sections {
fmt.Fprintf(&buf, `{{define "sec-%d"}}%s{{end}}\n`, i, sec.Fragment)
}
return template.New("").Funcs(funcs).Parse(buf.String())
}
func StatusHandler(w http.ResponseWriter, r *http.Request) {
lock.Lock()
defer lock.Unlock()
loadavg := "unknown"
l, err := load.AvgWithContext(r.Context())
if err == nil {
loadavg = fmt.Sprintf("%.2f %.2f %.2f", l.Load1, l.Load5, l.Load15)
}
data := struct {
Sections []section
BinaryName string
BinaryHash string
Hostname string
Username string
StartTime string
CurrentTime string
LoadAvg string
RpcPage string
Favicon string
}{
Sections: sections,
BinaryName: binaryName,
BinaryHash: binaryHash,
Hostname: hostname,
Username: username,
StartTime: serverStart.Format(time.RFC1123),
CurrentTime: time.Now().Format(time.RFC1123),
LoadAvg: loadavg,
RpcPage: RpcPage,
Favicon: Favicon,
}
if err := tmpl.ExecuteTemplate(w, "status", data); err != nil {
glog.Errorf("servenv: couldn't execute template: %v", err)
}
}
func init() {
var err error
hostname, err = os.Hostname()
if err != nil {
glog.Fatalf("os.Hostname: %v", err)
}
user, err := user.Current()
if err != nil {
glog.Fatalf("user.Current: %v", err)
}
username = fmt.Sprintf("%s (%s)", user.Username, user.Uid)
f, err := os.Open(os.Args[0])
if err != nil {
glog.Fatalf("os.Open(%q): %v", os.Args[0], err)
}
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
glog.Fatalf("io.Copy: %v", err)
}
binaryHash = fmt.Sprintf("%x", h.Sum(nil))
if DefaultMux {
http.HandleFunc("/debug/status", StatusHandler)
}
}
// AddStatusPart adds a new section to status. frag is used as a
// subtemplate of the template used to render /debug/status, and will
// be executed using the value of invoking f at the time of the
// /debug/status request. frag is parsed and executed with the
// html/template package. Functions registered with AddStatusFuncs
// may be used in the template.
func AddStatusPart(banner, frag string, f func(context.Context) interface{}) {
lock.Lock()
defer lock.Unlock()
secs := append(sections, section{
Banner: banner,
Fragment: frag,
F: func() interface{} { return f(context.Background()) },
})
var err error
tmpl, err = reparse(secs)
if err != nil {
secs[len(secs)-1] = section{
Banner: banner,
Fragment: "<code>bad status template: {{.}}</code>",
F: func() interface{} { return err },
}
}
tmpl, _ = reparse(secs)
sections = secs
}
// AddStatusSection registers a function that generates extra
// information for /debug/status. If banner is not empty, it will be
// used as a header before the information. If more complex output
// than a simple string is required use AddStatusPart instead.
func AddStatusSection(banner string, f func(context.Context) string) {
AddStatusPart(banner, `{{.}}`, func(ctx context.Context) interface{} { return f(ctx) })
}