-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoint.go
225 lines (202 loc) · 7.44 KB
/
endpoint.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 2015 Michal Witkowski. All Rights Reserved.
// Copyright 2020-2023 Fortio Authors. All Rights Reserved.
// See LICENSE for licensing terms.
package endpoint
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"html/template"
"net/http"
"strings"
"fortio.org/dflag"
"fortio.org/dflag/dynloglevel"
"fortio.org/log"
)
// FlagsEndpoint is a collection of `http.HandlerFunc` that serve debug pages about a given `FlagSet.
type FlagsEndpoint struct {
flagSet *flag.FlagSet
setURL string
}
// NewFlagsEndpoint creates a new debug `http.HandlerFunc` collection for a given `FlagSet`
// and an optional URL for Setter (needs to be secured). if setURL is empty, no setter function
// will be enabled. Also sets up `loglevel` flag as a dynamic flag.
func NewFlagsEndpoint(flagSet *flag.FlagSet, setURL string) *FlagsEndpoint {
dynloglevel.LoggerFlagSetup()
return &FlagsEndpoint{flagSet: flagSet, setURL: setURL}
}
// HTTPErrf logs and returns an error on the response.
func HTTPErrf(resp http.ResponseWriter, statusCode int, message string, rest ...interface{}) {
resp.WriteHeader(statusCode)
resp.Header().Set("Content-Type", "text/plain; charset=UTF-8")
log.Errf(message, rest...)
_, _ = resp.Write([]byte(fmt.Sprintf(message, rest...)))
}
// SetFlag updates a dynamic flag to a new value.
func (e *FlagsEndpoint) SetFlag(resp http.ResponseWriter, req *http.Request) {
log.LogRequest(req, "SetFlag")
if e.setURL == "" {
HTTPErrf(resp, http.StatusForbidden, "setting flags is not enabled")
return
}
name := req.URL.Query().Get("name")
value := req.URL.Query().Get("value")
f := e.flagSet.Lookup(name)
if f == nil {
HTTPErrf(resp, http.StatusForbidden, "Flag %q not found", name)
return
}
if !dflag.IsFlagDynamic(f) {
HTTPErrf(resp, http.StatusBadRequest, "Trying to set non dynamic flag %q", name)
return
}
if err := e.flagSet.Set(name, value); err != nil {
HTTPErrf(resp, http.StatusNotAcceptable, "Error setting %q to %q: %v", name, value, err)
return
}
resp.Header().Set("Content-Type", "text/plain; charset=UTF-8")
_, _ = resp.Write([]byte(fmt.Sprintf("Success %q -> %q", name, value)))
}
// ListFlags provides an HTML and JSON `http.HandlerFunc` that lists all Flags of a `FlagSet`.
// Additional URL query parameters can be used such as `type=[dynamic,static]` or `only_changed=true`.
func (e *FlagsEndpoint) ListFlags(resp http.ResponseWriter, req *http.Request) {
log.LogRequest(req, "ListFlags")
onlyChanged := req.URL.Query().Get("only_changed") != ""
onlyDynamic := req.URL.Query().Get("type") == "dynamic"
onlyStatic := req.URL.Query().Get("type") == "static"
flagSetJSON := &flagSetJSON{}
e.flagSet.VisitAll(func(f *flag.Flag) {
if onlyChanged && f.Value.String() == f.DefValue { // not exactly the same as "changed" (!)
return
}
if onlyDynamic && !dflag.IsFlagDynamic(f) {
return
}
if onlyStatic && dflag.IsFlagDynamic(f) {
return
}
flagSetJSON.Flags = append(flagSetJSON.Flags, flagToJSON(f))
})
flagSetJSON.ChecksumDynamic = fmt.Sprintf("%x", dflag.ChecksumFlagSet(e.flagSet, dflag.IsFlagDynamic))
flagSetJSON.ChecksumStatic = fmt.Sprintf("%x", dflag.ChecksumFlagSet(e.flagSet,
func(f *flag.Flag) bool { return !dflag.IsFlagDynamic(f) }))
flagSetJSON.FlagSetURL = e.setURL
if requestIsBrowser(req) && req.URL.Query().Get("format") != "json" {
resp.WriteHeader(http.StatusOK)
resp.Header().Add("Content-Type", "text/html")
if err := dflagListTemplate.Execute(resp, flagSetJSON); err != nil {
log.Fatalf("Bad template evaluation: %v", err)
}
} else {
resp.Header().Add("Content-Type", "application/json")
out, err := json.MarshalIndent(&flagSetJSON, "", " ")
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
return
}
resp.WriteHeader(http.StatusOK)
_, _ = resp.Write(out)
}
}
func requestIsBrowser(req *http.Request) bool {
return strings.Contains(req.Header.Get("Accept"), "html")
}
//nolint:lll
var dflagListTemplate = template.Must(template.New("dflag_list").Parse(
`
<html><head>
<title>Flags List</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="col-md-10 col-md-offset-1">
<h1>Flags Debug View</h1>
<p>
This page presents the configuration flags of this server (<a href="?format=json">JSON</a>).
</p>
<p>
You can easily filter only <a href="?only_changed=true"><span class="label label-primary">changed</span> flag</a> or filter flags by type:
</p>
<ul>
<li><a href="?type=dynamic"><span class="label label-success">dynamic</span></a> - flags tweakable dynamically - checksum <code>{{ .ChecksumDynamic }}</code></li>
<li><a href="?type=static"><span class="label label-default">static</span></a> - initialization-time only flags - checksum <code>{{ .ChecksumStatic }}</code></li>
</ul>
{{range $flag := .Flags }}
<div class="panel panel-default">
<div class="panel-heading">
<code>{{ $flag.Name }}</code>
{{ if $flag.IsChanged }}<span class="label label-primary">changed</span>{{ end }}
{{ if $flag.IsDynamic }}
<span class="label label-success">dynamic</span>
{{ else }}
<span class="label label-default">static</span>
{{ end }}
</div>
<div class="panel-body">
<dl class="dl-horizontal" style="margin-bottom: 0px">
<dt>Description</dt>
<dd><small>{{ $flag.Description }}</small></dd>
<dt>Default</dt>
<dd><pre style="font-size: 8pt">{{ $flag.DefaultValue }}</pre></dd>
<dt>Current</dt>
{{ if and $flag.IsDynamic (ne $.FlagSetURL "") }}
<form action="{{ $.FlagSetURL }}">
<input type="hidden" name="name" value="{{ $flag.Name }}" />
{{ if $flag.IsJSON }}
<dd><pre class="success" style="font-size: 8pt"><textarea name="value">{{ $flag.CurrentValue }}</textarea></pre><input type="submit" value="Update"/></dd>
{{ else }}
<dd><pre class="success" style="font-size: 8pt"><input type="text" name="value" value="{{ $flag.CurrentValue }}" /></pre></dd>
{{ end }}
</form>
{{ else }}
<dd><pre class="success" style="font-size: 8pt">{{ $flag.CurrentValue }}</pre></dd>
{{ end }}
</dl>
</div>
</div>
{{end}}
</div></div>
</body>
</html>
`))
type flagSetJSON struct {
ChecksumStatic string `json:"checksum_static"`
ChecksumDynamic string `json:"checksum_dynamic"`
FlagSetURL string `json:"set_url"`
Flags []*flagJSON `json:"flags"`
}
type flagJSON struct {
Name string `json:"name"`
Description string `json:"description"`
CurrentValue string `json:"current_value"`
DefaultValue string `json:"default_value"`
IsChanged bool `json:"is_changed"`
IsDynamic bool `json:"is_dynamic"`
IsJSON bool `json:"is_json"`
}
func flagToJSON(f *flag.Flag) *flagJSON {
fj := &flagJSON{
Name: f.Name,
Description: f.Usage,
CurrentValue: f.Value.String(),
DefaultValue: f.DefValue,
IsChanged: f.Value.String() != f.DefValue,
IsDynamic: dflag.IsFlagDynamic(f),
}
if dj, ok := f.Value.(dflag.DynamicJSONFlagValue); ok {
fj.IsJSON = dj.IsJSON() // could assert true
fj.CurrentValue = prettyPrintJSON(fj.CurrentValue)
fj.DefaultValue = prettyPrintJSON(fj.DefaultValue)
}
return fj
}
func prettyPrintJSON(input string) string {
out := &bytes.Buffer{}
if err := json.Indent(out, []byte(input), "", " "); err != nil {
log.Errf("Error pretty printing json %q: %v", input, err)
return "PRETTY_ERROR"
}
return out.String()
}