-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunit.go
1483 lines (1377 loc) · 44.1 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, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
stderrors "errors"
"fmt"
"time"
"github.com/juju/errors"
"github.com/juju/loggo"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"labix.org/v2/mgo/txn"
"github.com/juju/core/charm"
"github.com/juju/core/constraints"
"github.com/juju/core/instance"
"github.com/juju/core/names"
"github.com/juju/core/state/api/params"
"github.com/juju/core/state/presence"
"github.com/juju/core/tools"
"github.com/juju/core/utils"
"github.com/juju/core/version"
)
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 service units should be assigned
// to machine 0.
AssignLocal AssignmentPolicy = "local"
// AssignClean indicates that every service 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 service 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 service 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
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 state/api/params.
type unitDoc struct {
Name string `bson:"_id"`
Service string
Series string
CharmURL *charm.URL
Principal string
Subordinates []string
MachineId string
Resolved ResolvedMode
Tools *tools.Tools `bson:",omitempty"`
Ports []instance.Port
Life Life
TxnRevno int64 `bson:"txn-revno"`
PasswordHash string
// No longer used - to be removed.
PublicAddress string
PrivateAddress string
}
// Unit represents the state of a service unit.
type Unit struct {
st *State
doc unitDoc
annotator
}
func newUnit(st *State, udoc *unitDoc) *Unit {
unit := &Unit{
st: st,
doc: *udoc,
}
unit.annotator = annotator{
globalKey: unit.globalKey(),
tag: unit.Tag(),
st: st,
}
return unit
}
// Service returns the service.
func (u *Unit) Service() (*Service, error) {
return u.st.Service(u.doc.Service)
}
// ConfigSettings returns the complete set of service 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 charm not set")
}
settings, err := readSettings(u.st, serviceSettingsKey(u.doc.Service, u.doc.CharmURL))
if err != nil {
return nil, err
}
chrm, err := u.st.Charm(u.doc.CharmURL)
if err != nil {
return nil, err
}
result := chrm.Config().DefaultSettings()
for name, value := range settings.Map() {
result[name] = value
}
return result, nil
}
// ServiceName returns the service name.
func (u *Unit) ServiceName() string {
return u.doc.Service
}
// Series returns the deployed charm's series.
func (u *Unit) Series() string {
return u.doc.Series
}
// 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
}
// globalKey returns the global database key for the unit.
func (u *Unit) globalKey() string {
return unitGlobalKey(u.doc.Name)
}
// Life returns whether the unit is Alive, Dying or Dead.
func (u *Unit) Life() Life {
return u.doc.Life
}
// 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 tools for unit %q", u)
}
tools := *u.doc.Tools
return &tools, nil
}
// SetAgentVersion sets the version of juju that the agent is
// currently running.
func (u *Unit) SetAgentVersion(v version.Binary) (err error) {
defer errors.Maskf(&err, "cannot set agent version for unit %q", u)
if err = checkVersionValidity(v); err != nil {
return err
}
tools := &tools.Tools{Version: v}
ops := []txn.Op{{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"tools", tools}}}},
}}
if err := u.st.runTransaction(ops); err != nil {
return onAbort(err, errDead)
}
u.doc.Tools = tools
return nil
}
// SetMongoPassword sets the password the agent responsible for the unit
// should use to communicate with the state servers. Previous passwords
// are invalidated.
func (u *Unit) SetMongoPassword(password string) error {
return u.st.setMongoPassword(u.Tag(), password)
}
// 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 := []txn.Op{{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"passwordhash", passwordHash}}}},
}}
err := u.st.runTransaction(ops)
if err != nil {
return fmt.Errorf("cannot set password of unit %q: %v", u, onAbort(err, errDead))
}
u.doc.PasswordHash = passwordHash
return nil
}
// Return the underlying PasswordHash stored in the database. Used by the test
// suite to check that the PasswordHash gets properly updated to new values
// when compatibility mode is detected.
func (u *Unit) getPasswordHash() string {
return u.doc.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
}
// In Juju 1.16 and older we used the slower password hash for unit
// agents. So check to see if the supplied password matches the old
// path, and if so, update it to the new mechanism.
// We ignore any error in setting the password hash, as we'll just try
// again next time
if utils.UserPasswordHash(password, utils.CompatSalt) == u.doc.PasswordHash {
logger.Debugf("%s logged in with old password hash, changing to AgentPasswordHash",
u.Tag())
u.setPasswordHash(agentHash)
return true
}
return false
}
// 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() (err error) {
defer func() {
if err == nil {
// This is a white lie; the document might actually be removed.
u.doc.Life = Dying
}
}()
unit := &Unit{st: u.st, doc: u.doc}
for i := 0; i < 5; i++ {
switch ops, err := unit.destroyOps(); err {
case errRefresh:
case errAlreadyDying:
return nil
case nil:
if err := unit.st.runTransaction(ops); err != txn.ErrAborted {
return err
}
default:
return err
}
if err := unit.Refresh(); errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
}
return ErrExcessiveContention
}
// destroyOps returns the operations required to destroy the unit. If it
// returns errRefresh, the unit should be refreshed and the destruction
// operations recalculated.
func (u *Unit) destroyOps() ([]txn.Op, error) {
if u.doc.Life != Alive {
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.
minUnitsOp := minUnitsTriggerOp(u.st, u.ServiceName())
cleanupOp := u.st.newCleanupOp(cleanupDyingUnit, u.doc.Name)
setDyingOps := []txn.Op{{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: isAliveDoc,
Update: bson.D{{"$set", bson.D{{"life", Dying}}}},
}, cleanupOp, minUnitsOp}
if u.doc.Principal != "" {
return setDyingOps, nil
} else if len(u.doc.Subordinates) != 0 {
return setDyingOps, nil
}
sdocId := u.globalKey()
sdoc, err := getStatus(u.st, sdocId)
if errors.IsNotFound(err) {
return nil, errAlreadyDying
} else if err != nil {
return nil, err
}
if sdoc.Status != params.StatusPending {
return setDyingOps, nil
}
ops := []txn.Op{{
C: u.st.statuses.Name,
Id: sdocId,
Assert: bson.D{{"status", params.StatusPending}},
}, minUnitsOp}
removeAsserts := append(isAliveDoc, unitHasNoSubordinates...)
removeOps, err := u.removeOps(removeAsserts)
if err == errAlreadyRemoved {
return nil, errAlreadyDying
} else if err != nil {
return nil, err
}
return append(ops, removeOps...), nil
}
var errAlreadyRemoved = stderrors.New("entity has already been removed")
// removeOps returns the operations necessary to remove the unit, assuming
// the supplied asserts apply to the unit document.
func (u *Unit) removeOps(asserts bson.D) ([]txn.Op, error) {
svc, err := u.st.Service(u.doc.Service)
if errors.IsNotFound(err) {
// If the service has been removed, the unit must already have been.
return nil, errAlreadyRemoved
} else if err != nil {
return nil, err
}
return svc.removeUnitOps(u, asserts)
}
var ErrUnitHasSubordinates = stderrors.New("unit has subordinates")
var unitHasNoSubordinates = bson.D{{
"$or", []bson.D{
{{"subordinates", bson.D{{"$size", 0}}}},
{{"subordinates", 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.
func (u *Unit) EnsureDead() (err error) {
if u.doc.Life == Dead {
return nil
}
defer func() {
if err == nil {
u.doc.Life = Dead
}
}()
ops := []txn.Op{{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: append(notDeadDoc, unitHasNoSubordinates...),
Update: bson.D{{"$set", bson.D{{"life", Dead}}}},
}}
if err := u.st.runTransaction(ops); err != txn.ErrAborted {
return err
}
if notDead, err := isNotDead(u.st.units, u.doc.Name); err != nil {
return err
} else if !notDead {
return nil
}
return ErrUnitHasSubordinates
}
// Remove removes the unit from state, and may remove its service as well, if
// the service is Dying and no other references to it exist. It will fail if
// the unit is not Dead.
func (u *Unit) Remove() (err error) {
defer errors.Maskf(&err, "cannot remove unit %q", u)
if u.doc.Life != Dead {
return stderrors.New("unit is not dead")
}
// Now the unit is Dead, we can be sure that it's impossible for it to
// enter relation scopes (once it's Dying, we can be sure of this; but
// EnsureDead does not require that it already be Dying, so this is the
// only point at which we can safely backstop lp:1233457 and mitigate
// the impact of unit agent bugs that leave relation scopes occupied).
relations, err := serviceRelations(u.st, u.doc.Service)
if err != nil {
return err
}
for _, rel := range relations {
ru, err := rel.Unit(u)
if err != nil {
return err
}
if err := ru.LeaveScope(); err != nil {
return err
}
}
// Now we're sure we haven't left any scopes occupied by this unit, we
// can safely remove the document.
unit := &Unit{st: u.st, doc: u.doc}
for i := 0; i < 5; i++ {
switch ops, err := unit.removeOps(isDeadDoc); err {
case errRefresh:
case errAlreadyRemoved:
return nil
case nil:
if err := u.st.runTransaction(ops); err != txn.ErrAborted {
return err
}
default:
return err
}
if err := unit.Refresh(); errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
}
return ErrExcessiveContention
}
// Resolved returns the resolved mode for the unit.
func (u *Unit) Resolved() ResolvedMode {
return u.doc.Resolved
}
// IsPrincipal returns whether the unit is deployed in its own container,
// and can therefore have subordinate services deployed alongside it.
func (u *Unit) IsPrincipal() bool {
return u.doc.Principal == ""
}
// SubordinateNames returns the names of any subordinate units.
func (u *Unit) SubordinateNames() []string {
names := make([]string, len(u.doc.Subordinates))
copy(names, u.doc.Subordinates)
return names
}
// RelationsJoined returns the relations for which the unit has entered scope
// and neither left it nor prepared to leave it
func (u *Unit) RelationsJoined() ([]*Relation, error) {
return u.relations(func(ru *RelationUnit) (bool, error) {
return ru.Joined()
})
}
// RelationsInScope returns the relations for which the unit has entered scope
// and not left it.
func (u *Unit) RelationsInScope() ([]*Relation, error) {
return u.relations(func(ru *RelationUnit) (bool, error) {
return ru.InScope()
})
}
type relationPredicate func(ru *RelationUnit) (bool, error)
// relations implements RelationsJoined and RelationsInScope.
func (u *Unit) relations(predicate relationPredicate) ([]*Relation, error) {
candidates, err := serviceRelations(u.st, u.doc.Service)
if err != nil {
return nil, err
}
var filtered []*Relation
for _, relation := range candidates {
relationUnit, err := relation.Unit(u)
if err != nil {
return nil, err
}
if include, err := predicate(relationUnit); err != nil {
return nil, err
} else if include {
filtered = append(filtered, relation)
}
}
return filtered, nil
}
// DeployerTag returns the tag of the agent responsible for deploying
// the unit. If no such entity can be determined, false is returned.
func (u *Unit) DeployerTag() (string, bool) {
if u.doc.Principal != "" {
return names.UnitTag(u.doc.Principal), true
} else if u.doc.MachineId != "" {
return names.MachineTag(u.doc.MachineId), true
}
return "", false
}
// PrincipalName returns the name of the unit's principal.
// If the unit is not a subordinate, false is returned.
func (u *Unit) PrincipalName() (string, bool) {
return u.doc.Principal, u.doc.Principal != ""
}
// addressesOfMachine returns Addresses of the related machine if present.
func (u *Unit) addressesOfMachine() []instance.Address {
if id, err := u.AssignedMachineId(); err != nil {
unitLogger.Errorf("unit %v cannot get assigned machine: %v", u, err)
return nil
} else {
m, err := u.st.Machine(id)
if err == nil {
return m.Addresses()
}
unitLogger.Errorf("unit %v misses machine id %v", u, id)
}
return nil
}
// PublicAddress returns the public address of the unit and whether it is valid.
func (u *Unit) PublicAddress() (string, bool) {
var publicAddress string
addresses := u.addressesOfMachine()
if len(addresses) > 0 {
publicAddress = instance.SelectPublicAddress(addresses)
}
return publicAddress, publicAddress != ""
}
// PrivateAddress returns the private address of the unit and whether it is valid.
func (u *Unit) PrivateAddress() (string, bool) {
var privateAddress string
addresses := u.addressesOfMachine()
if len(addresses) > 0 {
privateAddress = instance.SelectInternalAddress(addresses, false)
}
return privateAddress, privateAddress != ""
}
// Refresh refreshes the contents of the Unit from the underlying
// state. It an error that satisfies errors.IsNotFound if the unit has
// been removed.
func (u *Unit) Refresh() error {
err := u.st.units.FindId(u.doc.Name).One(&u.doc)
if err == mgo.ErrNotFound {
return errors.NotFoundf("unit %q", u)
}
if err != nil {
return fmt.Errorf("cannot refresh unit %q: %v", u, err)
}
return nil
}
// Status returns the status of the unit.
func (u *Unit) Status() (status params.Status, info string, data params.StatusData, err error) {
doc, err := getStatus(u.st, u.globalKey())
if err != nil {
return "", "", nil, err
}
status = doc.Status
info = doc.StatusInfo
data = doc.StatusData
return
}
// SetStatus sets the status of the unit. The optional values
// allow to pass additional helpful status data.
func (u *Unit) SetStatus(status params.Status, info string, data params.StatusData) error {
doc := statusDoc{
Status: status,
StatusInfo: info,
StatusData: data,
}
if err := doc.validateSet(false); err != nil {
return err
}
ops := []txn.Op{{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: notDeadDoc,
},
updateStatusOp(u.st, u.globalKey(), doc),
}
err := u.st.runTransaction(ops)
if err != nil {
return fmt.Errorf("cannot set status of unit %q: %v", u, onAbort(err, errDead))
}
return nil
}
// OpenPort sets the policy of the port with protocol and number to be opened.
func (u *Unit) OpenPort(protocol string, number int) (err error) {
port := instance.Port{Protocol: protocol, Number: number}
defer errors.Maskf(&err, "cannot open port %v for unit %q", port, u)
ops := []txn.Op{{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: notDeadDoc,
Update: bson.D{{"$addToSet", bson.D{{"ports", port}}}},
}}
err = u.st.runTransaction(ops)
if err != nil {
return onAbort(err, errDead)
}
found := false
for _, p := range u.doc.Ports {
if p == port {
break
}
}
if !found {
u.doc.Ports = append(u.doc.Ports, port)
}
return nil
}
// ClosePort sets the policy of the port with protocol and number to be closed.
func (u *Unit) ClosePort(protocol string, number int) (err error) {
port := instance.Port{Protocol: protocol, Number: number}
defer errors.Maskf(&err, "cannot close port %v for unit %q", port, u)
ops := []txn.Op{{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: notDeadDoc,
Update: bson.D{{"$pull", bson.D{{"ports", port}}}},
}}
err = u.st.runTransaction(ops)
if err != nil {
return onAbort(err, errDead)
}
newPorts := make([]instance.Port, 0, len(u.doc.Ports))
for _, p := range u.doc.Ports {
if p != port {
newPorts = append(newPorts, p)
}
}
u.doc.Ports = newPorts
return nil
}
// OpenedPorts returns a slice containing the open ports of the unit.
func (u *Unit) OpenedPorts() []instance.Port {
ports := append([]instance.Port{}, u.doc.Ports...)
instance.SortPorts(ports)
return ports
}
// CharmURL returns the charm URL this unit is currently using.
func (u *Unit) CharmURL() (*charm.URL, bool) {
if u.doc.CharmURL == nil {
return nil, false
}
return u.doc.CharmURL, true
}
// SetCharmURL marks the unit as currently using the supplied charm URL.
// An error will be returned if the unit is dead, or the charm URL not known.
func (u *Unit) SetCharmURL(curl *charm.URL) (err error) {
defer func() {
if err == nil {
u.doc.CharmURL = curl
}
}()
if curl == nil {
return fmt.Errorf("cannot set nil charm url")
}
for i := 0; i < 5; i++ {
if notDead, err := isNotDead(u.st.units, u.doc.Name); err != nil {
return err
} else if !notDead {
return fmt.Errorf("unit %q is dead", u)
}
sel := bson.D{{"_id", u.doc.Name}, {"charmurl", curl}}
if count, err := u.st.units.Find(sel).Count(); err != nil {
return err
} else if count == 1 {
// Already set
return nil
}
if count, err := u.st.charms.FindId(curl).Count(); err != nil {
return err
} else if count < 1 {
return fmt.Errorf("unknown charm url %q", curl)
}
// Add a reference to the service settings for the new charm.
incOp, err := settingsIncRefOp(u.st, u.doc.Service, curl, false)
if err != nil {
return err
}
// Set the new charm URL.
differentCharm := bson.D{{"charmurl", bson.D{{"$ne", curl}}}}
ops := []txn.Op{
incOp,
{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: append(notDeadDoc, differentCharm...),
Update: bson.D{{"$set", bson.D{{"charmurl", curl}}}},
}}
if u.doc.CharmURL != nil {
// Drop the reference to the old charm.
decOps, err := settingsDecRefOps(u.st, u.doc.Service, u.doc.CharmURL)
if err != nil {
return err
}
ops = append(ops, decOps...)
}
if err := u.st.runTransaction(ops); err != txn.ErrAborted {
return err
}
}
return ErrExcessiveContention
}
// AgentAlive returns whether the respective remote agent is alive.
func (u *Unit) AgentAlive() (bool, error) {
return u.st.pwatcher.Alive(u.globalKey())
}
// Tag returns a name identifying the unit that is safe to use
// as a file name. The returned name will be different from other
// Tag values returned by any other entities from the same state.
func (u *Unit) Tag() string {
return names.UnitTag(u.Name())
}
// WaitAgentAlive blocks until the respective agent is alive.
func (u *Unit) WaitAgentAlive(timeout time.Duration) (err error) {
defer errors.Maskf(&err, "waiting for agent of unit %q", u)
ch := make(chan presence.Change)
u.st.pwatcher.Watch(u.globalKey(), ch)
defer u.st.pwatcher.Unwatch(u.globalKey(), ch)
for i := 0; i < 2; i++ {
select {
case change := <-ch:
if change.Alive {
return nil
}
case <-time.After(timeout):
return fmt.Errorf("still not alive after timeout")
case <-u.st.pwatcher.Dead():
return u.st.pwatcher.Err()
}
}
panic(fmt.Sprintf("presence reported dead status twice in a row for unit %q", u))
}
// SetAgentAlive signals that the agent for unit u is alive.
// It returns the started pinger.
func (u *Unit) SetAgentAlive() (*presence.Pinger, error) {
p := presence.NewPinger(u.st.presence, u.globalKey())
err := p.Start()
if err != nil {
return nil, err
}
return p, nil
}
// NotAssignedError indicates that a unit is not assigned to a machine (and, in
// the case of subordinate units, that the unit's principal is not assigned).
type NotAssignedError struct{ Unit *Unit }
func (e *NotAssignedError) Error() string {
return fmt.Sprintf("unit %q is not assigned to a machine", e.Unit)
}
// IsNotAssigned verifies that err is an instance of NotAssignedError
func IsNotAssigned(err error) bool {
_, ok := err.(*NotAssignedError)
return ok
}
// AssignedMachineId returns the id of the assigned machine.
func (u *Unit) AssignedMachineId() (id string, err error) {
if u.IsPrincipal() {
if u.doc.MachineId == "" {
return "", &NotAssignedError{u}
}
return u.doc.MachineId, nil
}
pudoc := unitDoc{}
err = u.st.units.Find(bson.D{{"_id", u.doc.Principal}}).One(&pudoc)
if err == mgo.ErrNotFound {
return "", errors.NotFoundf("principal unit %q of %q", u.doc.Principal, u)
} else if err != nil {
return "", err
}
if pudoc.MachineId == "" {
return "", &NotAssignedError{u}
}
return pudoc.MachineId, nil
}
var (
machineNotAliveErr = stderrors.New("machine is not alive")
machineNotCleanErr = stderrors.New("machine is dirty")
unitNotAliveErr = stderrors.New("unit is not alive")
alreadyAssignedErr = stderrors.New("unit is already assigned to a machine")
inUseErr = stderrors.New("machine is not unused")
)
// assignToMachine is the internal version of AssignToMachine,
// also used by AssignToUnusedMachine. It returns specific errors
// in some cases:
// - machineNotAliveErr when the machine is not alive.
// - unitNotAliveErr when the unit is not alive.
// - alreadyAssignedErr when the unit has already been assigned
// - inUseErr when the machine already has a unit assigned (if unused is true)
func (u *Unit) assignToMachine(m *Machine, unused bool) (err error) {
if u.doc.Series != m.doc.Series {
return fmt.Errorf("series does not match")
}
if u.doc.MachineId != "" {
if u.doc.MachineId != m.Id() {
return alreadyAssignedErr
}
return nil
}
if u.doc.Principal != "" {
return fmt.Errorf("unit is a subordinate")
}
canHost := false
for _, j := range m.doc.Jobs {
if j == JobHostUnits {
canHost = true
break
}
}
if !canHost {
return fmt.Errorf("machine %q cannot host units", m)
}
// assignToMachine implies assignment to an existing machine,
// which is only permitted if unit placement is supported.
if err := u.st.supportsUnitPlacement(); err != nil {
return err
}
assert := append(isAliveDoc, bson.D{
{"$or", []bson.D{
{{"machineid", ""}},
{{"machineid", m.Id()}},
}},
}...)
massert := isAliveDoc
if unused {
massert = append(massert, bson.D{{"clean", bson.D{{"$ne", false}}}}...)
}
ops := []txn.Op{{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: assert,
Update: bson.D{{"$set", bson.D{{"machineid", m.doc.Id}}}},
}, {
C: u.st.machines.Name,
Id: m.doc.Id,
Assert: massert,
Update: bson.D{{"$addToSet", bson.D{{"principals", u.doc.Name}}}, {"$set", bson.D{{"clean", false}}}},
}}
err = u.st.runTransaction(ops)
if err == nil {
u.doc.MachineId = m.doc.Id
m.doc.Clean = false
return nil
}
if err != txn.ErrAborted {
return err
}
u0, err := u.st.Unit(u.Name())
if err != nil {
return err
}
m0, err := u.st.Machine(m.Id())
if err != nil {
return err
}
switch {
case u0.Life() != Alive:
return unitNotAliveErr
case m0.Life() != Alive:
return machineNotAliveErr
case u0.doc.MachineId != "" || !unused:
return alreadyAssignedErr
}
return inUseErr
}
func assignContextf(err *error, unit *Unit, target string) {
if *err != nil {
*err = fmt.Errorf("cannot assign unit %q to %s: %v", unit, target, *err)
}
}
// AssignToMachine assigns this unit to a given machine.
func (u *Unit) AssignToMachine(m *Machine) (err error) {
defer assignContextf(&err, u, fmt.Sprintf("machine %s", m))
return u.assignToMachine(m, false)
}
// assignToNewMachine assigns the unit to a machine created according to
// the supplied params, with the supplied constraints.
func (u *Unit) assignToNewMachine(template MachineTemplate, parentId string, containerType instance.ContainerType) error {
template.principals = []string{u.doc.Name}
template.Dirty = true
var (
mdoc *machineDoc
ops []txn.Op
err error
)
switch {
case parentId == "" && containerType == "":
mdoc, ops, err = u.st.addMachineOps(template)
case parentId == "":
if containerType == "" {
return fmt.Errorf("assignToNewMachine called without container type (should never happen)")
}
// The new parent machine is clean and only hosts units,
// regardless of its child.
parentParams := template
parentParams.Jobs = []MachineJob{JobHostUnits}
mdoc, ops, err = u.st.addMachineInsideNewMachineOps(template, parentParams, containerType)
default:
// Container type is specified but no parent id.
mdoc, ops, err = u.st.addMachineInsideMachineOps(template, parentId, containerType)
}
if err != nil {
return err
}
// Ensure the host machine is really clean.
if parentId != "" {
ops = append(ops, txn.Op{
C: u.st.machines.Name,
Id: parentId,
Assert: bson.D{{"clean", true}},
}, txn.Op{
C: u.st.containerRefs.Name,
Id: parentId,
Assert: bson.D{hasNoContainersTerm},
})
}
isUnassigned := bson.D{{"machineid", ""}}
asserts := append(isAliveDoc, isUnassigned...)
ops = append(ops, txn.Op{
C: u.st.units.Name,
Id: u.doc.Name,
Assert: asserts,
Update: bson.D{{"$set", bson.D{{"machineid", mdoc.Id}}}},
})
err = u.st.runTransaction(ops)
if err == nil {
u.doc.MachineId = mdoc.Id
return nil
} else if err != txn.ErrAborted {
return err
}
// If we assume that the machine ops will never give us an
// operation that would fail (because the machine id(s) that it
// chooses are unique), then the only reasons that the
// transaction could have been aborted are:
// * the unit is no longer alive