forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanup.go
1775 lines (1660 loc) · 57.5 KB
/
cleanup.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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"fmt"
"time"
"github.com/juju/charm/v9"
"github.com/juju/errors"
"github.com/juju/mgo/v2/bson"
"github.com/juju/mgo/v2/txn"
"github.com/juju/names/v4"
jujutxn "github.com/juju/txn/v2"
"github.com/juju/juju/core/status"
"github.com/juju/juju/mongo"
stateerrors "github.com/juju/juju/state/errors"
)
type cleanupKind string
var (
// asap is the earliest possible time - cleanups scheduled at this
// time will run now. Used instead of time.Now() (hard to test) or
// some contextual clock now (requires that a clock or now value
// be passed through layers of functions from state to
// newCleanupOp).
asap = time.Time{}
)
const (
// SCHEMACHANGE: the names are expressive, the values not so much.
cleanupRelationSettings cleanupKind = "settings"
cleanupForceDestroyedRelation cleanupKind = "forceDestroyRelation"
cleanupUnitsForDyingApplication cleanupKind = "units"
cleanupCharm cleanupKind = "charm"
cleanupDyingUnit cleanupKind = "dyingUnit"
cleanupForceDestroyedUnit cleanupKind = "forceDestroyUnit"
cleanupForceRemoveUnit cleanupKind = "forceRemoveUnit"
cleanupRemovedUnit cleanupKind = "removedUnit"
cleanupApplication cleanupKind = "application"
cleanupForceApplication cleanupKind = "forceApplication"
cleanupApplicationsForDyingModel cleanupKind = "applications"
cleanupDyingMachine cleanupKind = "dyingMachine"
cleanupForceDestroyedMachine cleanupKind = "machine"
cleanupForceRemoveMachine cleanupKind = "forceRemoveMachine"
cleanupAttachmentsForDyingStorage cleanupKind = "storageAttachments"
cleanupAttachmentsForDyingVolume cleanupKind = "volumeAttachments"
cleanupAttachmentsForDyingFilesystem cleanupKind = "filesystemAttachments"
cleanupModelsForDyingController cleanupKind = "models"
// IAAS models require machines to be cleaned up.
cleanupMachinesForDyingModel cleanupKind = "modelMachines"
// CAAS models require storage to be cleaned up.
cleanupDyingUnitResources cleanupKind = "dyingUnitResources"
cleanupResourceBlob cleanupKind = "resourceBlob"
cleanupStorageForDyingModel cleanupKind = "modelStorage"
cleanupForceStorage cleanupKind = "forceStorage"
cleanupBranchesForDyingModel cleanupKind = "branches"
)
// cleanupDoc originally represented a set of documents that should be
// removed, but the Prefix field no longer means anything more than
// "what will be passed to the cleanup func".
type cleanupDoc struct {
DocID string `bson:"_id"`
Kind cleanupKind `bson:"kind"`
When time.Time `bson:"when"`
Prefix string `bson:"prefix"`
Args []*cleanupArg `bson:"args,omitempty"`
}
type cleanupArg struct {
Value interface{}
}
// GetBSON is part of the bson.Getter interface.
func (a *cleanupArg) GetBSON() (interface{}, error) {
return a.Value, nil
}
// SetBSON is part of the bson.Setter interface.
func (a *cleanupArg) SetBSON(raw bson.Raw) error {
a.Value = raw
return nil
}
// newCleanupOp returns a txn.Op that creates a cleanup document with a unique
// id and the supplied kind and prefix.
func newCleanupOp(kind cleanupKind, prefix string, args ...interface{}) txn.Op {
return newCleanupAtOp(asap, kind, prefix, args...)
}
func newCleanupAtOp(when time.Time, kind cleanupKind, prefix string, args ...interface{}) txn.Op {
var cleanupArgs []*cleanupArg
if len(args) > 0 {
cleanupArgs = make([]*cleanupArg, len(args))
for i, arg := range args {
cleanupArgs[i] = &cleanupArg{arg}
}
}
doc := &cleanupDoc{
DocID: bson.NewObjectId().Hex(),
Kind: kind,
When: when,
Prefix: prefix,
Args: cleanupArgs,
}
return txn.Op{
C: cleanupsC,
Id: doc.DocID,
Insert: doc,
}
}
// NeedsCleanup returns true if documents previously marked for removal exist.
func (st *State) NeedsCleanup() (bool, error) {
cleanups, closer := st.db().GetCollection(cleanupsC)
defer closer()
count, err := cleanups.Count()
if err != nil {
return false, err
}
return count > 0, nil
}
// Cleanup removes all documents that were previously marked for removal, if
// any such exist. It should be called periodically by at least one element
// of the system.
func (st *State) Cleanup() (err error) {
var doc cleanupDoc
cleanups, closer := st.db().GetCollection(cleanupsC)
defer closer()
modelUUID := st.ModelUUID()
modelId := modelUUID[:6]
// Only look at cleanups that should be run now.
query := bson.M{"$or": []bson.M{
{"when": bson.M{"$lte": st.stateClock.Now()}},
{"when": bson.M{"$exists": false}},
}}
// TODO(jam): 2019-05-01 We used to just query in any order, but that turned
// out to *normally* be in sorted order, and some cleanups ended up depending
// on that ordering. We shouldn't, but until we can fix the cleanups,
// enforce the sort ordering.
iter := cleanups.Find(query).Sort("_id").Iter()
defer closeIter(iter, &err, "reading cleanup document")
for iter.Next(&doc) {
var err error
logger.Debugf("model %v cleanup: %v(%q)", modelId, doc.Kind, doc.Prefix)
args := make([]bson.Raw, len(doc.Args))
for i, arg := range doc.Args {
args[i] = arg.Value.(bson.Raw)
}
switch doc.Kind {
case cleanupRelationSettings:
err = st.cleanupRelationSettings(doc.Prefix)
case cleanupForceDestroyedRelation:
err = st.cleanupForceDestroyedRelation(doc.Prefix)
case cleanupCharm:
err = st.cleanupCharm(doc.Prefix)
case cleanupApplication:
err = st.cleanupApplication(doc.Prefix, args)
case cleanupForceApplication:
err = st.cleanupForceApplication(doc.Prefix, args)
case cleanupUnitsForDyingApplication:
err = st.cleanupUnitsForDyingApplication(doc.Prefix, args)
case cleanupDyingUnit:
err = st.cleanupDyingUnit(doc.Prefix, args)
case cleanupForceDestroyedUnit:
err = st.cleanupForceDestroyedUnit(doc.Prefix, args)
case cleanupForceRemoveUnit:
err = st.cleanupForceRemoveUnit(doc.Prefix, args)
case cleanupDyingUnitResources:
err = st.cleanupDyingUnitResources(doc.Prefix, args)
case cleanupRemovedUnit:
err = st.cleanupRemovedUnit(doc.Prefix, args)
case cleanupApplicationsForDyingModel:
err = st.cleanupApplicationsForDyingModel(args)
case cleanupDyingMachine:
err = st.cleanupDyingMachine(doc.Prefix, args)
case cleanupForceDestroyedMachine:
err = st.cleanupForceDestroyedMachine(doc.Prefix, args)
case cleanupForceRemoveMachine:
err = st.cleanupForceRemoveMachine(doc.Prefix, args)
case cleanupAttachmentsForDyingStorage:
err = st.cleanupAttachmentsForDyingStorage(doc.Prefix, args)
case cleanupAttachmentsForDyingVolume:
err = st.cleanupAttachmentsForDyingVolume(doc.Prefix)
case cleanupAttachmentsForDyingFilesystem:
err = st.cleanupAttachmentsForDyingFilesystem(doc.Prefix)
case cleanupModelsForDyingController:
err = st.cleanupModelsForDyingController(args)
case cleanupMachinesForDyingModel: // IAAS models only
err = st.cleanupMachinesForDyingModel(args)
case cleanupResourceBlob:
err = st.cleanupResourceBlob(doc.Prefix)
case cleanupStorageForDyingModel:
err = st.cleanupStorageForDyingModel(doc.Prefix, args)
case cleanupForceStorage:
err = st.cleanupForceStorage(args)
case cleanupBranchesForDyingModel:
err = st.cleanupBranchesForDyingModel(args)
default:
err = errors.Errorf("unknown cleanup kind %q", doc.Kind)
}
if err != nil {
logger.Warningf(
"cleanup failed in model %v for %v(%q): %v",
modelUUID, doc.Kind, doc.Prefix, err,
)
continue
}
ops := []txn.Op{{
C: cleanupsC,
Id: doc.DocID,
Remove: true,
}}
if err := st.db().RunTransaction(ops); err != nil {
return errors.Annotate(err, "cannot remove empty cleanup document")
}
}
return nil
}
func (st *State) cleanupResourceBlob(storagePath string) error {
// Ignore attempts to clean up a placeholder resource.
if storagePath == "" {
return nil
}
persist := st.newPersistence()
storage := persist.NewStorage()
err := storage.Remove(storagePath)
if errors.IsNotFound(err) {
return nil
}
return errors.Trace(err)
}
func (st *State) cleanupRelationSettings(prefix string) error {
change := relationSettingsCleanupChange{Prefix: st.docID(prefix)}
if err := Apply(st.database, change); err != nil {
return errors.Trace(err)
}
return nil
}
func (st *State) cleanupForceDestroyedRelation(prefix string) (err error) {
relation, err := st.KeyRelation(prefix)
if errors.IsNotFound(err) {
return nil
}
if err != nil {
return errors.Annotatef(err, "getting relation %q", prefix)
}
scopes, closer := st.db().GetCollection(relationScopesC)
defer closer()
sel := bson.M{"_id": bson.M{
"$regex": fmt.Sprintf("^%s#", st.docID(relation.globalScope())),
}}
iter := scopes.Find(sel).Iter()
defer closeIter(iter, &err, "reading relation scopes")
var doc struct {
Key string `bson:"key"`
}
haveRelationUnits := false
for iter.Next(&doc) {
scope, role, unitName, err := unpackScopeKey(doc.Key)
if err != nil {
return errors.Annotatef(err, "unpacking scope key %q", doc.Key)
}
var matchingEp Endpoint
for _, ep := range relation.Endpoints() {
if string(ep.Role) == role {
matchingEp = ep
}
}
if matchingEp.Role == "" {
return errors.NotFoundf("endpoint matching %q", doc.Key)
}
haveRelationUnits = true
// This is nasty but I can't see any other way to do it - we
// can't rely on the unit existing to determine the values of
// isPrincipal and isLocalUnit, and we're only using the RU to
// call LeaveScope on it.
ru := RelationUnit{
st: st,
relation: relation,
unitName: unitName,
endpoint: matchingEp,
scope: scope,
}
// Run the leave scope txn immediately rather than building
// one big transaction because each one decrements the
// relation's unitcount, and we need the last one to remove
// the relation (which wouldn't work if the ops were combined
// into one txn).
// We know this should be forced, and we've already waited the
// required time.
errs, err := ru.LeaveScopeWithForce(true, 0)
if len(errs) > 0 {
logger.Warningf("operational errors leaving scope for unit %q in relation %q: %v", unitName, relation, errs)
}
if err != nil {
return errors.Annotatef(err, "leaving scope for unit %q in relation %q", unitName, relation)
}
}
if !haveRelationUnits {
// We got here because a relation claimed to have units but
// there weren't any corresponding relation unit records.
// We know this should be forced, and we've already waited the
// required time.
errs, err := relation.DestroyWithForce(true, 0)
if len(errs) > 0 {
logger.Warningf("operational errors force destroying orphaned relation %q: %v", relation, errs)
}
return errors.Annotatef(err, "force destroying relation %q", relation)
}
return nil
}
// cleanupModelsForDyingController sets all models to dying, if
// they are not already Dying or Dead. It's expected to be used when a
// controller is destroyed.
func (st *State) cleanupModelsForDyingController(cleanupArgs []bson.Raw) (err error) {
var args DestroyModelParams
switch n := len(cleanupArgs); n {
case 0:
// Old cleanups have no args, so follow the old behaviour.
destroyStorage := true
args.DestroyStorage = &destroyStorage
case 1:
if err := cleanupArgs[0].Unmarshal(&args); err != nil {
return errors.Annotate(err, "unmarshalling cleanup args")
}
default:
return errors.Errorf("expected 0-1 arguments, got %d", n)
}
modelUUIDs, err := st.AllModelUUIDs()
if err != nil {
return errors.Trace(err)
}
for _, modelUUID := range modelUUIDs {
newSt, err := st.newStateNoWorkers(modelUUID)
// We explicitly don't start the workers.
if err != nil {
// This model could have been removed.
if errors.IsNotFound(err) {
continue
}
return errors.Trace(err)
}
defer newSt.Close()
model, err := newSt.Model()
if err != nil {
return errors.Trace(err)
}
if err := model.Destroy(args); err != nil {
return errors.Trace(err)
}
}
return nil
}
// cleanupMachinesForDyingModel sets all non-manager machines to Dying,
// if they are not already Dying or Dead. It's expected to be used when
// a model is destroyed.
func (st *State) cleanupMachinesForDyingModel(cleanupArgs []bson.Raw) (err error) {
var args DestroyModelParams
switch n := len(cleanupArgs); n {
case 0:
// Old cleanups have no args, so follow the old behaviour.
case 1:
if err := cleanupArgs[0].Unmarshal(&args); err != nil {
return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args")
}
default:
return errors.Errorf("expected 0-1 arguments, got %d", n)
}
// This won't miss machines, because a Dying model cannot have
// machines added to it. But we do have to remove the machines themselves
// via individual transactions, because they could be in any state at all.
machines, err := st.AllMachines()
if err != nil {
return errors.Trace(err)
}
force := args.Force != nil && *args.Force
for _, m := range machines {
if m.IsManager() {
continue
}
manual, err := m.IsManual()
if err != nil {
// TODO (force 2019-4-24) we should not break out here but continue with other machines.
return errors.Trace(err)
}
if manual {
// Manually added machines should never be force-
// destroyed automatically. That should be a user-
// driven decision, since it may leak applications
// and resources on the machine. If something is
// stuck, then the user can still force-destroy
// the manual machines.
if err := m.DestroyWithContainers(); err != nil {
// Since we cannot delete a manual machine, we cannot proceed with model destruction even if it is forced.
// TODO (force 2019-4-24) However, we should not break out here but continue with other machines.
return errors.Trace(errors.Annotatef(err, "could not destroy manual machine %v", m.Id()))
}
continue
}
if force {
err = m.ForceDestroy(args.MaxWait)
} else {
err = m.DestroyWithContainers()
}
if err != nil {
err = errors.Annotatef(err, "while destroying machine %v is", m.Id())
// TODO (force 2019-4-24) we should not break out here but continue with other machines.
if !force {
return errors.Trace(err)
}
logger.Warningf("%v", err)
}
}
return nil
}
// cleanupStorageForDyingModel sets all storage to Dying, if they are not
// already Dying or Dead. It's expected to be used when a model is destroyed.
func (st *State) cleanupStorageForDyingModel(modelUUID string, cleanupArgs []bson.Raw) (err error) {
sb, err := NewStorageBackend(st)
if err != nil {
return errors.Trace(err)
}
var args DestroyModelParams
switch n := len(cleanupArgs); n {
case 0:
// Old cleanups have no args, so follow the old behaviour.
case 1:
if err := cleanupArgs[0].Unmarshal(&args); err != nil {
return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args")
}
default:
return errors.Errorf("expected 0-1 arguments, got %d", n)
}
destroyStorage := sb.DestroyStorageInstance
if args.DestroyStorage == nil || !*args.DestroyStorage {
destroyStorage = sb.ReleaseStorageInstance
}
storage, err := sb.AllStorageInstances()
if err != nil {
return errors.Trace(err)
}
force := args.Force != nil && *args.Force
for _, s := range storage {
const destroyAttached = true
err := destroyStorage(s.StorageTag(), destroyAttached, force, args.MaxWait)
if errors.IsNotFound(err) {
continue
} else if err != nil {
return errors.Trace(err)
}
}
if force {
st.scheduleForceCleanup(cleanupForceStorage, modelUUID, args.MaxWait)
}
return nil
}
// cleanupForceStorage forcibly removes any remaining storage records from a dying model.
func (st *State) cleanupForceStorage(cleanupArgs []bson.Raw) (err error) {
sb, err := NewStorageBackend(st)
if err != nil {
return errors.Trace(err)
}
// There may be unattached filesystems left over that need to be deleted.
filesystems, err := sb.AllFilesystems()
if err != nil {
return errors.Trace(err)
}
for _, fs := range filesystems {
if err := sb.DestroyFilesystem(fs.FilesystemTag(), true); err != nil {
return errors.Trace(err)
}
if err := sb.RemoveFilesystem(fs.FilesystemTag()); err != nil {
return errors.Trace(err)
}
}
// There may be unattached volumes left over that need to be deleted.
volumes, err := sb.AllVolumes()
if err != nil {
return errors.Trace(err)
}
for _, v := range volumes {
if err := sb.DestroyVolume(v.VolumeTag(), true); err != nil {
return errors.Trace(err)
}
if err := sb.RemoveVolume(v.VolumeTag()); err != nil {
return errors.Trace(err)
}
}
return nil
}
func (st *State) cleanupBranchesForDyingModel(cleanupArgs []bson.Raw) (err error) {
change := branchesCleanupChange{}
if err := Apply(st.database, change); err != nil {
return errors.Trace(err)
}
return nil
}
// cleanupApplication checks if all references to a dying application have been removed,
// and if so, removes the application.
func (st *State) cleanupApplication(applicationname string, cleanupArgs []bson.Raw) (err error) {
app, err := st.Application(applicationname)
if err != nil {
if errors.IsNotFound(err) {
// Nothing to do, the application is already gone.
logger.Tracef("cleanupApplication(%s): application already gone", applicationname)
return nil
}
return errors.Trace(err)
}
if app.Life() == Alive {
return errors.BadRequestf("cleanupApplication requested for an application (%s) that is still alive", applicationname)
}
// We know the app is at least Dying, so check if the unit/relation counts are no longer referencing this application.
if app.UnitCount() > 0 || app.RelationCount() > 0 {
// this is considered a no-op because whatever is currently referencing the application
// should queue up a new cleanup once it stops
logger.Tracef("cleanupApplication(%s) called, but it still has references: unitcount: %d relationcount: %d",
applicationname, app.UnitCount(), app.RelationCount())
return nil
}
destroyStorage := false
force := false
if n := len(cleanupArgs); n != 2 {
return errors.Errorf("expected 2 arguments, got %d", n)
}
if err := cleanupArgs[0].Unmarshal(&destroyStorage); err != nil {
return errors.Annotate(err, "unmarshalling cleanup args")
}
if err := cleanupArgs[1].Unmarshal(&force); err != nil {
return errors.Annotate(err, "unmarshalling cleanup arg 'force'")
}
op := app.DestroyOperation()
op.DestroyStorage = destroyStorage
op.Force = force
err = st.ApplyOperation(op)
if len(op.Errors) != 0 {
logger.Warningf("operational errors cleaning up application %v: %v", applicationname, op.Errors)
}
return err
}
// cleanupForceApplication forcibly removes the application.
func (st *State) cleanupForceApplication(applicationName string, cleanupArgs []bson.Raw) (err error) {
logger.Debugf("force destroy application: %v", applicationName)
app, err := st.Application(applicationName)
if err != nil {
if errors.IsNotFound(err) {
// Nothing to do, the application is already gone.
logger.Tracef("forceCleanupApplication(%s): application already gone", applicationName)
return nil
}
return errors.Trace(err)
}
var maxWait time.Duration
if n := len(cleanupArgs); n != 1 {
return errors.Errorf("expected 1 argument, got %d", n)
}
if err := cleanupArgs[0].Unmarshal(&maxWait); err != nil {
return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'")
}
op := app.DestroyOperation()
op.Force = true
op.CleanupIgnoringResources = true
op.MaxWait = maxWait
err = st.ApplyOperation(op)
if len(op.Errors) != 0 {
logger.Warningf("operational errors cleaning up application %v: %v", applicationName, op.Errors)
}
return err
}
// cleanupApplicationsForDyingModel sets all applications to Dying, if they are
// not already Dying or Dead. It's expected to be used when a model is
// destroyed.
func (st *State) cleanupApplicationsForDyingModel(cleanupArgs []bson.Raw) (err error) {
var args DestroyModelParams
switch n := len(cleanupArgs); n {
case 0:
// Old cleanups have no args, so follow the old behaviour.
case 1:
if err := cleanupArgs[0].Unmarshal(&args); err != nil {
return errors.Annotate(err, "unmarshalling cleanup 'destroy model' args")
}
default:
return errors.Errorf("expected 0-1 arguments, got %d", n)
}
if err := st.removeRemoteApplicationsForDyingModel(args); err != nil {
return err
}
return st.removeApplicationsForDyingModel(args)
}
func (st *State) removeApplicationsForDyingModel(args DestroyModelParams) (err error) {
// This won't miss applications, because a Dying model cannot have
// applications added to it. But we do have to remove the applications
// themselves via individual transactions, because they could be in any
// state at all.
applications, closer := st.db().GetCollection(applicationsC)
defer closer()
// Note(jam): 2019-04-25 This will only try to shut down Alive applications,
// it doesn't cause applications that are Dying to finish progressing to Dead.
application := Application{st: st}
sel := bson.D{{"life", Alive}}
force := args.Force != nil && *args.Force
if force {
// If we're forcing, propagate down to even dying
// applications, just in case they weren't originally forced.
sel = nil
}
iter := applications.Find(sel).Iter()
defer closeIter(iter, &err, "reading application document")
for iter.Next(&application.doc) {
op := application.DestroyOperation()
op.RemoveOffers = true
op.Force = force
op.MaxWait = args.MaxWait
err := st.ApplyOperation(op)
if len(op.Errors) != 0 {
logger.Warningf("operational errors removing application %v for dying model %v: %v", application.Name(), st.ModelUUID(), op.Errors)
}
if err != nil {
return errors.Trace(err)
}
}
return nil
}
func (st *State) removeRemoteApplicationsForDyingModel(args DestroyModelParams) (err error) {
// This won't miss remote applications, because a Dying model cannot have
// applications added to it. But we do have to remove the applications themselves
// via individual transactions, because they could be in any state at all.
remoteApps, closer := st.db().GetCollection(remoteApplicationsC)
defer closer()
remoteApp := RemoteApplication{st: st}
sel := bson.D{{"life", Alive}}
iter := remoteApps.Find(sel).Iter()
defer closeIter(iter, &err, "reading remote application document")
force := args.Force != nil && *args.Force
for iter.Next(&remoteApp.doc) {
errs, err := remoteApp.DestroyWithForce(force, args.MaxWait)
if len(errs) != 0 {
logger.Warningf("operational errors removing remote application %v for dying model %v: %v", remoteApp.Name(), st.ModelUUID(), errs)
}
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// cleanupUnitsForDyingApplication sets all units with the given prefix to Dying,
// if they are not already Dying or Dead. It's expected to be used when a
// application is destroyed.
func (st *State) cleanupUnitsForDyingApplication(applicationname string, cleanupArgs []bson.Raw) (err error) {
var destroyStorage bool
destroyStorageArg := func() error {
err := cleanupArgs[0].Unmarshal(&destroyStorage)
return errors.Annotate(err, "unmarshalling cleanup arg 'destroyStorage'")
}
var force bool
var maxWait time.Duration
switch n := len(cleanupArgs); n {
case 0:
// It's valid to have no args: old cleanups have no args, so follow the old behaviour.
case 1:
if err := destroyStorageArg(); err != nil {
return err
}
case 3:
if err := destroyStorageArg(); err != nil {
return err
}
if err := cleanupArgs[1].Unmarshal(&force); err != nil {
return errors.Annotate(err, "unmarshalling cleanup arg 'force'")
}
if err := cleanupArgs[2].Unmarshal(&maxWait); err != nil {
return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'")
}
default:
return errors.Errorf("expected 0, 1 or 3 arguments, got %d", n)
}
// This won't miss units, because a Dying application cannot have units
// added to it. But we do have to remove the units themselves via
// individual transactions, because they could be in any state at all.
units, closer := st.db().GetCollection(unitsC)
defer closer()
sel := bson.D{{"application", applicationname}}
// If we're forcing then include dying and dead units, since we
// still want the opportunity to schedule fallback cleanups if the
// unit or machine agents aren't doing their jobs.
if !force {
sel = append(sel, bson.DocElem{"life", Alive})
}
iter := units.Find(sel).Iter()
defer closeIter(iter, &err, "reading unit document")
m, err := st.Model()
if err != nil {
return errors.Trace(err)
}
var unitDoc unitDoc
for iter.Next(&unitDoc) {
unit := newUnit(st, m.Type(), &unitDoc)
op := unit.DestroyOperation()
op.DestroyStorage = destroyStorage
op.Force = force
op.MaxWait = maxWait
err := st.ApplyOperation(op)
if len(op.Errors) != 0 {
logger.Warningf("operational errors destroying unit %v for dying application %v: %v", unit.Name(), applicationname, op.Errors)
}
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// cleanupCharm is speculative: it can abort without error for many
// reasons, because it's triggered somewhat over-enthusiastically for
// simplicity's sake.
func (st *State) cleanupCharm(charmURL string) error {
curl, err := charm.ParseURL(charmURL)
if err != nil {
return errors.Annotatef(err, "invalid charm URL %v", charmURL)
}
ch, err := st.Charm(curl)
if errors.IsNotFound(err) {
// Charm already removed.
logger.Tracef("cleanup charm(%s) no-op, charm already gone", charmURL)
return nil
} else if err != nil {
return errors.Annotate(err, "reading charm")
}
logger.Tracef("cleanup charm(%s): Destroy", charmURL)
err = ch.Destroy()
switch errors.Cause(err) {
case nil:
case errCharmInUse:
// No cleanup necessary at this time.
logger.Tracef("cleanup charm(%s): charm still in use", charmURL)
return nil
default:
return errors.Annotate(err, "destroying charm")
}
logger.Tracef("cleanup charm(%s): Remove", charmURL)
if err := ch.Remove(); err != nil {
return errors.Trace(err)
}
return nil
}
// cleanupDyingUnit marks resources owned by the unit as dying, to ensure
// they are cleaned up as well.
func (st *State) cleanupDyingUnit(name string, cleanupArgs []bson.Raw) error {
var destroyStorage bool
destroyStorageArg := func() error {
err := cleanupArgs[0].Unmarshal(&destroyStorage)
return errors.Annotate(err, "unmarshalling cleanup arg 'destroyStorage'")
}
var force bool
var maxWait time.Duration
switch n := len(cleanupArgs); n {
case 0:
// It's valid to have no args: old cleanups have no args, so follow the old behaviour.
case 1:
if err := destroyStorageArg(); err != nil {
return err
}
case 3:
if err := destroyStorageArg(); err != nil {
return err
}
if err := cleanupArgs[1].Unmarshal(&force); err != nil {
return errors.Annotate(err, "unmarshalling cleanup arg 'force'")
}
if err := cleanupArgs[2].Unmarshal(&maxWait); err != nil {
return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'")
}
default:
return errors.Errorf("expected 0, 1 or 3 arguments, got %d", n)
}
unit, err := st.Unit(name)
if errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
// Mark the unit as departing from its joined relations, allowing
// related units to start converging to a state in which that unit
// is gone as quickly as possible.
relations, err := unit.RelationsJoined()
if err != nil {
if !force {
return err
}
logger.Warningf("could not get joined relations for unit %v during dying unit cleanup: %v", unit.Name(), err)
}
for _, relation := range relations {
relationUnit, err := relation.Unit(unit)
if errors.IsNotFound(err) {
continue
} else if err != nil {
if !force {
return err
}
logger.Warningf("could not get unit relation for unit %v during dying unit cleanup: %v", unit.Name(), err)
} else {
if err := relationUnit.PrepareLeaveScope(); err != nil {
if !force {
return err
}
logger.Warningf("could not prepare to leave scope for relation %v for unit %v during dying unit cleanup: %v", relation, unit.Name(), err)
}
}
}
// If we're forcing, set up a backstop cleanup to really remove
// the unit in the case that the unit and machine agents don't for
// some reason.
if force {
st.scheduleForceCleanup(cleanupForceDestroyedUnit, name, maxWait)
}
if destroyStorage {
// Detach and mark storage instances as dying, allowing the
// unit to terminate.
return st.cleanupUnitStorageInstances(unit.UnitTag(), force, maxWait)
} else {
// Mark storage attachments as dying, so that they are detached
// and removed from state, allowing the unit to terminate.
return st.cleanupUnitStorageAttachments(unit.UnitTag(), false, force, maxWait)
}
}
func (st *State) scheduleForceCleanup(kind cleanupKind, name string, maxWait time.Duration) {
deadline := st.stateClock.Now().Add(maxWait)
op := newCleanupAtOp(deadline, kind, name, maxWait)
err := st.db().Run(func(int) ([]txn.Op, error) {
return []txn.Op{op}, nil
})
if err != nil {
logger.Warningf("couldn't schedule %s cleanup: %v", kind, err)
}
}
func (st *State) cleanupForceDestroyedUnit(unitId string, cleanupArgs []bson.Raw) error {
var maxWait time.Duration
if n := len(cleanupArgs); n != 1 {
return errors.Errorf("expected 1 argument, got %d", n)
}
if err := cleanupArgs[0].Unmarshal(&maxWait); err != nil {
return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'")
}
unit, err := st.Unit(unitId)
if errors.IsNotFound(err) {
logger.Debugf("no need to force unit to dead %q", unitId)
return nil
} else if err != nil {
return errors.Trace(err)
}
// If we're here then the usual unit cleanup hasn't happened but
// since force was specified we still want the machine to go to
// dead.
// Destroy all subordinates.
for _, subName := range unit.SubordinateNames() {
subUnit, err := st.Unit(subName)
if errors.IsNotFound(err) {
continue
} else if err != nil {
logger.Warningf("couldn't get subordinate %q to force destroy: %v", subName, err)
}
opErrs, err := subUnit.DestroyWithForce(true, maxWait)
if len(opErrs) != 0 || err != nil {
logger.Warningf("errors while destroying subordinate %q: %v, %v", subName, err, opErrs)
}
}
// LeaveScope on all of the unit's relations.
relations, err := unit.RelationsInScope()
if err == nil {
for _, relation := range relations {
ru, err := relation.Unit(unit)
if err != nil {
logger.Warningf("couldn't get relation unit for %q in %q: %v", unit, relation, err)
continue
}
errs, err := ru.LeaveScopeWithForce(true, maxWait)
if len(errs) != 0 {
logger.Warningf("operational errors cleaning up force destroyed unit %v in relation %v: %v", unit, relation, errs)
}
if err != nil {
logger.Warningf("unit %q couldn't leave scope of relation %q: %v", unitId, relation, err)
}
}
} else {
logger.Warningf("couldn't get in-scope relations for unit %q: %v", unitId, err)
}
// Detach all storage.
err = st.forceRemoveUnitStorageAttachments(unit)
if err != nil {
logger.Warningf("couldn't remove storage attachments for %q: %v", unitId, err)
}
// Mark the unit dead.
err = unit.EnsureDead()
if err == stateerrors.ErrUnitHasSubordinates || err == stateerrors.ErrUnitHasStorageAttachments {
// In this case we do want to die and try again - we can't set
// the unit to dead until the subordinates and storage are
// gone, so we should give them time to be removed.
return err
} else if err != nil {
logger.Warningf("couldn't set unit %q dead: %v", unitId, err)
}
// Set up another cleanup to remove the unit in a minute if the
// deployer doesn't do it.
st.scheduleForceCleanup(cleanupForceRemoveUnit, unitId, maxWait)
return nil
}
func (st *State) forceRemoveUnitStorageAttachments(unit *Unit) error {
sb, err := NewStorageBackend(st)
if err != nil {
return errors.Annotate(err, "couldn't get storage backend")
}
err = sb.DestroyUnitStorageAttachments(unit.UnitTag())
if err != nil {
return errors.Annotatef(err, "destroying storage attachments for %q", unit.Tag().Id())
}
attachments, err := sb.UnitStorageAttachments(unit.UnitTag())
if err != nil {
return errors.Annotatef(err, "getting storage attachments for %q", unit.Tag().Id())
}
for _, attachment := range attachments {
err := sb.RemoveStorageAttachment(
attachment.StorageInstance(), unit.UnitTag(), true)
if err != nil {
logger.Warningf("couldn't remove storage attachment %q for %q: %v", attachment.StorageInstance(), unit, err)
}
}
return nil
}
func (st *State) cleanupForceRemoveUnit(unitId string, cleanupArgs []bson.Raw) error {
var maxWait time.Duration
if n := len(cleanupArgs); n != 1 {
return errors.Errorf("expected 1 argument, got %d", n)
}
if err := cleanupArgs[0].Unmarshal(&maxWait); err != nil {
return errors.Annotate(err, "unmarshalling cleanup arg 'maxWait'")
}
unit, err := st.Unit(unitId)
if errors.IsNotFound(err) {
logger.Debugf("no need to force remove unit %q", unitId)