forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanup.go
1007 lines (933 loc) · 30.7 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 (
"github.com/juju/errors"
jujutxn "github.com/juju/txn"
"gopkg.in/juju/charm.v6"
"gopkg.in/juju/names.v2"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/core/status"
"github.com/juju/juju/mongo"
)
type cleanupKind string
const (
// SCHEMACHANGE: the names are expressive, the values not so much.
cleanupRelationSettings cleanupKind = "settings"
cleanupUnitsForDyingApplication cleanupKind = "units"
cleanupCharm cleanupKind = "charm"
cleanupDyingUnit cleanupKind = "dyingUnit"
cleanupRemovedUnit cleanupKind = "removedUnit"
cleanupApplicationsForDyingModel cleanupKind = "applications"
cleanupDyingMachine cleanupKind = "dyingMachine"
cleanupForceDestroyedMachine cleanupKind = "machine"
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"
)
// 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"`
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 {
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,
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]
iter := cleanups.Find(nil).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 cleanupCharm:
err = st.cleanupCharm(doc.Prefix)
case cleanupUnitsForDyingApplication:
err = st.cleanupUnitsForDyingApplication(doc.Prefix, args)
case cleanupDyingUnit:
err = st.cleanupDyingUnit(doc.Prefix, args)
case cleanupDyingUnitResources:
err = st.cleanupDyingUnitResources(doc.Prefix)
case cleanupRemovedUnit:
err = st.cleanupRemovedUnit(doc.Prefix)
case cleanupApplicationsForDyingModel:
err = st.cleanupApplicationsForDyingModel()
case cleanupDyingMachine:
err = st.cleanupDyingMachine(doc.Prefix)
case cleanupForceDestroyedMachine:
err = st.cleanupForceDestroyedMachine(doc.Prefix)
case cleanupAttachmentsForDyingStorage:
err = st.cleanupAttachmentsForDyingStorage(doc.Prefix)
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()
case cleanupResourceBlob:
err = st.cleanupResourceBlob(doc.Prefix)
case cleanupStorageForDyingModel:
err = st.cleanupStorageForDyingModel(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
}
// 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() (err error) {
// 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)
}
for _, m := range machines {
if m.IsManager() {
continue
}
if _, isContainer := m.ParentId(); isContainer {
continue
}
manual, err := m.IsManual()
if err != nil {
return errors.Trace(err)
}
destroy := m.ForceDestroy
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.
destroy = m.Destroy
}
if err := destroy(); err != nil {
return errors.Trace(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(cleanupArgs []bson.Raw) (err error) {
sb, err := NewStorageBackend(st)
if err != nil {
return errors.Trace(err)
}
destroyStorage := sb.DestroyStorageInstance
switch n := len(cleanupArgs); n {
case 0:
// Old cleanups have no args, so follow the old
// behaviour: destroy the storage.
case 1:
var destroyStorageFlag bool
if err := cleanupArgs[0].Unmarshal(&destroyStorageFlag); err != nil {
return errors.Annotate(err, "unmarshalling cleanup args")
}
if !destroyStorageFlag {
destroyStorage = sb.ReleaseStorageInstance
}
default:
return errors.Errorf("expected 0-1 arguments, got %d", n)
}
storage, err := sb.AllStorageInstances()
if err != nil {
return errors.Trace(err)
}
for _, s := range storage {
const destroyAttached = true
err := destroyStorage(s.StorageTag(), destroyAttached)
if errors.IsNotFound(err) {
continue
} else if err != nil {
return errors.Trace(err)
}
}
return nil
}
// 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() (err error) {
if err := st.removeRemoteApplicationsForDyingModel(); err != nil {
return err
}
return st.removeApplicationsForDyingModel()
}
func (st *State) removeApplicationsForDyingModel() (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()
application := Application{st: st}
sel := bson.D{{"life", Alive}}
iter := applications.Find(sel).Iter()
defer closeIter(iter, &err, "reading application document")
for iter.Next(&application.doc) {
op := application.DestroyOperation()
op.RemoveOffers = true
if err := st.ApplyOperation(op); err != nil {
return errors.Trace(err)
}
}
return nil
}
func (st *State) removeRemoteApplicationsForDyingModel() (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")
for iter.Next(&remoteApp.doc) {
if err := remoteApp.Destroy(); 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
switch n := len(cleanupArgs); n {
case 0:
// Old cleanups have no args, so follow the old behaviour.
case 1:
if err := cleanupArgs[0].Unmarshal(&destroyStorage); err != nil {
return errors.Annotate(err, "unmarshalling cleanup args")
}
default:
return errors.Errorf("expected 0-1 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()
unit := Unit{st: st}
sel := bson.D{{"application", applicationname}, {"life", Alive}}
iter := units.Find(sel).Iter()
defer closeIter(iter, &err, "reading unit document")
for iter.Next(&unit.doc) {
op := unit.DestroyOperation()
op.DestroyStorage = destroyStorage
if err := st.ApplyOperation(op); err != nil {
return errors.Trace(err)
}
}
return nil
}
// cleanupCharm is speculative: it can abort without error for many
// reasons, because it's triggered somewhat overenthusiastically 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.
return nil
} else if err != nil {
return errors.Annotate(err, "reading charm")
}
err = ch.Destroy()
switch errors.Cause(err) {
case nil:
case errCharmInUse:
// No cleanup necessary at this time.
return nil
default:
return errors.Annotate(err, "destroying charm")
}
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
switch n := len(cleanupArgs); n {
case 0:
// Old cleanups have no args, so follow the old behaviour.
case 1:
if err := cleanupArgs[0].Unmarshal(&destroyStorage); err != nil {
return errors.Annotate(err, "unmarshalling cleanup args")
}
default:
return errors.Errorf("expected 0-1 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 {
return err
}
for _, relation := range relations {
relationUnit, err := relation.Unit(unit)
if errors.IsNotFound(err) {
continue
} else if err != nil {
return err
}
if err := relationUnit.PrepareLeaveScope(); err != nil {
return err
}
}
if destroyStorage {
// Detach and mark storage instances as dying, allowing the
// unit to terminate.
return st.cleanupUnitStorageInstances(unit.UnitTag())
} 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)
}
}
func (st *State) cleanupDyingUnitResources(unitId string) error {
unitTag := names.NewUnitTag(unitId)
sb, err := NewStorageBackend(st)
if err != nil {
return err
}
filesystemAttachments, err := sb.UnitFilesystemAttachments(unitTag)
if err != nil {
return errors.Annotate(err, "getting unit filesystem attachments")
}
volumeAttachments, err := sb.UnitVolumeAttachments(unitTag)
if err != nil {
return errors.Annotate(err, "getting unit volume attachments")
}
return cleanupDyingEntityStorage(sb, unitTag, false, filesystemAttachments, volumeAttachments)
}
func (st *State) cleanupUnitStorageAttachments(unitTag names.UnitTag, remove bool) error {
sb, err := NewStorageBackend(st)
if err != nil {
return err
}
storageAttachments, err := sb.UnitStorageAttachments(unitTag)
if err != nil {
return err
}
for _, storageAttachment := range storageAttachments {
storageTag := storageAttachment.StorageInstance()
err := sb.DetachStorage(storageTag, unitTag)
if errors.IsNotFound(err) {
continue
} else if err != nil {
return err
}
if !remove {
continue
}
err = sb.RemoveStorageAttachment(storageTag, unitTag)
if errors.IsNotFound(err) {
continue
} else if err != nil {
return err
}
}
return nil
}
func (st *State) cleanupUnitStorageInstances(unitTag names.UnitTag) error {
sb, err := NewStorageBackend(st)
if err != nil {
return err
}
storageAttachments, err := sb.UnitStorageAttachments(unitTag)
if err != nil {
return err
}
for _, storageAttachment := range storageAttachments {
storageTag := storageAttachment.StorageInstance()
err := sb.DestroyStorageInstance(storageTag, true)
if errors.IsNotFound(err) {
continue
} else if err != nil {
return err
}
}
return nil
}
// cleanupRemovedUnit takes care of all the final cleanup required when
// a unit is removed.
func (st *State) cleanupRemovedUnit(unitId string) error {
actions, err := st.matchingActionsByReceiverId(unitId)
if err != nil {
return errors.Trace(err)
}
cancelled := ActionResults{
Status: ActionCancelled,
Message: "unit removed",
}
for _, action := range actions {
switch action.Status() {
case ActionCompleted, ActionCancelled, ActionFailed:
// nothing to do here
default:
if _, err = action.Finish(cancelled); err != nil {
return errors.Trace(err)
}
}
}
change := payloadCleanupChange{
Unit: unitId,
}
if err := Apply(st.database, change); err != nil {
return errors.Trace(err)
}
return nil
}
// cleanupDyingMachine marks resources owned by the machine as dying, to ensure
// they are cleaned up as well.
func (st *State) cleanupDyingMachine(machineId string) error {
machine, err := st.Machine(machineId)
if errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
return cleanupDyingMachineResources(machine)
}
// cleanupForceDestroyedMachine systematically destroys and removes all entities
// that depend upon the supplied machine, and removes the machine from state. It's
// expected to be used in response to destroy-machine --force.
func (st *State) cleanupForceDestroyedMachine(machineId string) error {
machine, err := st.Machine(machineId)
if errors.IsNotFound(err) {
return nil
} else if err != nil {
return errors.Trace(err)
}
// The first thing we want to do is remove any series upgrade machine
// locks that might prevent other resources from being removed.
if err := cleanupUpgradeSeriesLock(machine); err != nil {
return errors.Trace(err)
}
// In an ideal world, we'd call machine.Destroy() here, and thus prevent
// new dependencies being added while we clean up the ones we know about.
// But machine destruction is unsophisticated, and doesn't allow for
// destruction while dependencies exist; so we just have to deal with that
// possibility below.
if err := st.cleanupContainers(machine); err != nil {
return errors.Trace(err)
}
for _, unitName := range machine.doc.Principals {
if err := st.obliterateUnit(unitName); err != nil {
return errors.Trace(err)
}
}
if err := cleanupDyingMachineResources(machine); err != nil {
return errors.Trace(err)
}
if machine.IsManager() {
if machine.HasVote() {
// we remove the vote from the machine so that it can be torn down cleanly. Note that this isn't reflected
// in the actual replicaset, so users using --force should be careful.
hasVoteTxn := func(attempt int) ([]txn.Op, error) {
if attempt != 0 {
if err := machine.Refresh(); err != nil {
return nil, errors.Trace(err)
}
if !machine.HasVote() {
return nil, jujutxn.ErrNoOperations
}
}
return []txn.Op{{
C: machinesC,
Id: machine.doc.Id,
Update: bson.D{{"$set", bson.D{{"hasvote", false}}}},
}}, nil
}
if err := st.db().Run(hasVoteTxn); err != nil {
return errors.Trace(err)
}
}
if err := st.RemoveControllerMachine(machine); err != nil {
return errors.Trace(err)
}
}
// We need to refresh the machine at this point, because the local copy
// of the document will not reflect changes caused by the unit cleanups
// above, and may thus fail immediately.
if err := machine.Refresh(); errors.IsNotFound(err) {
return nil
} else if err != nil {
return errors.Trace(err)
}
// TODO(fwereade): 2013-11-11 bug 1250104
// If this fails, it's *probably* due to a race in which new dependencies
// were added while we cleaned up the old ones. If the cleanup doesn't run
// again -- which it *probably* will anyway -- the issue can be resolved by
// force-destroying the machine again; that's better than adding layer
// upon layer of complication here.
if err := machine.EnsureDead(); err != nil {
return errors.Trace(err)
}
removePortsOps, err := machine.removePortsOps()
if len(removePortsOps) == 0 || err != nil {
return errors.Trace(err)
}
if err := st.db().RunTransaction(removePortsOps); err != nil {
return errors.Trace(err)
}
return nil
// Note that we do *not* remove the machine entirely: we leave it for the
// provisioner to clean up, so that we don't end up with an unreferenced
// instance that would otherwise be ignored when in provisioner-safe-mode.
}
// cleanupContainers recursively calls cleanupForceDestroyedMachine on the supplied
// machine's containers, and removes them from state entirely.
func (st *State) cleanupContainers(machine *Machine) error {
containerIds, err := machine.Containers()
if errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
for _, containerId := range containerIds {
if err := st.cleanupForceDestroyedMachine(containerId); err != nil {
return err
}
container, err := st.Machine(containerId)
if errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
if err := container.Remove(); err != nil {
return err
}
}
return nil
}
func cleanupDyingMachineResources(m *Machine) error {
sb, err := NewStorageBackend(m.st)
if err != nil {
return errors.Trace(err)
}
filesystemAttachments, err := sb.MachineFilesystemAttachments(m.MachineTag())
if err != nil {
return errors.Annotate(err, "getting machine filesystem attachments")
}
volumeAttachments, err := sb.MachineVolumeAttachments(m.MachineTag())
if err != nil {
return errors.Annotate(err, "getting machine volume attachments")
}
// Check if the machine is manual, to decide whether or not to
// short circuit the removal of non-detachable filesystems.
manual, err := m.IsManual()
if err != nil {
return errors.Trace(err)
}
return cleanupDyingEntityStorage(sb, m.Tag(), manual, filesystemAttachments, volumeAttachments)
}
func cleanupDyingEntityStorage(sb *storageBackend, hostTag names.Tag, manual bool, filesystemAttachments []FilesystemAttachment, volumeAttachments []VolumeAttachment) error {
// Destroy non-detachable machine/unit filesystems first.
filesystems, err := sb.filesystems(bson.D{{"hostid", hostTag.Id()}})
if err != nil {
return errors.Annotate(err, "getting host filesystems")
}
for _, f := range filesystems {
if err := sb.DestroyFilesystem(f.FilesystemTag()); err != nil {
return errors.Trace(err)
}
}
// Detach all filesystems from the machine/unit.
for _, fsa := range filesystemAttachments {
detachable, err := isDetachableFilesystemTag(sb.mb.db(), fsa.Filesystem())
if err != nil {
return errors.Trace(err)
}
if detachable {
if err := sb.DetachFilesystem(fsa.Host(), fsa.Filesystem()); err != nil {
return errors.Trace(err)
}
}
if !manual {
// For non-manual machines we immediately remove the attachments
// for non-detachable or volume-backed filesystems, which should
// have been set to Dying by the destruction of the machine
// filesystems, or filesystem detachment, above.
machineTag := fsa.Host()
var remove bool
var volumeTag names.VolumeTag
var updateStatus func() error
if !detachable {
remove = true
updateStatus = func() error { return nil }
} else {
f, err := sb.Filesystem(fsa.Filesystem())
if err != nil {
return errors.Trace(err)
}
if v, err := f.Volume(); err == nil {
// Filesystem is volume-backed.
volumeTag = v
remove = true
}
updateStatus = func() error {
return f.SetStatus(status.StatusInfo{
Status: status.Detached,
})
}
}
if remove {
if err := sb.RemoveFilesystemAttachment(
fsa.Host(), fsa.Filesystem(),
); err != nil {
return errors.Trace(err)
}
if volumeTag != (names.VolumeTag{}) {
if err := sb.RemoveVolumeAttachmentPlan(
machineTag, volumeTag,
); err != nil {
return errors.Trace(err)
}
}
if err := updateStatus(); err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
}
}
}
// For non-manual machines we immediately remove the non-detachable
// filesystems, which should have been detached above. Short circuiting
// the removal of machine filesystems means we can avoid stuck
// filesystems preventing any model-scoped backing volumes from being
// detached and destroyed. For non-manual machines this is safe, because
// the machine is about to be terminated. For manual machines, stuck
// filesystems will have to be fixed manually.
if !manual {
for _, f := range filesystems {
if err := sb.RemoveFilesystem(f.FilesystemTag()); err != nil {
return errors.Trace(err)
}
}
}
// Detach all remaining volumes from the machine.
for _, va := range volumeAttachments {
if detachable, err := isDetachableVolumeTag(sb.mb.db(), va.Volume()); err != nil {
return errors.Trace(err)
} else if !detachable {
// Non-detachable volumes will be removed along with the machine.
continue
}
if err := sb.DetachVolume(va.Host(), va.Volume()); err != nil {
if IsContainsFilesystem(err) {
// The volume will be destroyed when the
// contained filesystem is removed, whose
// destruction is initiated below.
continue
}
return errors.Trace(err)
}
}
return nil
}
// obliterateUnit removes a unit from state completely. It is not safe or
// sane to obliterate any unit in isolation; its only reasonable use is in
// the context of machine obliteration, in which we can be sure that unclean
// shutdown of units is not going to leave a machine in a difficult state.
func (st *State) obliterateUnit(unitName string) error {
unit, err := st.Unit(unitName)
if errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
// Unlike the machine, we *can* always destroy the unit, and (at least)
// prevent further dependencies being added. If we're really lucky, the
// unit will be removed immediately.
if err := unit.Destroy(); err != nil {
return errors.Annotatef(err, "cannot destroy unit %q", unitName)
}
if err := unit.Refresh(); errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
// Destroy and remove all storage attachments for the unit.
if err := st.cleanupUnitStorageAttachments(unit.UnitTag(), true); err != nil {
return errors.Annotatef(err, "cannot destroy storage for unit %q", unitName)
}
for _, subName := range unit.SubordinateNames() {
if err := st.obliterateUnit(subName); err != nil {
return err
}
}
if err := unit.EnsureDead(); err != nil {
return err
}
return unit.Remove()
}
// cleanupAttachmentsForDyingStorage sets all storage attachments related
// to the specified storage instance to Dying, if they are not already Dying
// or Dead. It's expected to be used when a storage instance is destroyed.
func (st *State) cleanupAttachmentsForDyingStorage(storageId string) (err error) {
sb, err := NewStorageBackend(st)
if err != nil {
return errors.Trace(err)
}
storageTag := names.NewStorageTag(storageId)
// This won't miss attachments, because a Dying storage instance cannot
// have attachments added to it. But we do have to remove the attachments
// themselves via individual transactions, because they could be in
// any state at all.
coll, closer := st.db().GetCollection(storageAttachmentsC)
defer closer()
var doc storageAttachmentDoc
fields := bson.D{{"unitid", 1}}
iter := coll.Find(bson.D{{"storageid", storageId}}).Select(fields).Iter()
defer closeIter(iter, &err, "reading storage attachment document")
for iter.Next(&doc) {
unitTag := names.NewUnitTag(doc.Unit)
if err := sb.DetachStorage(storageTag, unitTag); err != nil {
return errors.Annotate(err, "destroying storage attachment")
}
}
return nil
}
// cleanupAttachmentsForDyingVolume sets all volume attachments related
// to the specified volume to Dying, if they are not already Dying or
// Dead. It's expected to be used when a volume is destroyed.
func (st *State) cleanupAttachmentsForDyingVolume(volumeId string) (err error) {
volumeTag := names.NewVolumeTag(volumeId)
// This won't miss attachments, because a Dying volume cannot have
// attachments added to it. But we do have to remove the attachments
// themselves via individual transactions, because they could be in
// any state at all.
coll, closer := st.db().GetCollection(volumeAttachmentsC)
defer closer()
sb, err := NewStorageBackend(st)
if err != nil {
return errors.Trace(err)
}
var doc volumeAttachmentDoc
fields := bson.D{{"hostid", 1}}
iter := coll.Find(bson.D{{"volumeid", volumeId}}).Select(fields).Iter()
defer closeIter(iter, &err, "reading volume attachment document")
for iter.Next(&doc) {
hostTag := storageAttachmentHost(doc.Host)
if err := sb.DetachVolume(hostTag, volumeTag); err != nil {
return errors.Annotate(err, "destroying volume attachment")
}
}
return nil
}
// cleanupAttachmentsForDyingFilesystem sets all filesystem attachments related
// to the specified filesystem to Dying, if they are not already Dying or
// Dead. It's expected to be used when a filesystem is destroyed.
func (st *State) cleanupAttachmentsForDyingFilesystem(filesystemId string) (err error) {
sb, err := NewStorageBackend(st)
if err != nil {
return errors.Trace(err)
}
filesystemTag := names.NewFilesystemTag(filesystemId)
// This won't miss attachments, because a Dying filesystem cannot have
// attachments added to it. But we do have to remove the attachments
// themselves via individual transactions, because they could be in
// any state at all.
coll, closer := sb.mb.db().GetCollection(filesystemAttachmentsC)
defer closer()
var doc filesystemAttachmentDoc
fields := bson.D{{"hostid", 1}}
iter := coll.Find(bson.D{{"filesystemid", filesystemId}}).Select(fields).Iter()
defer closeIter(iter, &err, "reading filesystem attachment document")
for iter.Next(&doc) {
hostTag := storageAttachmentHost(doc.Host)
if err := sb.DetachFilesystem(hostTag, filesystemTag); err != nil {
return errors.Annotate(err, "destroying filesystem attachment")
}
}
return nil
}
func closeIter(iter mongo.Iterator, errOut *error, message string) {
err := iter.Close()
if err == nil {
return
}
err = errors.Annotate(err, message)
if *errOut == nil {
*errOut = err
return
}
logger.Errorf("%v", err)
}
func cleanupUpgradeSeriesLock(machine *Machine) error {
logger.Infof("removing any upgrade series locks for machine, %s", machine)