-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.handlers.ops.go
240 lines (216 loc) · 8.05 KB
/
api.handlers.ops.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
package main
import (
"encoding/json"
"expvar"
"fmt"
"net/http"
"net/http/pprof"
"runtime"
"runtime/debug"
"sync"
"sync/atomic"
"time"
"github.com/julienschmidt/httprouter"
"go.uber.org/zap"
)
// export goroutines to be used by expvar handler.
var goroutines = expvar.NewInt("goroutines")
// Statistics holds app stats for ops.
type Statistics struct {
version string
container bool
runtime string
platform string
called uint64
started time.Time
status map[int]uint64
mu *sync.RWMutex
}
// Maintenance holds app maintenance mode infos.
type Maintenance struct {
enabled atomic.Bool
reason string
started time.Time
}
func NewStatistics(tag, commit, runtime, platform string, iscontainer bool, starttime time.Time) *Statistics {
var version string
if tag == "" {
version = commit
}
return &Statistics{
version: version,
container: iscontainer,
started: starttime,
runtime: runtime,
platform: platform,
}
}
// OpsHandlerWrapper takes an http.Handler function and provides httprouter.Handle.
func (api *APIHandler) OpsHandlerWrapper(h http.Handler) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
h.ServeHTTP(w, r)
}
}
// GetMemStats returns memory statistics with number of goroutines in json.
func GetMemStats(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
goroutines.Set(int64(runtime.NumGoroutine()))
expvar.Handler().ServeHTTP(w, r)
}
// RunGC forces the run of the garbage collector asynchronously.
func (api *APIHandler) RunGC(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
go runtime.GC()
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
map[string]string{
"called": "go runtime.GC()",
},
); err != nil {
api.logger.Error("failed to send run gc response", zap.String("request.id", requestID), zap.Error(err))
}
}
// FreeOSMemory forces the garbage collector to and tries to returns the memory
// back to the operating system in an asynchronous fashion.
func (api *APIHandler) FreeOSMemory(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
go debug.FreeOSMemory()
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
map[string]string{
"called": "go debug.FreeOSMemory()",
},
); err != nil {
api.logger.Error("failed to send free os memory response", zap.String("request.id", requestID), zap.Error(err))
}
}
// GetStatistics provides useful details about the application to the internal ops users.
// The stats returns by this handler do not contain the ops request which triggered that.
// That is why we remove 1 from the called field value in order to match the status stats.
func (api *APIHandler) GetStatistics(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
api.stats.mu.RLock()
maintenanceModeStartedTime := api.mode.started.String()
if api.mode.started.IsZero() {
maintenanceModeStartedTime = ""
}
err := json.NewEncoder(w).Encode(
map[string]interface{}{
"requestid": requestID,
"app.version": api.stats.version,
"app.container": api.stats.container,
"app.platform": api.stats.platform,
"go.version": api.stats.runtime,
"called": atomic.LoadUint64(&api.stats.called) - 1,
"started": api.stats.started.Format(time.RFC1123),
"uptime": fmt.Sprintf("%.0f mins", api.clock.Now().Sub(api.stats.started).Minutes()),
"maintenance": map[string]interface{}{
"enabled": api.mode.enabled.Load(),
"started": maintenanceModeStartedTime,
"reason": api.mode.reason,
},
"status": api.stats.status,
},
)
api.stats.mu.RUnlock()
if err != nil {
api.logger.Error("failed to send statistics response", zap.String("request.id", requestID), zap.Error(err))
}
}
// GetConfigs serves current in-use configurations/settings.
func (api *APIHandler) GetConfigs(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
map[string]interface{}{
"configs": api.config,
},
); err != nil {
api.logger.Error("failed to send settings response", zap.String("request.id", requestID), zap.Error(err))
}
}
// Maintenance handles request to enable or disable the maintenance mode of the service and respond
// to client requests with predefined message when the service is in maintenance mode.
// Enable the maintenance mode : /ops/maintenance?status=enable&msg=message-to-be-displayed-to-users
// Disable the maintenance mode: /ops/maintenance?status=disable
func (api *APIHandler) Maintenance(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var response map[string]interface{}
var logger *zap.Logger
q := r.URL.Query()
mstatus := "show"
if ps.ByName("status") != mstatus {
mstatus = q.Get("status")
}
switch mstatus {
case "enable":
api.mode.reason = q.Get("msg")
api.mode.started = api.clock.Now()
api.mode.enabled.Store(true)
response = map[string]interface{}{
"requestid": requestID,
"maintenance.started": api.mode.started.Format(time.RFC1123),
"maintenance.reason": api.mode.reason,
"message": "Maintenance mode enabled successfully.",
}
logger = api.logger.With(zap.String("request.id", requestID))
case "disable":
api.mode.enabled.Store(false)
api.mode.started = api.clock.Zero()
api.mode.reason = ""
response = map[string]interface{}{
"requestid": requestID,
"message": "Maintenance mode disabled successfully.",
}
logger = api.logger.With(zap.String("request.id", requestID))
case "show":
response = map[string]interface{}{
"requestid": requestID,
"message": "service currently unvailable.",
"reason": api.mode.reason,
"since": api.mode.started.Format(time.RFC1123),
}
w.WriteHeader(http.StatusServiceUnavailable)
}
if err := json.NewEncoder(w).Encode(response); err != nil {
logger.Error("failed to send maintenance response",
zap.String("request.maintenance", mstatus),
zap.Error(err),
)
}
}
// ClearBooksCache deletes all books entries from the primary storage (cache).
func (api *APIHandler) ClearBooksCache(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
requestID := GetValueFromContext(r.Context(), RequestIDContextKey)
go api.bookService.DeleteAll(r.Context(), requestID)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
if err := json.NewEncoder(w).Encode(
map[string]string{
"requestid": requestID,
"message": "books cache clearing started. check logs every 30 secs based on requestid",
},
); err != nil {
api.logger.Error("failed to send clear books cache response", zap.String("request.id", requestID), zap.Error(err))
}
}
// GetProfilerIndexPage displays pprof index page.
// func (api *APIHandler) GetProfilerIndexPage(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// pprof.Index(w, r)
// }
// GetCPUProfile returns a snapshot of the pprof-formatted CPU profile.
func (api *APIHandler) GetCPUProfile(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
pprof.Profile(w, r)
}
// GetTraceProfile returns the execution trace.
func (api *APIHandler) GetTraceProfile(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
pprof.Trace(w, r)
}
// GetSymbol returns the program symbol from the pprof package.
func (api *APIHandler) GetSymbol(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
pprof.Symbol(w, r)
}
// GetCmdLine returns the program command lines arguments.
func (api *APIHandler) GetCmdLine(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
pprof.Cmdline(w, r)
}