forked from canonical/lxd
/
warnings.go
454 lines (398 loc) · 10.6 KB
/
warnings.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/filter"
"github.com/lxc/lxd/lxd/lifecycle"
"github.com/lxc/lxd/lxd/operations"
"github.com/lxc/lxd/lxd/project"
"github.com/lxc/lxd/lxd/request"
"github.com/lxc/lxd/lxd/response"
"github.com/lxc/lxd/lxd/task"
"github.com/lxc/lxd/shared/api"
log "github.com/lxc/lxd/shared/log15"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/version"
)
var warningsCmd = APIEndpoint{
Path: "warnings",
Get: APIEndpointAction{Handler: warningsGet},
}
var warningCmd = APIEndpoint{
Path: "warnings/{id}",
Get: APIEndpointAction{Handler: warningGet},
Patch: APIEndpointAction{Handler: warningPatch},
Put: APIEndpointAction{Handler: warningPut},
Delete: APIEndpointAction{Handler: warningDelete},
}
func filterWarnings(warnings []api.Warning, clauses []filter.Clause) []api.Warning {
filtered := []api.Warning{}
for _, warning := range warnings {
if !filter.Match(warning, clauses) {
continue
}
filtered = append(filtered, warning)
}
return filtered
}
// swagger:operation GET /1.0/warnings warnings warnings_get
//
// List the warnings
//
// Returns a list of warnings.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// responses:
// "200":
// description: Sync response
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of endpoints
// items:
// type: string
// example: |-
// [
// "/1.0/warnings/39c61a48-cc17-40ae-8248-4f7b4cadedf4",
// "/1.0/warnings/951779a5-2820-4d96-b01e-88fe820e5310"
// ]
// "500":
// $ref: "#/responses/InternalServerError"
// swagger:operation GET /1.0/warnings?recursion=1 warnings warnings_get_recursion1
//
// Get the warnings
//
// Returns a list of warnings (structs).
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of warnings
// items:
// $ref: "#/definitions/Warning"
// "500":
// $ref: "#/responses/InternalServerError"
func warningsGet(d *Daemon, r *http.Request) response.Response {
// Parse the recursion field
recursionStr := r.FormValue("recursion")
recursion, err := strconv.Atoi(recursionStr)
if err != nil {
recursion = 0
}
// Parse filter value
var clauses []filter.Clause
filterStr := r.FormValue("filter")
if filterStr != "" {
clauses, err = filter.Parse(filterStr)
if err != nil {
return response.SmartError(errors.Wrap(err, "Failed to filter warnings"))
}
}
// Parse the project field
projectName := queryParam(r, "project")
var dbWarnings []db.Warning
err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
if projectName != "" {
dbWarnings, err = tx.GetWarningsByProject(projectName)
} else {
dbWarnings, err = tx.GetWarnings()
}
if err != nil {
return errors.Wrap(err, "Failed to get warnings")
}
return nil
})
if err != nil {
return response.SmartError(err)
}
warnings := make([]api.Warning, len(dbWarnings))
for i, w := range dbWarnings {
warning, err := w.ToAPI(d.cluster)
if err != nil {
return response.SmartError(err)
}
warnings[i] = warning
}
if recursion == 0 {
var resultList []string
for _, w := range filterWarnings(warnings, clauses) {
url := fmt.Sprintf("/%s/warnings/%s", version.APIVersion, w.UUID)
resultList = append(resultList, url)
}
return response.SyncResponse(true, resultList)
}
// Return detailed list of warning
return response.SyncResponse(true, filterWarnings(warnings, clauses))
}
// swagger:operation GET /1.0/warnings/{uuid} warnings warning_get
//
// Get the warning
//
// Gets a specific warning.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// description: Warning
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/Warning"
// "404":
// $ref: "#/responses/NotFound"
// "500":
// $ref: "#/responses/InternalServerError"
func warningGet(d *Daemon, r *http.Request) response.Response {
id := mux.Vars(r)["id"]
var dbWarning *db.Warning
var err error
err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
dbWarning, err = tx.GetWarning(id)
if err != nil {
return err
}
return nil
})
if err != nil {
return response.SmartError(err)
}
resp, err := dbWarning.ToAPI(d.cluster)
if err != nil {
return response.SmartError(err)
}
return response.SyncResponse(true, resp)
}
// swagger:operation PATCH /1.0/warnings/{uuid} warnings warning_patch
//
// Partially update the warning
//
// Updates a subset of the warning status.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: warning
// description: Warning status
// required: true
// schema:
// $ref: "#/definitions/WarningPut"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func warningPatch(d *Daemon, r *http.Request) response.Response {
return warningPut(d, r)
}
// swagger:operation PUT /1.0/warnings/{uuid} warnings warning_put
//
// Update the warning
//
// Updates the warning status.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: body
// name: warning
// description: Warning status
// required: true
// schema:
// $ref: "#/definitions/WarningPut"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func warningPut(d *Daemon, r *http.Request) response.Response {
id := mux.Vars(r)["id"]
req := api.WarningPut{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Currently, we only allow changing the status to acknowledged or new.
status, ok := db.WarningStatusTypes[req.Status]
if !ok {
// Invalid status
return response.BadRequest(fmt.Errorf("Invalid warning type %q", req.Status))
}
if status != db.WarningStatusAcknowledged && status != db.WarningStatusNew {
return response.Forbidden(fmt.Errorf(`Status may only be set to "acknowledge" or "new"`))
}
err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
err := tx.UpdateWarningStatus(id, status)
if err != nil {
return err
}
return nil
})
if err != nil {
return response.SmartError(err)
}
if status == db.WarningStatusAcknowledged {
d.State().Events.SendLifecycle(project.Default, lifecycle.WarningAcknowledged.Event(id, request.CreateRequestor(r), nil))
} else {
d.State().Events.SendLifecycle(project.Default, lifecycle.WarningReset.Event(id, request.CreateRequestor(r), nil))
}
return response.EmptySyncResponse
}
// swagger:operation DELETE /1.0/warnings/{uuid} warnings warning_delete
//
// Delete the warning
//
// Removes the warning.
//
// ---
// produces:
// - application/json
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "500":
// $ref: "#/responses/InternalServerError"
func warningDelete(d *Daemon, r *http.Request) response.Response {
id := mux.Vars(r)["id"]
err := d.cluster.Transaction(func(tx *db.ClusterTx) error {
err := tx.DeleteWarning(id)
if err != nil {
return err
}
return nil
})
if err != nil {
return response.SmartError(err)
}
d.State().Events.SendLifecycle(project.Default, lifecycle.WarningDeleted.Event(id, request.CreateRequestor(r), nil))
return response.EmptySyncResponse
}
func pruneResolvedWarningsTask(d *Daemon) (task.Func, task.Schedule) {
f := func(ctx context.Context) {
opRun := func(op *operations.Operation) error {
return pruneResolvedWarnings(ctx, d)
}
op, err := operations.OperationCreate(d.State(), "", operations.OperationClassTask, db.OperationWarningsPruneResolved, nil, nil, opRun, nil, nil, nil)
if err != nil {
logger.Error("Failed to start prune resolved warnings operation", log.Ctx{"err": err})
return
}
logger.Info("Pruning resolved warnings")
_, err = op.Run()
if err != nil {
logger.Error("Failed to prune resolved warnings", log.Ctx{"err": err})
}
logger.Info("Done pruning resolved warnings")
}
return f, task.Daily()
}
func pruneResolvedWarnings(ctx context.Context, d *Daemon) error {
err := d.cluster.Transaction(func(tx *db.ClusterTx) error {
// Retrieve warnings by status
warnings, err := tx.GetWarningsByStatus(db.WarningStatusResolved)
if err != nil {
return errors.Wrap(err, "Failed to get resolved warnings")
}
for _, w := range warnings {
// Delete the warning if it has been resolved for at least 24 hours
if time.Since(w.UpdatedDate) >= 24*time.Hour {
err = tx.DeleteWarning(w.UUID)
if err != nil {
return err
}
}
}
return nil
})
if err != nil {
return errors.Wrap(err, "Failed to delete warnings")
}
return nil
}