-
Notifications
You must be signed in to change notification settings - Fork 28
/
maintainer.go
608 lines (550 loc) · 25 KB
/
maintainer.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
/*
* Copyright 2018 The Service Manager Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package operations
import (
"context"
"fmt"
"sync"
"time"
"github.com/Peripli/service-manager/pkg/log"
"github.com/Peripli/service-manager/pkg/query"
"github.com/Peripli/service-manager/pkg/types"
"github.com/Peripli/service-manager/pkg/util"
"github.com/Peripli/service-manager/storage"
)
const (
initialOperationsLockIndex = 200
ZeroTime = "0001-01-01 00:00:00+00"
)
// maintainerFunctor represents a named maintainer function which runs over a pre-defined period
type maintainerFunctor struct {
name string
interval time.Duration
execute func()
}
// Maintainer ensures that operations old enough are deleted
// and that no orphan operations are left in the DB due to crashes/restarts of SM
type Maintainer struct {
smCtx context.Context
repository storage.TransactionalRepository
scheduler *Scheduler
cascadePollingScheduler *Scheduler
settings *Settings
wg *sync.WaitGroup
functors []maintainerFunctor
operationLockers map[string]storage.Locker
}
// NewMaintainer constructs a Maintainer
func NewMaintainer(smCtx context.Context, repository storage.TransactionalRepository, lockerCreatorFunc storage.LockerCreatorFunc, options *Settings, wg *sync.WaitGroup) *Maintainer {
maintainer := &Maintainer{
smCtx: smCtx,
repository: repository,
scheduler: NewScheduler(smCtx, repository, options, options.DefaultPoolSize, wg),
cascadePollingScheduler: NewScheduler(smCtx, repository, options, options.DefaultCascadePollingPoolSize, wg),
settings: options,
wg: wg,
}
maintainer.functors = []maintainerFunctor{
{
name: "cleanupExternalOperations",
execute: maintainer.cleanupExternalOperations,
interval: options.CleanupInterval,
},
{
name: "cleanupInternalSuccessfulOperations",
execute: maintainer.cleanupInternalSuccessfulOperations,
interval: options.CleanupInterval,
},
{
name: "cleanupInternalFailedOperations",
execute: maintainer.cleanupInternalFailedOperations,
interval: options.CleanupInterval,
},
{
name: "cleanupFinishedCascadeOperations",
execute: maintainer.CleanupFinishedCascadeOperations,
interval: options.CleanupInterval,
},
{
name: "pollUpdateCascadeOperations",
execute: maintainer.PollUpdateCascadeOperations,
interval: options.PollCascadeInterval,
},
{
name: "cleanupResourcelessOperations",
execute: maintainer.CleanupResourcelessOperations,
interval: options.CleanupInterval,
},
{
name: "pollPendingCascadeOperations",
execute: maintainer.pollPendingCascadeOperations,
interval: options.PollCascadeInterval,
},
{
name: "markStuckOperationsFailed",
execute: maintainer.markStuckOperationsFailed,
interval: options.MaintainerRetryInterval,
},
{
name: "rescheduleUnfinishedOperations",
execute: maintainer.rescheduleUnfinishedOperations,
interval: options.MaintainerRetryInterval,
},
{
name: "rescheduleOrphanMitigationOperations",
execute: maintainer.rescheduleOrphanMitigationOperations,
interval: options.MaintainerRetryInterval,
},
}
operationLockers := make(map[string]storage.Locker)
advisoryLockStartIndex := initialOperationsLockIndex
for _, functor := range maintainer.functors {
operationLockers[functor.name] = lockerCreatorFunc(advisoryLockStartIndex)
advisoryLockStartIndex++
}
maintainer.operationLockers = operationLockers
return maintainer
}
// Run starts the two recurring jobs responsible for cleaning up operations which are too old
// and deleting orphan operations
func (om *Maintainer) Run() {
for _, functor := range om.functors {
functor := functor
maintainerFunc := func() {
log.C(om.smCtx).Debugf("Attempting to retrieve lock for maintainer functor (%s)", functor.name)
err := om.operationLockers[functor.name].TryLock(om.smCtx)
if err != nil {
log.C(om.smCtx).Debugf("Failed to retrieve lock for maintainer functor (%s): %s", functor.name, err)
return
}
defer func() {
if err := om.operationLockers[functor.name].Unlock(om.smCtx); err != nil {
log.C(om.smCtx).Warnf("Could not unlock for maintainer functor (%s): %s", functor.name, err)
}
}()
log.C(om.smCtx).Debugf("Successfully retrieved lock for maintainer functor (%s)", functor.name)
functor.execute()
}
go maintainerFunc()
go om.processOperations(maintainerFunc, functor.name, functor.interval)
}
}
func (om *Maintainer) processOperations(functor func(), functorName string, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
func() {
om.wg.Add(1)
defer om.wg.Done()
log.C(om.smCtx).Debugf("Starting execution of maintainer functor (%s)", functorName)
functor()
log.C(om.smCtx).Debugf("Finished execution of maintainer functor (%s)", functorName)
}()
case <-om.smCtx.Done():
ticker.Stop()
log.C(om.smCtx).Info("Server is shutting down. Stopping operations maintainer...")
return
}
}
}
// cleanUpExternalOperations cleans up periodically all external operations which are older than some specified time
func (om *Maintainer) cleanupExternalOperations() {
currentTime := time.Now()
criteria := []query.Criterion{
query.ByField(query.NotEqualsOperator, "platform_id", types.SMPlatform),
// check if operation hasn't been updated for the operation's maximum allowed time to live in DB
query.ByField(query.LessThanOperator, "updated_at", util.ToRFCNanoFormat(currentTime.Add(-om.settings.Lifespan))),
query.ByNotExists(storage.GetSubQuery(storage.QueryForAllLastOperationsPerResource)),
}
if err := om.repository.Delete(om.smCtx, types.OperationType, criteria...); err != nil && err != util.ErrNotFoundInStorage {
log.C(om.smCtx).Debugf("Failed to cleanup operations: %s", err)
return
}
log.C(om.smCtx).Debug("Finished cleaning up external operations")
}
func (om *Maintainer) PollUpdateCascadeOperations() {
rootsCriteria := []query.Criterion{
query.ByField(query.EqualsOperator, "platform_id", types.SMPlatform),
query.ByField(query.EqualsOperator, "type", string(types.UPDATE)),
query.ByField(query.EqualsOperator, "state", string(types.IN_PROGRESS)),
query.ByField(query.EqualsOrNilOperator, "parent_id", ""),
query.ByField(query.NotEqualsOperator, "cascade_root_id", ""),
}
roots, err := om.repository.List(om.smCtx, types.OperationType, rootsCriteria...)
if err != nil {
log.C(om.smCtx).Debugf("Failed to fetch finished cascade operations: %s", err)
return
}
for i := 0; i < roots.Len(); i++ {
root := roots.ItemAt(i).(*types.Operation)
logger := log.C(om.smCtx).WithField(log.FieldCorrelationID, root.CorrelationID)
subOperations, err := GetSubOperations(om.smCtx, root, om.repository)
if err != nil {
log.C(om.smCtx).Debugf("Failed to get sub operations: %s", err)
return
}
byRootID := query.ByField(query.EqualsOperator, "cascade_root_id", root.GetID())
if len(subOperations.FailedOperations) > 0 && len(subOperations.FailedOperations)+len(subOperations.SucceededOperations) == subOperations.AllOperationsCount {
errorsJson, err := PrepareAggregatedErrorsArray(subOperations.FailedOperations, root.ResourceID, root.ResourceType)
if err != nil {
logger.Errorf("Couldn't aggregate errors for failed operation with id %s: %s", root.ResourceID, err)
}
root.Errors = errorsJson
root.State = types.FAILED
if _, err := om.repository.Update(om.smCtx, root, nil, byRootID); err != nil && err != util.ErrNotFoundInStorage {
log.C(om.smCtx).Errorf("Failed to update root operation: %s", err)
}
log.C(om.smCtx).Debug("Finished updating a cascade update operation state")
}
if len(subOperations.SucceededOperations) == subOperations.AllOperationsCount {
root.State = types.SUCCEEDED
if _, err := om.repository.Update(om.smCtx, root, nil, byRootID); err != nil && err != util.ErrNotFoundInStorage {
log.C(om.smCtx).Errorf("Failed to cleanup an instance update root operation: %s", err)
}
log.C(om.smCtx).Debug("Finished updating a cascade update operation state")
}
}
}
// cleanupFinishedCascadeOperations cleans up all successful/failed internal cascade operations which are older than some specified time
func (om *Maintainer) CleanupFinishedCascadeOperations() {
currentTime := time.Now()
rootsCriteria := []query.Criterion{
query.ByField(query.EqualsOperator, "platform_id", types.SMPlatform),
query.ByField(query.EqualsOrNilOperator, "parent_id", ""),
query.ByField(query.NotEqualsOperator, "cascade_root_id", ""),
query.ByField(query.InOperator, "state", string(types.SUCCEEDED), string(types.FAILED)),
// check if operation hasn't been updated for the operation's maximum allowed time to live in DB//
query.ByField(query.LessThanOperator, "updated_at", util.ToRFCNanoFormat(currentTime.Add(-om.settings.Lifespan))),
query.ByNotExists(storage.GetSubQuery(storage.QueryForAllLastOperationsPerResource)),
}
roots, err := om.repository.List(om.smCtx, types.OperationType, rootsCriteria...)
if err != nil {
log.C(om.smCtx).Debugf("Failed to fetch finished cascade operations: %s", err)
return
}
for i := 0; i < roots.Len(); i++ {
root := roots.ItemAt(i)
byRootID := query.ByField(query.EqualsOperator, "cascade_root_id", root.GetID())
if err := om.repository.Delete(om.smCtx, types.OperationType, byRootID); err != nil && err != util.ErrNotFoundInStorage {
log.C(om.smCtx).Errorf("Failed to cleanup cascade operations: %s", err)
}
}
log.C(om.smCtx).Debug("Finished cleaning up successful cascade operations")
}
// cleanupInternalCascadeOperations cleans up all finished internal cascade operations which are older than some specified time
func (om *Maintainer) cleanupInternalSuccessfulOperations() {
currentTime := time.Now()
criteria := []query.Criterion{
query.ByField(query.EqualsOperator, "platform_id", types.SMPlatform),
query.ByField(query.EqualsOperator, "state", string(types.SUCCEEDED)),
// ignore cascade operations
query.ByField(query.EqualsOrNilOperator, "cascade_root_id", ""),
// check if operation hasn't been updated for the operation's maximum allowed time to live in DB
query.ByField(query.LessThanOperator, "updated_at", util.ToRFCNanoFormat(currentTime.Add(-om.settings.Lifespan))),
query.ByNotExists(storage.GetSubQuery(storage.QueryForAllLastOperationsPerResource)),
}
if err := om.repository.Delete(om.smCtx, types.OperationType, criteria...); err != nil && err != util.ErrNotFoundInStorage {
log.C(om.smCtx).Debugf("Failed to cleanup operations: %s", err)
return
}
log.C(om.smCtx).Debug("Finished cleaning up successful internal operations")
}
// cleanupInternalFailedOperations cleans up all failed internal operations which are older than some specified time
func (om *Maintainer) cleanupInternalFailedOperations() {
currentTime := time.Now()
criteria := []query.Criterion{
query.ByField(query.EqualsOperator, "platform_id", types.SMPlatform),
query.ByField(query.EqualsOperator, "state", string(types.FAILED)),
query.ByField(query.EqualsOperator, "reschedule", "false"),
query.ByField(query.EqualsOperator, "deletion_scheduled", ZeroTime),
// ignore cascade operations
query.ByField(query.EqualsOrNilOperator, "cascade_root_id", ""),
// check if operation hasn't been updated for the operation's maximum allowed time to live in DB
query.ByField(query.LessThanOperator, "updated_at", util.ToRFCNanoFormat(currentTime.Add(-om.settings.Lifespan))),
query.ByNotExists(storage.GetSubQuery(storage.QueryForAllLastOperationsPerResource)),
}
if err := om.repository.Delete(om.smCtx, types.OperationType, criteria...); err != nil && err != util.ErrNotFoundInStorage {
log.C(om.smCtx).Debugf("Failed to cleanup operations: %s", err)
return
}
log.C(om.smCtx).Debug("Finished cleaning up failed internal operations")
}
func (om *Maintainer) CleanupResourcelessOperations() {
currentTime := time.Now()
criteria := []query.Criterion{
// check if operation hasn't been updated for the operation's maximum allowed time to live in DB
query.ByField(query.LessThanOperator, "updated_at", util.ToRFCNanoFormat(currentTime.Add(-om.settings.Lifespan))),
}
// Build the 'WHERE' clause of the deletion statement with 'byIdNotExist' criterion for each resource table.
for _, entity := range om.repository.GetEntities() {
if entity.TableName == "operations" {
continue
}
params := storage.SubQueryParams{
"RESOURCE_TABLE": entity.TableName,
}
subQuery, err := storage.GetSubQueryWithParams(storage.QueryForOperationsWithResource, params)
if err != nil {
log.C(om.smCtx).Debugf(
"Failed resolving template parameters for sub-query: %v. Error: %v",
storage.QueryForOperationsWithResource,
err)
}
byIDNotExistCriterion := query.ByNotExists(subQuery)
criteria = append(criteria, byIDNotExistCriterion)
}
if err := om.repository.Delete(om.smCtx, types.OperationType, criteria...); err != nil && err != util.ErrNotFoundInStorage {
log.C(om.smCtx).Debugf("Failed to cleanup operations: %s", err)
return
}
log.C(om.smCtx).Debug("Finished cleaning up resource-less operations")
}
// rescheduleUnfinishedOperations reschedules IN_PROGRESS operations which are reschedulable, not scheduled for deletion and no goroutine is processing at the moment
func (om *Maintainer) rescheduleUnfinishedOperations() {
currentTime := time.Now()
criteria := []query.Criterion{
query.ByField(query.EqualsOperator, "platform_id", types.SMPlatform),
query.ByField(query.EqualsOperator, "state", string(types.IN_PROGRESS)),
query.ByField(query.EqualsOperator, "reschedule", "true"),
query.ByField(query.EqualsOperator, "deletion_scheduled", ZeroTime),
// check if operation hasn't been updated for the operation's maximum allowed time to execute
query.ByField(query.LessThanOperator, "updated_at", util.ToRFCNanoFormat(currentTime.Add(-om.settings.ActionTimeout))),
}
objectList, err := om.repository.List(om.smCtx, types.OperationType, criteria...)
if err != nil {
log.C(om.smCtx).Debugf("Failed to fetch unprocessed operations: %s", err)
return
}
operations := objectList.(*types.Operations)
for i := 0; i < operations.Len(); i++ {
operation := operations.ItemAt(i).(*types.Operation)
logger := log.C(om.smCtx).WithField(log.FieldCorrelationID, operation.CorrelationID)
ctx := log.ContextWithLogger(om.smCtx, logger)
var action storageAction
switch operation.Type {
case types.CREATE:
object, err := om.repository.Get(ctx, operation.ResourceType, query.ByField(query.EqualsOperator, "id", operation.ResourceID))
if err != nil {
logger.Warnf("Failed to fetch resource with ID (%s) for operation with ID (%s): %s", operation.ResourceID, operation.ID, err)
break
}
action = func(ctx context.Context, repository storage.Repository) (types.Object, error) {
object, err := repository.Create(ctx, object)
return object, util.HandleStorageError(err, operation.ResourceType.String())
}
case types.UPDATE:
byID := query.ByField(query.EqualsOperator, "id", operation.ResourceID)
object, err := om.repository.Get(ctx, operation.ResourceType, byID)
if err != nil {
logger.Warnf("Failed to fetch resource with ID (%s) for operation with ID (%s): %s", operation.ResourceID, operation.ID, err)
break
}
action = func(ctx context.Context, repository storage.Repository) (types.Object, error) {
object, err := repository.Update(ctx, object, nil, byID)
return object, util.HandleStorageError(err, operation.ResourceType.String())
}
case types.DELETE:
byID := query.ByField(query.EqualsOperator, "id", operation.ResourceID)
action = func(ctx context.Context, repository storage.Repository) (types.Object, error) {
err := repository.Delete(ctx, operation.ResourceType, byID)
if err != nil {
if err == util.ErrNotFoundInStorage {
return nil, nil
}
return nil, util.HandleStorageError(err, operation.ResourceType.String())
}
return nil, nil
}
}
if err := om.scheduler.ScheduleAsyncStorageAction(ctx, operation, action); err != nil {
logger.Warnf("Failed to reschedule unprocessed operation with ID (%s): %s", operation.ID, err)
}
logger.Debugf("Successfully rescheduled unfinished operation %+v", operation)
}
}
func (om *Maintainer) pollPendingCascadeOperations() {
criteria := []query.Criterion{
query.ByField(query.NotEqualsOperator, "cascade_root_id", ""),
query.ByField(query.EqualsOperator, "type", string(types.DELETE)),
query.ByField(query.EqualsOperator, "state", string(types.PENDING)),
}
operations, err := om.repository.List(om.smCtx, types.OperationType, criteria...)
if err != nil {
log.C(om.smCtx).Errorf("Failed to fetch cascaded operations in progress: %s", err)
return
}
skipSameResourcesForCurrentIteration := make(map[string]bool)
operations = operations.(*types.Operations)
for i := 0; i < operations.Len(); i++ {
operation := operations.ItemAt(i).(*types.Operation)
if skipSameResourcesForCurrentIteration[operation.ResourceID] {
continue
}
logger := log.C(om.smCtx).WithField(log.FieldCorrelationID, operation.CorrelationID)
ctx := log.ContextWithLogger(om.smCtx, logger)
subOperations, err := GetSubOperations(ctx, operation, om.repository)
if err != nil {
logger.Errorf("Failed to retrieve children of the operation with ID (%s): %s", operation.ID, err)
continue
}
if subOperations.AllOperationsCount == len(subOperations.SucceededOperations) {
if types.IsVirtualType(operation.ResourceType) {
operation.State = types.SUCCEEDED
if _, err := om.repository.Update(ctx, operation, types.LabelChanges{}); err != nil {
logger.Errorf("Failed to update the operation with ID (%s) state to Success: %s", operation.ID, err)
}
} else {
sameResourceState, skip, err := handleDuplicateOperations(ctx, om.repository, operation)
if err != nil {
logger.Errorf("Failed to validate if operation with ID (%s) is in polling: %s", operation.ID, err)
continue
}
if skip {
skipSameResourcesForCurrentIteration[operation.ResourceID] = true
continue
}
if sameResourceState != "" {
operation.State = sameResourceState
if _, err := om.repository.Update(ctx, operation, types.LabelChanges{}); err != nil {
logger.Errorf("Failed to update the operation with ID (%s) state to Success: %s", operation.ID, err)
continue
}
} else {
operation.State = types.IN_PROGRESS
action := func(ctx context.Context, repository storage.Repository) (types.Object, error) {
byID := query.ByField(query.EqualsOperator, "id", operation.ResourceID)
err := repository.Delete(ctx, operation.ResourceType, byID)
if err != nil {
if err == util.ErrNotFoundInStorage {
return nil, nil
}
return nil, util.HandleStorageError(err, operation.ResourceType.String())
}
return nil, nil
}
if err := om.cascadePollingScheduler.ScheduleAsyncStorageAction(ctx, operation, action); err != nil {
logger.Errorf("Failed to reschedule cascaded delete operation with ID (%s): %s ok for concurrent deletion failure", operation.ID, err)
} else {
skipSameResourcesForCurrentIteration[operation.ResourceID] = true
}
}
}
} else if len(subOperations.FailedOperations) > 0 && len(subOperations.FailedOperations)+len(subOperations.SucceededOperations) == subOperations.AllOperationsCount {
if !operation.IsForceDeleteCascadeOperation() {
// if its not force cascade delete operion -> aggregating errors
errorsJson, err := PrepareAggregatedErrorsArray(subOperations.FailedOperations, operation.ResourceID, operation.ResourceType)
if err != nil {
logger.Errorf("Couldn't aggregate errors for failed operation with id %s: %s", operation.ResourceID, err)
} else {
operation.Errors = errorsJson
}
} else if operation.CascadeRootID == operation.ID {
// if operation is force cascade delete and its failed -> database error
operation.Errors = []byte(fmt.Sprintf(`{"error": "InternalServerError", "description": "failed to force cascade delete of %s with id %s"}`, operation.ResourceType, operation.ResourceID))
}
operation.State = types.FAILED
if _, err := om.repository.Update(ctx, operation, types.LabelChanges{}); err != nil {
logger.Errorf("Failed to update the operation with ID (%s) state to Success: %s", operation.ID, err)
}
}
}
}
// rescheduleOrphanMitigationOperations reschedules orphan mitigation operations which no goroutine is processing at the moment
func (om *Maintainer) rescheduleOrphanMitigationOperations() {
currentTime := time.Now()
criteria := []query.Criterion{
query.ByField(query.EqualsOperator, "platform_id", types.SMPlatform),
query.ByField(query.NotEqualsOperator, "deletion_scheduled", ZeroTime),
query.ByField(query.NotEqualsOperator, "type", string(types.UPDATE)),
// check if operation hasn't been updated for the operation's maximum allowed time to execute
query.ByField(query.LessThanOperator, "updated_at", util.ToRFCNanoFormat(currentTime.Add(-om.settings.ActionTimeout))),
}
objectList, err := om.repository.List(om.smCtx, types.OperationType, criteria...)
if err != nil {
log.C(om.smCtx).Debugf("Failed to fetch unprocessed orphan mitigation operations: %s", err)
return
}
operations := objectList.(*types.Operations)
for i := 0; i < operations.Len(); i++ {
operation := operations.ItemAt(i).(*types.Operation)
logger := log.C(om.smCtx).WithField(log.FieldCorrelationID, operation.CorrelationID)
ctx := log.ContextWithLogger(om.smCtx, logger)
byID := query.ByField(query.EqualsOperator, "id", operation.ResourceID)
action := func(ctx context.Context, repository storage.Repository) (types.Object, error) {
err := repository.Delete(ctx, operation.ResourceType, byID)
if err != nil {
if err == util.ErrNotFoundInStorage {
return nil, nil
}
return nil, util.HandleStorageError(err, operation.ResourceType.String())
}
return nil, nil
}
if err := om.scheduler.ScheduleAsyncStorageAction(ctx, operation, action); err != nil {
logger.Warnf("Failed to reschedule unprocessed orphan mitigation operation with ID (%s): %s", operation.ID, err)
}
logger.Debugf("Successfully rescheduled orphan mitigation operation %+v", operation)
}
}
// markStuckOperationsFailed checks for operations which are stuck in state IN_PROGRESS, updates their status to FAILED and schedules a delete action
func (om *Maintainer) markStuckOperationsFailed() {
currentTime := time.Now()
criteria := []query.Criterion{
query.ByField(query.EqualsOperator, "platform_id", types.SMPlatform),
query.ByField(query.EqualsOperator, "state", string(types.IN_PROGRESS)),
query.ByField(query.EqualsOperator, "reschedule", "false"),
query.ByField(query.EqualsOperator, "deletion_scheduled", ZeroTime),
// check if operation hasn't been updated for the operation's maximum allowed time to execute
query.ByField(query.LessThanOperator, "updated_at", util.ToRFCNanoFormat(currentTime.Add(-om.settings.ActionTimeout))),
}
objectList, err := om.repository.List(om.smCtx, types.OperationType, criteria...)
if err != nil {
log.C(om.smCtx).Debugf("Failed to fetch stuck operations: %s", err)
return
}
operations := objectList.(*types.Operations)
for i := 0; i < operations.Len(); i++ {
operation := operations.ItemAt(i).(*types.Operation)
logger := log.C(om.smCtx).WithField(log.FieldCorrelationID, operation.CorrelationID)
operation.State = types.FAILED
if operation.Type == types.CREATE || operation.Type == types.DELETE {
operation.DeletionScheduled = time.Now()
}
if _, err := om.repository.Update(om.smCtx, operation, types.LabelChanges{}); err != nil {
logger.Warnf("Failed to update orphan operation with ID (%s) state to FAILED: %s", operation.ID, err)
continue
}
if operation.Type == types.CREATE || operation.Type == types.DELETE {
byID := query.ByField(query.EqualsOperator, "id", operation.ResourceID)
action := func(ctx context.Context, repository storage.Repository) (types.Object, error) {
err := repository.Delete(ctx, operation.ResourceType, byID)
if err != nil {
if err == util.ErrNotFoundInStorage {
return nil, nil
}
return nil, util.HandleStorageError(err, operation.ResourceType.String())
}
return nil, nil
}
if err := om.scheduler.ScheduleAsyncStorageAction(om.smCtx, operation, action); err != nil {
logger.Warnf("Failed to schedule delete action for stuck operation with ID (%s): %s", operation.ID, err)
}
}
}
log.C(om.smCtx).Debug("Finished marking stuck operations as failed")
}