-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathserver.go
More file actions
339 lines (290 loc) · 8.9 KB
/
server.go
File metadata and controls
339 lines (290 loc) · 8.9 KB
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
package server
import (
"crypto/tls"
"errors"
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
adminServerJob "github.com/linuxboot/contest/cmds/admin_server/job"
"github.com/linuxboot/contest/cmds/admin_server/storage"
"github.com/linuxboot/contest/pkg/job"
"github.com/linuxboot/contest/pkg/types"
"github.com/linuxboot/contest/pkg/xcontext"
"github.com/linuxboot/contest/pkg/xcontext/logger"
)
var (
MaxPageSize uint = 100
DefaultPage uint = 0
DefaultDBAccessTimeout time.Duration = 10 * time.Second
)
/*
Query should have the same names as the fields in the entity that it queries(in this case Log).
To generalize filtering time fields (range filtering), it should have two fields with prefixes `start_<name>`, `end_<name>`
to make the frontend generate the query programmatically.
e.g. (Log.Date `date` -> Query.StartDate `start_date`, Query.EndDate `end_date`)
*/
type Query struct {
JobID *uint64 `form:"job_id"`
LogData *string `form:"log_data"`
LogLevel *string `form:"log_level"`
StartDate *time.Time `form:"start_date" time_format:"2006-01-02T15:04:05.000Z07:00"`
EndDate *time.Time `form:"end_date" time_format:"2006-01-02T15:04:05.000Z07:00"`
PageSize *uint `form:"page_size"`
Page *uint `form:"page"`
}
// toStorageQurey returns a storage Query and populates the required fields
func (q *Query) ToStorageQuery() storage.Query {
storageQuery := storage.Query{
Page: DefaultPage,
PageSize: MaxPageSize,
}
storageQuery.JobID = q.JobID
storageQuery.LogData = q.LogData
storageQuery.LogLevel = q.LogLevel
storageQuery.StartDate = q.StartDate
storageQuery.EndDate = q.EndDate
if q.Page != nil {
storageQuery.Page = *q.Page
}
if q.PageSize != nil && *q.PageSize < MaxPageSize {
storageQuery.PageSize = *q.PageSize
}
return storageQuery
}
type Log struct {
JobID uint64 `json:"job_id" filter:"uint"`
LogData string `json:"log_data" filter:"string"`
Date time.Time `json:"date" filter:"time"`
LogLevel string `json:"log_level" filter:"enum" values:"info,debug,error,fatal,panic,warning"`
}
func (l *Log) ToStorageLog() storage.Log {
return storage.Log{
JobID: l.JobID,
LogData: l.LogData,
Date: l.Date,
LogLevel: l.LogLevel,
}
}
func toServerLog(l *storage.Log) Log {
return Log{
JobID: l.JobID,
LogData: l.LogData,
Date: l.Date,
LogLevel: l.LogLevel,
}
}
type Result struct {
Logs []Log `json:"logs"`
Count uint64 `json:"count"`
Page uint `json:"page"`
PageSize uint `json:"page_size"`
}
func toServerResult(r *storage.Result) Result {
var result Result
result.Count = r.Count
result.Page = r.Page
result.PageSize = r.PageSize
for _, log := range r.Logs {
result.Logs = append(result.Logs, toServerLog(&log))
}
return result
}
type Tag struct {
Name string `json:"name"`
JobsCount uint `json:"jobs_count"`
}
func fromStorageTags(storageTags []adminServerJob.Tag) []Tag {
tags := make([]Tag, 0, len(storageTags))
for _, tag := range storageTags {
tags = append(tags, Tag{
Name: tag.Name,
JobsCount: tag.JobsCount,
})
}
return tags
}
type report struct {
ReporterName string `json:"reporter_name"`
Success *bool `json:"success"`
Time *time.Time `json:"time"`
Data *string `json:"data"`
}
type Job struct {
JobID types.JobID `json:"job_id"`
Report *report `json:"report"`
}
func fromStorageJobs(storageJobs []adminServerJob.Job) []Job {
jobs := make([]Job, 0, len(storageJobs))
for _, job := range storageJobs {
var r *report
if job.ReporterName != nil {
r = &report{
ReporterName: *job.ReporterName,
Success: job.Success,
Time: job.ReportTime,
Data: job.Data,
}
}
jobs = append(jobs, Job{
JobID: job.JobID,
Report: r,
})
}
return jobs
}
type RouteHandler struct {
storage storage.Storage
jobStorage adminServerJob.Storage
log logger.Logger
}
// status is a simple endpoint to check if the serves is alive
func (r *RouteHandler) status(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "live"})
}
//
func (r *RouteHandler) describeLog(c *gin.Context) {
res, err := DescribeEntity(Log{})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "err", "msg": "error while getting the storage descirbtion"})
return
}
c.JSON(http.StatusOK, res)
}
// addLogs inserts log's batches into the database
func (r *RouteHandler) addLogs(c *gin.Context) {
var logs []Log
if err := c.Bind(&logs); err != nil {
c.JSON(http.StatusBadRequest, makeRestErr("badly formatted logs"))
r.log.Errorf("Err while binding request body %v", err)
return
}
storageLogs := make([]storage.Log, 0, len(logs))
for _, log := range logs {
storageLogs = append(storageLogs, log.ToStorageLog())
}
ctx, cancel := xcontext.WithTimeout(xcontext.Background(), DefaultDBAccessTimeout)
defer cancel()
ctx = ctx.WithLogger(r.log)
err := r.storage.StoreLogs(ctx, storageLogs)
if err != nil {
r.log.Errorf("Err while storing logs: %v", err)
switch {
case errors.Is(err, storage.ErrInsert):
c.JSON(http.StatusInternalServerError, makeRestErr("error while storing the batch"))
case errors.Is(err, storage.ErrReadOnlyStorage):
c.JSON(http.StatusNotImplemented, makeRestErr("not supported action"))
default:
c.JSON(http.StatusInternalServerError, makeRestErr("unknown server error"))
}
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
// geLogs gets logs form the db based on the filters
func (r *RouteHandler) getLogs(c *gin.Context) {
var query Query
if err := c.BindQuery(&query); err != nil {
c.JSON(http.StatusBadRequest, makeRestErr("bad formatted query %v", err))
r.log.Errorf("Err while binding request body %v", err)
return
}
ctx, cancel := xcontext.WithTimeout(xcontext.Background(), DefaultDBAccessTimeout)
defer cancel()
ctx = ctx.WithLogger(r.log)
result, err := r.storage.GetLogs(ctx, query.ToStorageQuery())
if err != nil {
c.JSON(http.StatusInternalServerError, makeRestErr("error while getting the logs"))
r.log.Errorf("Err while getting logs from storage: %v", err)
return
}
c.JSON(http.StatusOK, toServerResult(result))
}
// getTags gets the tags with similar name to text
func (r *RouteHandler) getTags(c *gin.Context) {
var query struct {
Text string `form:"text"`
}
if err := c.BindQuery(&query); err != nil {
c.JSON(http.StatusBadRequest, makeRestErr("bad formatted query %v", err))
r.log.Errorf("Err while binding request body %v", err)
return
}
ctx, cancel := xcontext.WithTimeout(xcontext.Background(), DefaultDBAccessTimeout)
defer cancel()
ctx = ctx.WithLogger(r.log)
res, err := r.jobStorage.GetTags(ctx, query.Text)
if err != nil {
c.JSON(http.StatusInternalServerError, makeRestErr("error while getting the projects"))
return
}
c.JSON(http.StatusOK, fromStorageTags(res))
}
// getJobs gets the jobs with final report -if it exists- under a given project name as a url parameter
func (r *RouteHandler) getJobs(c *gin.Context) {
projectName := c.Param("name")
if err := job.CheckTags([]string{projectName}, false); err != nil {
c.JSON(http.StatusBadRequest, makeRestErr("bad formatted job tag %v", err))
return
}
ctx, cancel := xcontext.WithTimeout(xcontext.Background(), DefaultDBAccessTimeout)
defer cancel()
ctx = ctx.WithLogger(r.log)
res, err := r.jobStorage.GetJobs(ctx, projectName)
if err != nil {
c.JSON(http.StatusInternalServerError, makeRestErr("error while getting the jobs"))
return
}
c.JSON(http.StatusOK, fromStorageJobs(res))
}
func makeRestErr(format string, args ...any) gin.H {
return gin.H{"status": "err", "msg": fmt.Sprintf(format, args...)}
}
func initRouter(ctx xcontext.Context, rh RouteHandler, middlewares []gin.HandlerFunc) *gin.Engine {
r := gin.New()
r.Use(gin.Logger())
// add the middlewares
for _, hf := range middlewares {
r.Use(hf)
}
r.GET("/status", rh.status)
r.POST("/log", rh.addLogs)
r.GET("/log", rh.getLogs)
r.GET("/tag", rh.getTags)
r.GET("/tag/:name/jobs", rh.getJobs)
r.GET("/log-description", rh.describeLog)
// serve the frontend app
r.StaticFS("/app", FS(false))
return r
}
func Serve(ctx xcontext.Context, port int, storage storage.Storage, jobStorage adminServerJob.Storage, middlewares []gin.HandlerFunc, tlsConfig *tls.Config) error {
routeHandler := RouteHandler{
storage: storage,
jobStorage: jobStorage,
log: ctx.Logger(),
}
router := initRouter(ctx, routeHandler, middlewares)
server := &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: router,
TLSConfig: tlsConfig,
}
go func() {
<-ctx.Done()
// on cancel close the server
ctx.Debugf("Closing the server")
if err := server.Close(); err != nil {
ctx.Errorf("Error closing the server: %v", err)
}
}()
var err error
if tlsConfig != nil {
err = server.ListenAndServeTLS("", "")
} else {
err = server.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
return err
}
return ctx.Err()
}