/
unit.go
3100 lines (2857 loc) · 96.3 KB
/
unit.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 2012-2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"fmt"
"reflect"
"sort"
"time"
"github.com/juju/charm/v12"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/mgo/v3"
"github.com/juju/mgo/v3/bson"
"github.com/juju/mgo/v3/txn"
"github.com/juju/names/v5"
jujutxn "github.com/juju/txn/v3"
"github.com/juju/utils/v3"
"github.com/juju/version/v2"
"github.com/juju/juju/core/actions"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/instance"
"github.com/juju/juju/core/model"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/status"
mgoutils "github.com/juju/juju/mongo/utils"
stateerrors "github.com/juju/juju/state/errors"
"github.com/juju/juju/tools"
)
var unitLogger = loggo.GetLogger("juju.state.unit")
// AssignmentPolicy controls what machine a unit will be assigned to.
type AssignmentPolicy string
const (
// AssignLocal indicates that all application units should be assigned
// to machine 0.
AssignLocal AssignmentPolicy = "local"
// AssignClean indicates that every application unit should be assigned
// to a machine which never previously has hosted any units, and that
// new machines should be launched if required.
AssignClean AssignmentPolicy = "clean"
// AssignCleanEmpty indicates that every application unit should be assigned
// to a machine which never previously has hosted any units, and which is not
// currently hosting any containers, and that new machines should be launched if required.
AssignCleanEmpty AssignmentPolicy = "clean-empty"
// AssignNew indicates that every application unit should be assigned to a new
// dedicated machine. A new machine will be launched for each new unit.
AssignNew AssignmentPolicy = "new"
)
// ResolvedMode describes the way state transition errors
// are resolved.
type ResolvedMode string
// These are available ResolvedMode values.
const (
ResolvedNone ResolvedMode = ""
ResolvedRetryHooks ResolvedMode = "retry-hooks"
ResolvedNoHooks ResolvedMode = "no-hooks"
)
// unitDoc represents the internal state of a unit in MongoDB.
// Note the correspondence with UnitInfo in core/multiwatcher.
type unitDoc struct {
DocID string `bson:"_id"`
Name string `bson:"name"`
ModelUUID string `bson:"model-uuid"`
Base Base `bson:"base"`
Application string
CharmURL *string
Principal string
Subordinates []string
StorageAttachmentCount int `bson:"storageattachmentcount"`
MachineId string
Resolved ResolvedMode
Tools *tools.Tools `bson:",omitempty"`
Life Life
PasswordHash string
}
// Unit represents the state of an application unit.
type Unit struct {
st *State
doc unitDoc
// Cache the model type as it is immutable as is referenced
// during the lifecycle of the unit.
modelType ModelType
}
func newUnit(st *State, modelType ModelType, udoc *unitDoc) *Unit {
unit := &Unit{
st: st,
doc: *udoc,
modelType: modelType,
}
return unit
}
// ContainerInfo returns information about the containing hosting this unit.
// This is only used for CAAS models.
func (u *Unit) ContainerInfo() (CloudContainer, error) {
doc, err := u.cloudContainer()
if err != nil {
return nil, errors.Trace(err)
}
return &cloudContainer{doc: *doc, unitName: u.Name()}, nil
}
// ShouldBeAssigned returns whether the unit should be assigned to a machine.
// IAAS models require units to be assigned.
func (u *Unit) ShouldBeAssigned() bool {
return !u.isCaas()
}
func (u *Unit) isCaas() bool {
return u.modelType == ModelTypeCAAS
}
// IsSidecar returns true when using new CAAS charms in sidecar mode.
func (u *Unit) IsSidecar() (bool, error) {
app, err := u.Application()
if err != nil {
return false, errors.Trace(err)
}
return app.IsSidecar()
}
// Application returns the application.
func (u *Unit) Application() (*Application, error) {
return u.st.Application(u.doc.Application)
}
// ConfigSettings returns the complete set of application charm config settings
// available to the unit. Unset values will be replaced with the default
// value for the associated option, and may thus be nil when no default is
// specified.
func (u *Unit) ConfigSettings() (charm.Settings, error) {
if u.doc.CharmURL == nil {
return nil, fmt.Errorf("unit's charm URL must be set before retrieving config")
}
// TODO (manadart 2019-02-21) Factor the current generation into this call.
s, err := charmSettingsWithDefaults(u.st, u.doc.CharmURL, u.doc.Application, model.GenerationMaster)
if err != nil {
return nil, errors.Annotatef(err, "charm config for unit %q", u.Name())
}
return s, nil
}
// ApplicationName returns the application name.
func (u *Unit) ApplicationName() string {
return u.doc.Application
}
// Base returns the deployed charm's base.
func (u *Unit) Base() Base {
return u.doc.Base
}
// String returns the unit as string.
func (u *Unit) String() string {
return u.doc.Name
}
// Name returns the unit name.
func (u *Unit) Name() string {
return u.doc.Name
}
// unitGlobalKey returns the global database key for the named unit.
func unitGlobalKey(name string) string {
return "u#" + name + "#charm"
}
// globalWorkloadVersionKey returns the global database key for the
// workload version status key for this unit.
func globalWorkloadVersionKey(name string) string {
return unitGlobalKey(name) + "#sat#workload-version"
}
// globalAgentKey returns the global database key for the unit.
func (u *Unit) globalAgentKey() string {
return unitAgentGlobalKey(u.doc.Name)
}
// globalMeterStatusKey returns the global database key for the meter status of the unit.
func (u *Unit) globalMeterStatusKey() string {
return unitAgentGlobalKey(u.doc.Name)
}
// globalKey returns the global database key for the unit.
func (u *Unit) globalKey() string {
return unitGlobalKey(u.doc.Name)
}
// globalWorkloadVersionKey returns the global database key for the unit's
// workload version info.
func (u *Unit) globalWorkloadVersionKey() string {
return globalWorkloadVersionKey(u.doc.Name)
}
// globalCloudContainerKey returns the global database key for the unit's
// Cloud Container info.
func (u *Unit) globalCloudContainerKey() string {
return globalCloudContainerKey(u.doc.Name)
}
// Life returns whether the unit is Alive, Dying or Dead.
func (u *Unit) Life() Life {
return u.doc.Life
}
// WorkloadVersion returns the version of the running workload set by
// the charm (eg, the version of postgresql that is running, as
// opposed to the version of the postgresql charm).
func (u *Unit) WorkloadVersion() (string, error) {
unitStatus, err := getStatus(u.st.db(), u.globalWorkloadVersionKey(), "workload")
if errors.IsNotFound(err) {
return "", nil
} else if err != nil {
return "", errors.Trace(err)
}
return unitStatus.Message, nil
}
// SetWorkloadVersion sets the version of the workload that the unit
// is currently running.
func (u *Unit) SetWorkloadVersion(version string) error {
// Store in status rather than an attribute of the unit doc - we
// want to avoid everything being an attr of the main docs to
// stop a swarm of watchers being notified for irrelevant changes.
now := u.st.clock().Now()
return setStatus(u.st.db(), setStatusParams{
badge: "workload",
globalKey: u.globalWorkloadVersionKey(),
status: status.Active,
message: version,
updated: &now,
})
}
// WorkloadVersionHistory returns a HistoryGetter which enables the
// caller to request past workload version changes.
func (u *Unit) WorkloadVersionHistory() *HistoryGetter {
return &HistoryGetter{st: u.st, globalKey: u.globalWorkloadVersionKey()}
}
// AgentTools returns the tools that the agent is currently running.
// It an error that satisfies errors.IsNotFound if the tools have not
// yet been set.
func (u *Unit) AgentTools() (*tools.Tools, error) {
if u.doc.Tools == nil {
return nil, errors.NotFoundf("agent binaries for unit %q", u)
}
result := *u.doc.Tools
return &result, nil
}
// SetAgentVersion sets the version of juju that the agent is
// currently running.
func (u *Unit) SetAgentVersion(v version.Binary) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set agent version for unit %q", u)
if err = checkVersionValidity(v); err != nil {
return err
}
versionedTool := &tools.Tools{Version: v}
ops := []txn.Op{{
C: unitsC,
Id: u.doc.DocID,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"tools", versionedTool}}}},
}}
if err := u.st.db().RunTransaction(ops); err != nil {
return onAbort(err, stateerrors.ErrDead)
}
u.doc.Tools = versionedTool
return nil
}
// SetPassword sets the password for the machine's agent.
func (u *Unit) SetPassword(password string) error {
if len(password) < utils.MinAgentPasswordLength {
return fmt.Errorf("password is only %d bytes long, and is not a valid Agent password", len(password))
}
return u.setPasswordHash(utils.AgentPasswordHash(password))
}
// setPasswordHash sets the underlying password hash in the database directly
// to the value supplied. This is split out from SetPassword to allow direct
// manipulation in tests (to check for backwards compatibility).
func (u *Unit) setPasswordHash(passwordHash string) error {
ops := u.setPasswordHashOps(passwordHash)
err := u.st.db().RunTransaction(ops)
if err != nil {
return fmt.Errorf("cannot set password of unit %q: %v", u, onAbort(err, stateerrors.ErrDead))
}
u.doc.PasswordHash = passwordHash
return nil
}
func (u *Unit) setPasswordHashOps(passwordHash string) []txn.Op {
return []txn.Op{{
C: unitsC,
Id: u.doc.DocID,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"passwordhash", passwordHash}}}},
}}
}
// PasswordValid returns whether the given password is valid
// for the given unit.
func (u *Unit) PasswordValid(password string) bool {
agentHash := utils.AgentPasswordHash(password)
if agentHash == u.doc.PasswordHash {
return true
}
// Increased error logging for LP: 1956975 agent lost due to ErrBadCreds.
// Usually found 1-3 months after it happened. It would be helpful to have
// additional data we can go back and find.
if agentHash == "" {
logger.Errorf("%q invalid password, provided agent hash empty", u.Name())
return false
}
if u.doc.PasswordHash == "" {
logger.Errorf("%q invalid password, doc password hash empty", u.Name())
return false
}
app, err := u.Application()
if err != nil {
logger.Errorf("%q invalid password, error getting application: %s", u.Name(), err.Error())
return false
}
units, err := app.AllUnits()
if err != nil {
logger.Errorf("%q invalid password, error getting all units: %s", app.Name(), err.Error())
return false
}
for _, unit := range units {
if u.Name() != unit.Name() && agentHash == unit.doc.PasswordHash {
logger.Errorf("%q invalid password, provided agent hash matches %q password hash", u.Name(), unit.Name())
}
}
return false
}
// UpdateOperation returns a model operation that will update a unit.
func (u *Unit) UpdateOperation(props UnitUpdateProperties) *UpdateUnitOperation {
return &UpdateUnitOperation{
unit: &Unit{st: u.st, doc: u.doc, modelType: u.modelType},
props: props,
}
}
// UpdateUnitOperation is a model operation for updating a unit.
type UpdateUnitOperation struct {
unit *Unit
props UnitUpdateProperties
setStatusDocs map[string]statusDoc
}
// Build is part of the ModelOperation interface.
func (op *UpdateUnitOperation) Build(_ int) ([]txn.Op, error) {
op.setStatusDocs = make(map[string]statusDoc)
containerInfo, err := op.unit.cloudContainer()
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
if containerInfo == nil {
containerInfo = &cloudContainerDoc{
Id: op.unit.globalKey(),
}
}
existingContainerInfo := *containerInfo
var newProviderId string
if op.props.ProviderId != nil {
newProviderId = *op.props.ProviderId
}
if containerInfo.ProviderId != "" &&
newProviderId != "" &&
containerInfo.ProviderId != newProviderId {
logger.Debugf("unit %q has provider id %q which changed to %q",
op.unit.Name(), containerInfo.ProviderId, newProviderId)
}
if op.props.ProviderId != nil {
containerInfo.ProviderId = newProviderId
}
if op.props.Address != nil {
networkAddr := network.NewSpaceAddress(*op.props.Address, network.WithScope(network.ScopeMachineLocal))
addr := fromNetworkAddress(networkAddr, network.OriginProvider)
containerInfo.Address = &addr
}
if op.props.Ports != nil {
containerInfo.Ports = *op.props.Ports
}
// Currently, we only update container attributes but that might change.
var ops []txn.Op
if !reflect.DeepEqual(*containerInfo, existingContainerInfo) {
containerOps, err := op.unit.saveContainerOps(*containerInfo)
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops, containerOps...)
}
updateStatus := func(key, badge string, status *status.StatusInfo) error {
now := op.unit.st.clock().Now()
doc := statusDoc{
Status: status.Status,
StatusInfo: status.Message,
StatusData: mgoutils.EscapeKeys(status.Data),
Updated: now.UnixNano(),
}
op.setStatusDocs[key] = doc
// It's possible we're getting a first status update (i.e. cloud container)
_, err = getStatus(op.unit.st.db(), key, badge)
if err != nil {
if !errors.IsNotFound(err) {
return errors.Trace(err)
}
statusOps := createStatusOp(op.unit.st, key, doc)
ops = append(ops, statusOps)
} else {
statusOps, err := statusSetOps(op.unit.st.db(), doc, key)
if err != nil {
return errors.Trace(err)
}
ops = append(ops, statusOps...)
}
return nil
}
if op.props.AgentStatus != nil {
if err := updateStatus(op.unit.globalAgentKey(), "agent", op.props.AgentStatus); err != nil {
return nil, errors.Trace(err)
}
}
var cloudContainerStatus status.StatusInfo
if op.props.CloudContainerStatus != nil {
if err := updateStatus(op.unit.globalCloudContainerKey(), "cloud container", op.props.CloudContainerStatus); err != nil {
return nil, errors.Trace(err)
}
cloudContainerStatus = *op.props.CloudContainerStatus
}
if cloudContainerStatus.Status != "" {
// Since we have updated cloud container, that may impact on
// the perceived unit status. we'll update status history if the
// unit status is different due to having a cloud container status.
// This correctly ensures the status history goes from "waiting for
// container" to <something else>.
unitStatus, err := getStatus(op.unit.st.db(), op.unit.globalKey(), "unit")
if err != nil {
return nil, errors.Trace(err)
}
modifiedStatus := status.UnitDisplayStatus(unitStatus, cloudContainerStatus, true)
now := op.unit.st.clock().Now()
doc := statusDoc{
Status: modifiedStatus.Status,
StatusInfo: modifiedStatus.Message,
StatusData: mgoutils.EscapeKeys(modifiedStatus.Data),
Updated: now.UnixNano(),
}
op.setStatusDocs[op.unit.globalKey()] = doc
}
return ops, nil
}
// Done is part of the ModelOperation interface.
func (op *UpdateUnitOperation) Done(err error) error {
if err != nil {
return errors.Annotatef(err, "updating unit %q", op.unit.Name())
}
// We can't include in the ops slice the necessary status history updates,
// so as with existing practice, do a best effort update of status history.
for key, doc := range op.setStatusDocs {
_, _ = probablyUpdateStatusHistory(op.unit.st.db(), key, doc)
}
return nil
}
// Destroy, when called on a Alive unit, advances its lifecycle as far as
// possible; it otherwise has no effect. In most situations, the unit's
// life is just set to Dying; but if a principal unit that is not assigned
// to a provisioned machine is Destroyed, it will be removed from state
// directly.
func (u *Unit) Destroy() error {
errs, err := u.DestroyWithForce(false, time.Duration(0))
if len(errs) != 0 {
logger.Warningf("operational errors destroying unit %v: %v", u.Name(), errs)
}
return err
}
// DestroyWithForce does the same thing as Destroy() but
// ignores errors.
func (u *Unit) DestroyWithForce(force bool, maxWait time.Duration) (errs []error, err error) {
defer func() {
if err == nil {
// This is a white lie; the document might actually be removed.
u.doc.Life = Dying
}
}()
op := u.DestroyOperation()
op.Force = force
op.MaxWait = maxWait
err = u.st.ApplyOperation(op)
return op.Errors, err
}
// DestroyOperation returns a model operation that will destroy the unit.
func (u *Unit) DestroyOperation() *DestroyUnitOperation {
return &DestroyUnitOperation{
unit: &Unit{st: u.st, doc: u.doc, modelType: u.modelType},
}
}
// DestroyUnitOperation is a model operation for destroying a unit.
type DestroyUnitOperation struct {
// ForcedOperation stores needed information to force this operation.
ForcedOperation
// unit holds the unit to destroy.
unit *Unit
// DestroyStorage controls whether or not storage attached
// to the unit is destroyed. If this is false, then detachable
// storage will be detached and left in the model.
DestroyStorage bool
}
// Build is part of the ModelOperation interface.
func (op *DestroyUnitOperation) Build(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err := op.unit.Refresh(); errors.IsNotFound(err) {
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, err
}
}
// When 'force' is set on the operation, this call will return both needed operations
// as well as all operational errors encountered.
// If the 'force' is not set, any error will be fatal and no operations will be returned.
switch ops, err := op.destroyOps(); err {
case errRefresh:
case errAlreadyDying:
return nil, jujutxn.ErrNoOperations
case nil:
return ops, nil
default:
if op.Force {
logger.Warningf("forcing unit destruction for %v despite error %v", op.unit.Name(), err)
return ops, nil
}
return nil, err
}
return nil, jujutxn.ErrNoOperations
}
// Done is part of the ModelOperation interface.
func (op *DestroyUnitOperation) Done(err error) error {
if err != nil {
if !op.Force {
return errors.Annotatef(err, "cannot destroy unit %q", op.unit)
}
op.AddError(errors.Errorf("force destroy unit %q proceeded despite encountering ERROR %v", op.unit, err))
}
if err := op.eraseHistory(); err != nil {
if !op.Force {
logger.Errorf("cannot delete history for unit %q: %v", op.unit.globalKey(), err)
}
op.AddError(errors.Errorf("force erase unit's %q history proceeded despite encountering ERROR %v", op.unit.globalKey(), err))
}
if err := op.deleteSecrets(); err != nil {
logger.Errorf("cannot delete secrets for unit %q: %v", op.unit, err)
}
return nil
}
func (op *DestroyUnitOperation) eraseHistory() error {
var stop <-chan struct{} // stop not used here yet.
if err := eraseStatusHistory(stop, op.unit.st, op.unit.globalKey()); err != nil {
one := errors.Annotate(err, "workload")
if op.FatalError(one) {
return one
}
}
if err := eraseStatusHistory(stop, op.unit.st, op.unit.globalAgentKey()); err != nil {
one := errors.Annotate(err, "agent")
if op.FatalError(one) {
return one
}
}
if err := eraseStatusHistory(stop, op.unit.st, op.unit.globalWorkloadVersionKey()); err != nil {
one := errors.Annotate(err, "version")
if op.FatalError(one) {
return one
}
}
return nil
}
func (op *DestroyUnitOperation) deleteSecrets() error {
ownedURIs, err := op.unit.st.referencedSecrets(op.unit.Tag(), "owner-tag")
if err != nil {
return errors.Trace(err)
}
if _, err := op.unit.st.deleteSecrets(ownedURIs); err != nil {
return errors.Annotatef(err, "deleting owned secrets for %q", op.unit.Name())
}
if err := op.unit.st.RemoveSecretConsumer(op.unit.Tag()); err != nil {
return errors.Annotatef(err, "deleting secret consumer records for %q", op.unit.Name())
}
return nil
}
// destroyOps returns the operations required to destroy the unit. If it
// returns errRefresh, the unit should be refreshed and the destruction
// operations recalculated.
// When 'force' is set on the operation, this call will return both needed operations
// as well as all operational errors encountered.
// If the 'force' is not set, any error will be fatal and no operations will be returned.
func (op *DestroyUnitOperation) destroyOps() ([]txn.Op, error) {
if op.unit.doc.Life != Alive {
if !op.Force {
return nil, errAlreadyDying
}
}
// Where possible, we'd like to be able to short-circuit unit destruction
// such that units can be removed directly rather than waiting for their
// agents to start, observe Dying, set Dead, and shut down; this takes a
// long time and is vexing to users. This turns out to be possible if and
// only if the unit agent has not yet set its status; this implies that the
// most the unit could possibly have done is to run its install hook.
//
// There's no harm in removing a unit that's run its install hook only --
// or, at least, there is no more harm than there is in removing a unit
// that's run its stop hook, and that's the usual condition.
//
// Principals with subordinates are never eligible for this shortcut,
// because the unit agent must inevitably have set a status before getting
// to the point where it can actually create its subordinate.
//
// Subordinates should be eligible for the shortcut but are not currently
// considered, on the basis that (1) they were created by active principals
// and can be expected to be deployed pretty soon afterwards, so we don't
// lose much time and (2) by maintaining this restriction, I can reduce
// the number of tests that have to change and defer that improvement to
// its own CL.
// if the minUnits document exists, we need to increment the revno so that
// it is obvious the min units count is changing.
minUnitsOp := minUnitsTriggerOp(op.unit.st, op.unit.ApplicationName())
minUnitsExists, err := doesMinUnitsExist(op.unit.st, op.unit.ApplicationName())
if err != nil {
return nil, errors.Trace(err)
}
cleanupOp := newCleanupOp(cleanupDyingUnit, op.unit.doc.Name, op.DestroyStorage, op.Force, op.MaxWait)
// If we're forcing destruction the assertion shouldn't be that
// life is alive, but that it's what we think it is now.
assertion := isAliveDoc
if op.Force {
assertion = bson.D{{"life", op.unit.doc.Life}}
}
setDyingOp := txn.Op{
C: unitsC,
Id: op.unit.doc.DocID,
Assert: assertion,
Update: bson.D{{"$set", bson.D{{"life", Dying}}}},
}
setDyingOps := func(dyingErr error) ([]txn.Op, error) {
if !op.Force && dyingErr != nil {
// If we are not forcing removal, we care about the errors as they will stop removal.
// Don't return operations.
return nil, dyingErr
}
// If we are forcing, we care about the errors as we want report them to the user.
// But we also want operations to power through the removal.
if dyingErr != nil {
op.AddError(errors.Errorf("force destroying dying unit %v despite error %v", op.unit.Name(), dyingErr))
}
ops := []txn.Op{setDyingOp, cleanupOp}
if minUnitsExists {
ops = append(ops, minUnitsOp)
}
return ops, nil
}
if op.unit.doc.Principal != "" {
return setDyingOps(nil)
} else if len(op.unit.doc.Subordinates)+op.unit.doc.StorageAttachmentCount != 0 {
return setDyingOps(nil)
}
// See if the unit agent has started running.
// If so then we can't set directly to dead.
isAssigned := op.unit.doc.MachineId != ""
shouldBeAssigned := op.unit.ShouldBeAssigned()
agentStatusDocId := op.unit.globalAgentKey()
agentStatusInfo, agentErr := getStatus(op.unit.st.db(), agentStatusDocId, "agent")
if errors.IsNotFound(agentErr) {
return nil, errAlreadyDying
} else if agentErr != nil {
if !op.Force {
return nil, errors.Trace(agentErr)
}
}
// This has to be a function since we want to delay the evaluation of the value,
// in case agent erred out.
isReady := func() (bool, error) {
// IAAS models need the unit to be assigned.
if shouldBeAssigned {
return isAssigned && agentStatusInfo.Status != status.Allocating, nil
}
// For CAAS models, check to see if the unit agent has started (the
// presence of the unitstates row indicates this).
unitState, err := op.unit.State()
if err != nil {
return false, errors.Trace(err)
}
return unitState.Modified(), nil
}
if agentErr == nil {
ready, err := isReady()
if op.FatalError(err) {
return nil, errors.Trace(err)
}
if ready {
return setDyingOps(agentErr)
}
}
switch agentStatusInfo.Status {
case status.Error, status.Allocating:
default:
err := errors.Errorf("unexpected unit state - unit with status %v is not deployed", agentStatusInfo.Status)
if op.FatalError(err) {
return nil, err
}
}
statusOp := txn.Op{
C: statusesC,
Id: op.unit.st.docID(agentStatusDocId),
Assert: bson.D{{"status", agentStatusInfo.Status}},
}
removeAsserts := isAliveDoc
if op.Force {
removeAsserts = bson.D{{"life", op.unit.doc.Life}}
}
removeAsserts = append(removeAsserts, bson.DocElem{
"$and", []bson.D{
unitHasNoSubordinates,
unitHasNoStorageAttachments,
},
})
// If the unit is unassigned, ensure it is not assigned in the interim.
if !isAssigned && shouldBeAssigned {
removeAsserts = append(removeAsserts, bson.DocElem{"machineid", ""})
}
// When 'force' is set, this call will return some, if not all, needed operations.
// All operational errors encountered will be added to the operation.
// If the 'force' is not set, any error will be fatal and no operations will be returned.
removeOps, err := op.unit.removeOps(removeAsserts, &op.ForcedOperation, op.DestroyStorage)
if err == errAlreadyRemoved {
return nil, errAlreadyDying
} else if op.FatalError(err) {
return nil, err
}
ops := []txn.Op{statusOp}
if minUnitsExists {
ops = append(ops, minUnitsOp)
}
ops = append(ops, removeOps...)
return ops, nil
}
// destroyHostOps returns all necessary operations to destroy the application unit's host machine,
// or ensure that the conditions preventing its destruction remain stable through the transaction.
// When 'force' is set, this call will return needed operations
// and accumulate all operational errors encountered on the operation.
// If the 'force' is not set, any error will be fatal and no operations will be returned.
func (u *Unit) destroyHostOps(a *Application, op *ForcedOperation) (ops []txn.Op, err error) {
if a.doc.Subordinate {
return []txn.Op{{
C: unitsC,
Id: u.st.docID(u.doc.Principal),
Assert: txn.DocExists,
Update: bson.D{{"$pull", bson.D{{"subordinates", u.doc.Name}}}},
}}, nil
} else if u.doc.MachineId == "" {
unitLogger.Tracef("unit %v unassigned", u)
return nil, nil
}
m, err := u.st.Machine(u.doc.MachineId)
if err != nil {
if errors.IsNotFound(err) {
return nil, nil
}
return nil, err
}
node, err := u.st.ControllerNode(u.doc.MachineId)
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
haveControllerNode := err == nil
hasVote := haveControllerNode && node.HasVote()
containerCheck := true // whether container conditions allow destroying the host machine
containers, err := m.Containers()
if op.FatalError(err) {
return nil, err
}
if len(containers) > 0 {
ops = append(ops, txn.Op{
C: containerRefsC,
Id: m.doc.DocID,
Assert: bson.D{{"children.0", bson.D{{"$exists", 1}}}},
})
containerCheck = false
} else {
ops = append(ops, txn.Op{
C: containerRefsC,
Id: m.doc.DocID,
Assert: bson.D{{"$or", []bson.D{
{{"children", bson.D{{"$size", 0}}}},
{{"children", bson.D{{"$exists", false}}}},
}}},
})
}
isController := m.IsManager()
machineCheck := true // whether host machine conditions allow destroy
if len(m.doc.Principals) != 1 || m.doc.Principals[0] != u.doc.Name {
machineCheck = false
} else if isController {
// Check that the machine does not have any responsibilities that
// prevent a lifecycle change.
machineCheck = false
} else if hasVote {
machineCheck = false
}
// assert that the machine conditions pertaining to host removal conditions
// remain the same throughout the transaction.
var machineAssert bson.D
var controllerNodeAssert interface{}
if machineCheck {
machineAssert = bson.D{{"$and", []bson.D{
{{"principals", []string{u.doc.Name}}},
{{"jobs", bson.D{{"$nin", []MachineJob{JobManageModel}}}}},
}}}
controllerNodeAssert = txn.DocMissing
if haveControllerNode {
controllerNodeAssert = bson.D{{"has-vote", false}}
}
} else {
machineAssert = bson.D{{"$or", []bson.D{
{{"principals", bson.D{{"$ne", []string{u.doc.Name}}}}},
{{"jobs", bson.D{{"$in", []MachineJob{JobManageModel}}}}},
}}}
if isController {
controllerNodeAssert = txn.DocExists
}
}
// If removal conditions satisfied by machine & container docs, we can
// destroy it, in addition to removing the unit principal.
machineUpdate := bson.D{{"$pull", bson.D{{"principals", u.doc.Name}}}}
var cleanupOps []txn.Op
if machineCheck && containerCheck {
machineUpdate = append(machineUpdate, bson.D{{"$set", bson.D{{"life", Dying}}}}...)
if !op.Force {
cleanupOps = []txn.Op{newCleanupOp(cleanupDyingMachine, m.doc.Id, op.Force)}
} else {
cleanupOps = []txn.Op{newCleanupOp(cleanupForceDestroyedMachine, m.doc.Id, op.MaxWait)}
}
}
ops = append(ops, txn.Op{
C: machinesC,
Id: m.doc.DocID,
Assert: machineAssert,
Update: machineUpdate,
})
if controllerNodeAssert != nil {
ops = append(ops, txn.Op{
C: controllerNodesC,
Id: m.st.docID(m.Id()),
Assert: controllerNodeAssert,
})
}
return append(ops, cleanupOps...), nil
}
// removeOps returns the operations necessary to remove the unit, assuming
// the supplied asserts apply to the unit document.
// When 'force' is set, this call will return needed operations
// accumulating all operational errors in the operation.
// If the 'force' is not set, any error will be fatal and no operations will be returned.
func (u *Unit) removeOps(asserts bson.D, op *ForcedOperation, destroyStorage bool) ([]txn.Op, error) {
app, err := u.st.Application(u.doc.Application)
if errors.IsNotFound(err) {
// If the application has been removed, the unit must already have been.
return nil, errAlreadyRemoved
} else if err != nil {
// If we cannot find application, no amount of force will succeed after this point.
return nil, err
}
return app.removeUnitOps(u, asserts, op, destroyStorage)
}
var unitHasNoSubordinates = bson.D{{
"$or", []bson.D{
{{"subordinates", bson.D{{"$size", 0}}}},
{{"subordinates", bson.D{{"$exists", false}}}},
},
}}
var unitHasNoStorageAttachments = bson.D{{
"$or", []bson.D{
{{"storageattachmentcount", 0}},
{{"storageattachmentcount", bson.D{{"$exists", false}}}},
},
}}
// EnsureDead sets the unit lifecycle to Dead if it is Alive or Dying.
// It does nothing otherwise. If the unit has subordinates, it will
// return ErrUnitHasSubordinates; otherwise, if it has storage instances,
// it will return ErrUnitHasStorageInstances.
func (u *Unit) EnsureDead() (err error) {
if u.doc.Life == Dead {
return nil
}
defer func() {
if err == nil {
u.doc.Life = Dead
}
}()
assert := append(notDeadDoc, bson.DocElem{
"$and", []bson.D{
unitHasNoSubordinates,
unitHasNoStorageAttachments,
},
})
ops := []txn.Op{{
C: unitsC,
Id: u.doc.DocID,
Assert: assert,
Update: bson.D{{"$set", bson.D{{"life", Dead}}}},
}}
if err := u.st.db().RunTransaction(ops); err != txn.ErrAborted {
return err
}
if notDead, err := isNotDead(u.st, unitsC, u.doc.DocID); err != nil {
return err
} else if !notDead {
return nil
}
if err := u.Refresh(); errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
if len(u.doc.Subordinates) > 0 {
return stateerrors.ErrUnitHasSubordinates
}
return stateerrors.ErrUnitHasStorageAttachments
}
// RemoveOperation returns a model operation that will remove the unit.
func (u *Unit) RemoveOperation(force bool) *RemoveUnitOperation {
return &RemoveUnitOperation{
unit: &Unit{st: u.st, doc: u.doc, modelType: u.modelType},
ForcedOperation: ForcedOperation{Force: force},
}
}
// RemoveUnitOperation is a model operation for removing a unit.
type RemoveUnitOperation struct {
// ForcedOperation stores needed information to force this operation.
ForcedOperation