-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.go
424 lines (374 loc) · 12.1 KB
/
service.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package admin
import (
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
adminapi "github.com/airenas/api-doorman/internal/pkg/admin/api"
"github.com/airenas/api-doorman/internal/pkg/integration/cms"
"github.com/airenas/api-doorman/internal/pkg/mongodb"
"github.com/airenas/api-doorman/internal/pkg/utils"
"github.com/airenas/go-app/pkg/goapp"
"github.com/facebookgo/grace/gracehttp"
"github.com/labstack/echo-contrib/prometheus"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
type (
// KeyCreator creates key
KeyCreator interface {
Create(string, *adminapi.Key) (*adminapi.Key, error)
}
// KeyUpdater creates key
KeyUpdater interface {
Update(string, string, map[string]interface{}) (*adminapi.Key, error)
}
// UsageRestorer restores key usage by requestID
UsageRestorer interface {
RestoreUsage(project string, manual bool, request string, errorMsg string) error
}
// KeyRetriever gets keys list from db
KeyRetriever interface {
List(string) ([]*adminapi.Key, error)
}
// OneKeyRetriever retrieves one list from db
OneKeyRetriever interface {
Get(string, string) (*adminapi.Key, error)
}
// LogRetriever retrieves one list from db
LogProvider interface {
Get(string, string) ([]*adminapi.Log, error)
List(string, time.Time) ([]*adminapi.Log, error)
Delete(string, time.Time) (int, error)
}
// UsageReseter resets montly usage
UsageReseter interface {
Reset(ctx context.Context, project string, since time.Time, limit float64) error
}
// PrValidator validates if project is available
PrValidator interface {
Check(string) bool
Projects() []string
}
//Data is service operation data
Data struct {
Port int
KeySaver KeyCreator
KeyGetter KeyRetriever
OneKeyGetter OneKeyRetriever
LogProvider LogProvider
OneKeyUpdater KeyUpdater
UsageRestorer UsageRestorer
UsageReseter UsageReseter
ProjectValidator PrValidator
CmsData *cms.Data
}
)
// StartWebServer starts the HTTP service and listens for the admin requests
func StartWebServer(data *Data) error {
goapp.Log.Infof("Starting HTTP doorman admin service at %d", data.Port)
e := initRoutes(data)
portStr := strconv.Itoa(data.Port)
e.Server.Addr = ":" + portStr
e.Server.IdleTimeout = 3 * time.Minute
e.Server.ReadHeaderTimeout = 10 * time.Second
e.Server.ReadTimeout = 20 * time.Second
e.Server.WriteTimeout = 60 * time.Second
w := goapp.Log.Writer()
defer w.Close()
gracehttp.SetLogger(log.New(w, "", 0))
return gracehttp.Serve(e.Server)
}
var promMdlw *prometheus.Prometheus
func init() {
promMdlw = prometheus.NewPrometheus("doorman_admin", nil)
}
func initRoutes(data *Data) *echo.Echo {
e := echo.New()
promMdlw.Use(e)
e.GET("/live", live(data))
e.GET("/:project/key-list", keyList(data))
e.GET("/:project/key/:key", keyInfo(data))
e.POST("/:project/key", keyAdd(data))
e.PATCH("/:project/key/:key", keyUpdate(data))
e.POST("/:project/restore/:requestID", restore(data))
e.POST("/:project/reset", reset(data))
e.GET("/:project/log", logList(data))
e.DELETE("/:project/log", logDelete(data))
cms.InitRoutes(e, data.CmsData)
goapp.Log.Info("Routes:")
for _, r := range e.Routes() {
goapp.Log.Infof(" %s %s", r.Method, r.Path)
}
return e
}
func keyAdd(data *Data) func(echo.Context) error {
return func(c echo.Context) error {
defer goapp.Estimate("Service method: " + c.Path())()
project := c.Param("project")
if err := validateProject(project, data.ProjectValidator); err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
var input adminapi.Key
if err := utils.TakeJSONInput(c, &input); err != nil {
goapp.Log.Error(err)
return err
}
if input.Limit < 0.1 {
goapp.Log.Error("no limit")
return echo.NewHTTPError(http.StatusBadRequest, "no limit")
}
if input.ValidTo == nil || input.ValidTo.Before(time.Now()) {
goapp.Log.Error("wrong valid to")
return echo.NewHTTPError(http.StatusBadRequest, "wrong valid to")
}
keyResp, err := data.KeySaver.Create(project, &input)
if err != nil {
goapp.Log.Error("can't create key. ", err)
if mongodb.IsDuplicate(err) {
return echo.NewHTTPError(http.StatusBadRequest, "duplicate key")
} else if errors.Is(err, adminapi.ErrWrongField) {
return echo.NewHTTPError(http.StatusBadRequest, "wrong field. "+err.Error())
} else {
return echo.NewHTTPError(http.StatusInternalServerError)
}
}
return c.JSON(http.StatusOK, keyResp)
}
}
func keyList(data *Data) func(echo.Context) error {
return func(c echo.Context) error {
defer goapp.Estimate("Service method: " + c.Path())()
project := c.Param("project")
if err := validateProject(project, data.ProjectValidator); err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
keyResp, err := data.KeyGetter.List(project)
if err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
return c.JSON(http.StatusOK, keyResp)
}
}
func logList(data *Data) func(echo.Context) error {
return func(c echo.Context) error {
defer goapp.Estimate("Service method: " + c.Path())()
project := c.Param("project")
if err := validateProject(project, data.ProjectValidator); err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
to, err := utils.ParseDateParam(c.QueryParam("to"))
if err != nil {
return err
}
if to == nil {
return echo.NewHTTPError(http.StatusBadRequest, "no 'to' query param")
}
res, err := data.LogProvider.List(project, *to)
if err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
return c.JSON(http.StatusOK, res)
}
}
func logDelete(data *Data) func(echo.Context) error {
return func(c echo.Context) error {
defer goapp.Estimate("Service method: " + c.Path())()
project := c.Param("project")
if err := validateProject(project, data.ProjectValidator); err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
to, err := utils.ParseDateParam(c.QueryParam("to"))
if err != nil {
return err
}
if to == nil {
return echo.NewHTTPError(http.StatusBadRequest, "no 'to' query param")
}
deleted, err := data.LogProvider.Delete(project, *to)
if err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
return c.JSONBlob(http.StatusOK, []byte(fmt.Sprintf(`{"deleted":%d}`, deleted)))
}
}
func keyInfo(data *Data) func(echo.Context) error {
return func(c echo.Context) error {
defer goapp.Estimate("Service method: " + c.Path())()
key := c.Param("key")
if key == "" {
goapp.Log.Error("no key")
return echo.NewHTTPError(http.StatusBadRequest, "no key")
}
project := c.Param("project")
if err := validateProject(project, data.ProjectValidator); err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
res := &adminapi.KeyInfoResp{}
var err error
res.Key, err = data.OneKeyGetter.Get(project, key)
if errors.Is(err, adminapi.ErrNoRecord) {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, "key not found")
}
if err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
if c.QueryParam("full") == "1" {
res.Logs, err = data.LogProvider.Get(project, key)
if err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
if res.Key.KeyID != "" {
logsByKeyID, err := data.LogProvider.Get(project, res.Key.KeyID)
if err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
res.Logs = append(res.Logs, logsByKeyID...)
}
}
return c.JSON(http.StatusOK, res)
}
}
func keyUpdate(data *Data) func(echo.Context) error {
return func(c echo.Context) error {
defer goapp.Estimate("Service method: " + c.Path())()
key := c.Param("key")
if key == "" {
goapp.Log.Error("no key")
return echo.NewHTTPError(http.StatusBadRequest, "no key")
}
project := c.Param("project")
if err := validateProject(project, data.ProjectValidator); err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
input := make(map[string]interface{})
if err := utils.TakeJSONInput(c, &input); err != nil {
goapp.Log.Error(err)
return err
}
keyResp, err := data.OneKeyUpdater.Update(project, key, input)
if errors.Is(err, adminapi.ErrNoRecord) {
goapp.Log.Error("key not found. ", err)
return echo.NewHTTPError(http.StatusBadRequest, "key not found")
} else if errors.Is(err, adminapi.ErrWrongField) {
goapp.Log.Error("wrong field. ", err)
return echo.NewHTTPError(http.StatusBadRequest, "wrong field. "+err.Error())
} else if err != nil {
goapp.Log.Error("can't update key. ", err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
return c.JSON(http.StatusOK, keyResp)
}
}
type restoreReq struct {
Error string `json:"error,omitempty"`
}
func restore(data *Data) func(echo.Context) error {
return func(c echo.Context) error {
defer goapp.Estimate("Service method: " + c.Path())()
rStr := c.Param("requestID")
if rStr == "" {
goapp.Log.Error("no requestID")
return echo.NewHTTPError(http.StatusBadRequest, "no requestID")
}
rID, manual, err := parseRequestID(rStr)
if err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, "wrong requestID format")
}
project := c.Param("project")
if err := validateProject(project, data.ProjectValidator); err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
input := restoreReq{}
if err := utils.TakeJSONInput(c, &input); err != nil {
goapp.Log.Error(err)
return err
}
err = data.UsageRestorer.RestoreUsage(project, manual, rID, input.Error)
if errors.Is(err, adminapi.ErrNoRecord) {
goapp.Log.Error("log not found. ", err)
return echo.NewHTTPError(http.StatusBadRequest, "requestID not found")
} else if errors.Is(err, adminapi.ErrLogRestored) {
goapp.Log.Error("already restored. ", err)
return echo.NewHTTPError(http.StatusConflict, "already restored")
} else if err != nil {
goapp.Log.Error("can't restore requestID usage. ", err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
return c.NoContent(http.StatusOK)
}
}
func reset(data *Data) func(echo.Context) error {
return func(c echo.Context) error {
defer goapp.Estimate("Service method: " + c.Path())()
project := c.Param("project")
if err := validateProject(project, data.ProjectValidator); err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
qStr := c.Param("quota")
if qStr == "" {
goapp.Log.Error("no quota")
return echo.NewHTTPError(http.StatusBadRequest, "no quota")
}
quota, err := strconv.ParseFloat(qStr, 64)
if err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, "wrong quota '%s'", qStr)
}
since, err := utils.ParseDateParam(c.Param("since"))
if err != nil {
goapp.Log.Error(err)
return echo.NewHTTPError(http.StatusBadRequest, "wrong since '%s'", qStr)
}
if since == nil {
goapp.Log.Error("no since")
return echo.NewHTTPError(http.StatusBadRequest, "no since")
}
err = data.UsageReseter.Reset(c.Request().Context(), project, *since, quota)
if err != nil {
goapp.Log.Errorf("reset usage: %v ", err)
return echo.NewHTTPError(http.StatusInternalServerError)
}
return c.NoContent(http.StatusOK)
}
}
func parseRequestID(rStr string) (string, bool, error) {
strs := strings.Split(rStr, ":")
if len(strs) != 2 {
return "", false, errors.Errorf("wrong request format %s, wanted 'manual:rID'", rStr)
}
return strs[1], strs[0] == "m", nil
}
func validateProject(project string, prV PrValidator) error {
if project == "" {
return errors.New("no project")
}
if !prV.Check(project) {
return errors.Errorf("wrong project %s", project)
}
return nil
}
func live(data *Data) func(echo.Context) error {
return func(c echo.Context) error {
return c.JSONBlob(http.StatusOK, []byte(`{"service":"OK"}`))
}
}