-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmachine.go
1315 lines (1213 loc) · 41.2 KB
/
machine.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 (
"fmt"
"net"
"strings"
"time"
"github.com/juju/errors"
"github.com/juju/names"
jujutxn "github.com/juju/txn"
"github.com/juju/utils"
"github.com/juju/utils/set"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"labix.org/v2/mgo/txn"
"github.com/juju/juju/constraints"
"github.com/juju/juju/instance"
"github.com/juju/juju/network"
"github.com/juju/juju/state/api/params"
"github.com/juju/juju/state/presence"
"github.com/juju/juju/tools"
"github.com/juju/juju/version"
)
// Machine represents the state of a machine.
type Machine struct {
st *State
doc machineDoc
annotator
presence.Presencer
}
// MachineJob values define responsibilities that machines may be
// expected to fulfil.
type MachineJob int
const (
_ MachineJob = iota
JobHostUnits
JobManageEnviron
// Deprecated in 1.18.
JobManageStateDeprecated
)
var jobNames = map[MachineJob]params.MachineJob{
JobHostUnits: params.JobHostUnits,
JobManageEnviron: params.JobManageEnviron,
// Deprecated in 1.18.
JobManageStateDeprecated: params.JobManageStateDeprecated,
}
// AllJobs returns all supported machine jobs.
func AllJobs() []MachineJob {
return []MachineJob{JobHostUnits, JobManageEnviron}
}
// ToParams returns the job as params.MachineJob.
func (job MachineJob) ToParams() params.MachineJob {
if paramsJob, ok := jobNames[job]; ok {
return paramsJob
}
return params.MachineJob(fmt.Sprintf("<unknown job %d>", int(job)))
}
// MachineJobFromParams returns the job corresponding to params.MachineJob.
func MachineJobFromParams(job params.MachineJob) (MachineJob, error) {
for machineJob, paramJob := range jobNames {
if paramJob == job {
return machineJob, nil
}
}
return -1, fmt.Errorf("invalid machine job %q", job)
}
// paramsJobsFromJobs converts state jobs to params jobs.
func paramsJobsFromJobs(jobs []MachineJob) []params.MachineJob {
paramsJobs := make([]params.MachineJob, len(jobs))
for i, machineJob := range jobs {
paramsJobs[i] = machineJob.ToParams()
}
return paramsJobs
}
func (job MachineJob) String() string {
return string(job.ToParams())
}
// machineDoc represents the internal state of a machine in MongoDB.
// Note the correspondence with MachineInfo in state/api/params.
type machineDoc struct {
Id string `bson:"_id"`
Nonce string
Series string
ContainerType string
Principals []string
Life Life
Tools *tools.Tools `bson:",omitempty"`
Jobs []MachineJob
NoVote bool
HasVote bool
PasswordHash string
Clean bool
// We store 2 different sets of addresses for the machine, obtained
// from different sources.
// Addresses is the set of addresses obtained by asking the provider.
Addresses []address
// MachineAddresses is the set of addresses obtained from the machine itself.
MachineAddresses []address
// The SupportedContainers attributes are used to advertise what containers this
// machine is capable of hosting.
SupportedContainersKnown bool
SupportedContainers []instance.ContainerType `bson:",omitempty"`
// Placement is the placement directive that should be used when provisioning
// an instance for the machine.
Placement string `bson:",omitempty"`
// Deprecated. InstanceId, now lives on instanceData.
// This attribute is retained so that data from existing machines can be read.
// SCHEMACHANGE
// TODO(wallyworld): remove this attribute when schema upgrades are possible.
InstanceId instance.Id
}
func newMachine(st *State, doc *machineDoc) *Machine {
machine := &Machine{
st: st,
doc: *doc,
}
machine.annotator = annotator{
globalKey: machine.globalKey(),
tag: machine.Tag().String(),
st: st,
}
return machine
}
// Id returns the machine id.
func (m *Machine) Id() string {
return m.doc.Id
}
// Series returns the operating system series running on the machine.
func (m *Machine) Series() string {
return m.doc.Series
}
// ContainerType returns the type of container hosting this machine.
func (m *Machine) ContainerType() instance.ContainerType {
return instance.ContainerType(m.doc.ContainerType)
}
// machineGlobalKey returns the global database key for the identified machine.
func machineGlobalKey(id string) string {
return "m#" + id
}
// globalKey returns the global database key for the machine.
func (m *Machine) globalKey() string {
return machineGlobalKey(m.doc.Id)
}
// instanceData holds attributes relevant to a provisioned machine.
type instanceData struct {
Id string `bson:"_id"`
InstanceId instance.Id `bson:"instanceid"`
Status string `bson:"status,omitempty"`
Arch *string `bson:"arch,omitempty"`
Mem *uint64 `bson:"mem,omitempty"`
RootDisk *uint64 `bson:"rootdisk,omitempty"`
CpuCores *uint64 `bson:"cpucores,omitempty"`
CpuPower *uint64 `bson:"cpupower,omitempty"`
Tags *[]string `bson:"tags,omitempty"`
}
func hardwareCharacteristics(instData instanceData) *instance.HardwareCharacteristics {
return &instance.HardwareCharacteristics{
Arch: instData.Arch,
Mem: instData.Mem,
RootDisk: instData.RootDisk,
CpuCores: instData.CpuCores,
CpuPower: instData.CpuPower,
Tags: instData.Tags,
}
}
// TODO(wallyworld): move this method to a service.
func (m *Machine) HardwareCharacteristics() (*instance.HardwareCharacteristics, error) {
instData, err := getInstanceData(m.st, m.Id())
if err != nil {
return nil, err
}
return hardwareCharacteristics(instData), nil
}
func getInstanceData(st *State, id string) (instanceData, error) {
var instData instanceData
err := st.instanceData.FindId(id).One(&instData)
if err == mgo.ErrNotFound {
return instanceData{}, errors.NotFoundf("instance data for machine %v", id)
}
if err != nil {
return instanceData{}, fmt.Errorf("cannot get instance data for machine %v: %v", id, err)
}
return instData, nil
}
// Tag returns a tag identifying the machine. The String method provides a
// string representation 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 (m *Machine) Tag() names.Tag {
return names.NewMachineTag(m.Id())
}
// Life returns whether the machine is Alive, Dying or Dead.
func (m *Machine) Life() Life {
return m.doc.Life
}
// Jobs returns the responsibilities that must be fulfilled by m's agent.
func (m *Machine) Jobs() []MachineJob {
return m.doc.Jobs
}
// WantsVote reports whether the machine is a state server
// that wants to take part in peer voting.
func (m *Machine) WantsVote() bool {
return hasJob(m.doc.Jobs, JobManageEnviron) && !m.doc.NoVote
}
// HasVote reports whether that machine is currently a voting
// member of the replica set.
func (m *Machine) HasVote() bool {
return m.doc.HasVote
}
// SetHasVote sets whether the machine is currently a voting
// member of the replica set. It should only be called
// from the worker that maintains the replica set.
func (m *Machine) SetHasVote(hasVote bool) error {
ops := []txn.Op{{
C: m.st.machines.Name,
Id: m.doc.Id,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"hasvote", hasVote}}}},
}}
if err := m.st.runTransaction(ops); err != nil {
return fmt.Errorf("cannot set HasVote of machine %v: %v", m, onAbort(err, errDead))
}
m.doc.HasVote = hasVote
return nil
}
// IsManager returns true if the machine has JobManageEnviron.
func (m *Machine) IsManager() bool {
return hasJob(m.doc.Jobs, JobManageEnviron)
}
// IsManual returns true if the machine was manually provisioned.
func (m *Machine) IsManual() (bool, error) {
// Apart from the bootstrap machine, manually provisioned
// machines have a nonce prefixed with "manual:". This is
// unique to manual provisioning.
if strings.HasPrefix(m.doc.Nonce, "manual:") {
return true, nil
}
// The bootstrap machine uses BootstrapNonce, so in that
// case we need to check if its provider type is "manual".
// We also check for "null", which is an alias for manual.
if m.doc.Id == "0" {
cfg, err := m.st.EnvironConfig()
if err != nil {
return false, err
}
t := cfg.Type()
return t == "null" || t == "manual", nil
}
return false, nil
}
// AgentTools returns the tools that the agent is currently running.
// It returns an error that satisfies errors.IsNotFound if the tools
// have not yet been set.
func (m *Machine) AgentTools() (*tools.Tools, error) {
if m.doc.Tools == nil {
return nil, errors.NotFoundf("agent tools for machine %v", m)
}
tools := *m.doc.Tools
return &tools, nil
}
// checkVersionValidity checks whether the given version is suitable
// for passing to SetAgentVersion.
func checkVersionValidity(v version.Binary) error {
if v.Series == "" || v.Arch == "" {
return fmt.Errorf("empty series or arch")
}
return nil
}
// SetAgentVersion sets the version of juju that the agent is
// currently running.
func (m *Machine) SetAgentVersion(v version.Binary) (err error) {
defer errors.Maskf(&err, "cannot set agent version for machine %v", m)
if err = checkVersionValidity(v); err != nil {
return err
}
tools := &tools.Tools{Version: v}
ops := []txn.Op{{
C: m.st.machines.Name,
Id: m.doc.Id,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"tools", tools}}}},
}}
if err := m.st.runTransaction(ops); err != nil {
return onAbort(err, errDead)
}
m.doc.Tools = tools
return nil
}
// SetMongoPassword sets the password the agent responsible for the machine
// should use to communicate with the state servers. Previous passwords
// are invalidated.
func (m *Machine) SetMongoPassword(password string) error {
return m.st.setMongoPassword(m.Tag().String(), password)
}
// SetPassword sets the password for the machine's agent.
func (m *Machine) 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 m.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 (m *Machine) setPasswordHash(passwordHash string) error {
ops := []txn.Op{{
C: m.st.machines.Name,
Id: m.doc.Id,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"passwordhash", passwordHash}}}},
}}
if err := m.st.runTransaction(ops); err != nil {
return fmt.Errorf("cannot set password of machine %v: %v", m, onAbort(err, errDead))
}
m.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 (m *Machine) getPasswordHash() string {
return m.doc.PasswordHash
}
// PasswordValid returns whether the given password is valid
// for the given machine.
func (m *Machine) PasswordValid(password string) bool {
agentHash := utils.AgentPasswordHash(password)
if agentHash == m.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, as we'll just try again
// next time
if utils.UserPasswordHash(password, utils.CompatSalt) == m.doc.PasswordHash {
logger.Debugf("%s logged in with old password hash, changing to AgentPasswordHash",
m.Tag())
m.setPasswordHash(agentHash)
return true
}
return false
}
// Destroy sets the machine lifecycle to Dying if it is Alive. It does
// nothing otherwise. Destroy will fail if the machine has principal
// units assigned, or if the machine has JobManageEnviron.
// If the machine has assigned units, Destroy will return
// a HasAssignedUnitsError.
func (m *Machine) Destroy() error {
return m.advanceLifecycle(Dying)
}
// ForceDestroy queues the machine for complete removal, including the
// destruction of all units and containers on the machine.
func (m *Machine) ForceDestroy() error {
if !m.IsManager() {
ops := []txn.Op{{
C: m.st.machines.Name,
Id: m.doc.Id,
Assert: bson.D{{"jobs", bson.D{{"$nin", []MachineJob{JobManageEnviron}}}}},
}, m.st.newCleanupOp(cleanupForceDestroyedMachine, m.doc.Id)}
if err := m.st.runTransaction(ops); err != txn.ErrAborted {
return err
}
}
return fmt.Errorf("machine %s is required by the environment", m.doc.Id)
}
// EnsureDead sets the machine lifecycle to Dead if it is Alive or Dying.
// It does nothing otherwise. EnsureDead will fail if the machine has
// principal units assigned, or if the machine has JobManageEnviron.
// If the machine has assigned units, EnsureDead will return
// a HasAssignedUnitsError.
func (m *Machine) EnsureDead() error {
return m.advanceLifecycle(Dead)
}
type HasAssignedUnitsError struct {
MachineId string
UnitNames []string
}
func (e *HasAssignedUnitsError) Error() string {
return fmt.Sprintf("machine %s has unit %q assigned", e.MachineId, e.UnitNames[0])
}
func IsHasAssignedUnitsError(err error) bool {
_, ok := err.(*HasAssignedUnitsError)
return ok
}
// Containers returns the container ids belonging to a parent machine.
// TODO(wallyworld): move this method to a service
func (m *Machine) Containers() ([]string, error) {
var mc machineContainers
err := m.st.containerRefs.FindId(m.Id()).One(&mc)
if err == nil {
return mc.Children, nil
}
if err == mgo.ErrNotFound {
return nil, errors.NotFoundf("container info for machine %v", m.Id())
}
return nil, err
}
// ParentId returns the Id of the host machine if this machine is a container.
func (m *Machine) ParentId() (string, bool) {
parentId := ParentId(m.Id())
return parentId, parentId != ""
}
type HasContainersError struct {
MachineId string
ContainerIds []string
}
func (e *HasContainersError) Error() string {
return fmt.Sprintf("machine %s is hosting containers %q", e.MachineId, strings.Join(e.ContainerIds, ","))
}
func IsHasContainersError(err error) bool {
_, ok := err.(*HasContainersError)
return ok
}
// advanceLifecycle ensures that the machine's lifecycle is no earlier
// than the supplied value. If the machine already has that lifecycle
// value, or a later one, no changes will be made to remote state. If
// the machine has any responsibilities that preclude a valid change in
// lifecycle, it will return an error.
func (original *Machine) advanceLifecycle(life Life) (err error) {
containers, err := original.Containers()
if err != nil {
return err
}
if len(containers) > 0 {
return &HasContainersError{
MachineId: original.doc.Id,
ContainerIds: containers,
}
}
m := original
defer func() {
if err == nil {
// The machine's lifecycle is known to have advanced; it may be
// known to have already advanced further than requested, in
// which case we set the latest known valid value.
if m == nil {
life = Dead
} else if m.doc.Life > life {
life = m.doc.Life
}
original.doc.Life = life
}
}()
// op and
op := txn.Op{
C: m.st.machines.Name,
Id: m.doc.Id,
Update: bson.D{{"$set", bson.D{{"life", life}}}},
}
advanceAsserts := bson.D{
{"jobs", bson.D{{"$nin", []MachineJob{JobManageEnviron}}}},
{"$or", []bson.D{
{{"principals", bson.D{{"$size", 0}}}},
{{"principals", bson.D{{"$exists", false}}}},
}},
{"hasvote", bson.D{{"$ne", true}}},
}
// multiple attempts: one with original data, one with refreshed data, and a final
// one intended to determine the cause of failure of the preceding attempt.
buildTxn := func(attempt int) ([]txn.Op, error) {
// If the transaction was aborted, grab a fresh copy of the machine data.
// We don't write to original, because the expectation is that state-
// changing methods only set the requested change on the receiver; a case
// could perhaps be made that this is not a helpful convention in the
// context of the new state API, but we maintain consistency in the
// face of uncertainty.
if attempt != 0 {
if m, err = m.st.Machine(m.doc.Id); errors.IsNotFound(err) {
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, err
}
}
// Check that the life change is sane, and collect the assertions
// necessary to determine that it remains so.
switch life {
case Dying:
if m.doc.Life != Alive {
return nil, jujutxn.ErrNoOperations
}
op.Assert = append(advanceAsserts, isAliveDoc...)
case Dead:
if m.doc.Life == Dead {
return nil, jujutxn.ErrNoOperations
}
op.Assert = append(advanceAsserts, notDeadDoc...)
default:
panic(fmt.Errorf("cannot advance lifecycle to %v", life))
}
// Check that the machine does not have any responsibilities that
// prevent a lifecycle change.
if hasJob(m.doc.Jobs, JobManageEnviron) {
// (NOTE: When we enable multiple JobManageEnviron machines,
// this restriction will be lifted, but we will assert that the
// machine is not voting)
return nil, fmt.Errorf("machine %s is required by the environment", m.doc.Id)
}
if m.doc.HasVote {
return nil, fmt.Errorf("machine %s is a voting replica set member", m.doc.Id)
}
if len(m.doc.Principals) != 0 {
return nil, &HasAssignedUnitsError{
MachineId: m.doc.Id,
UnitNames: m.doc.Principals,
}
}
return []txn.Op{op}, nil
}
if err = m.st.run(buildTxn); err == jujutxn.ErrExcessiveContention {
err = errors.Annotatef(err, "machine %s cannot advance lifecycle", m)
}
return err
}
func (m *Machine) removeNetworkInterfacesOps() ([]txn.Op, error) {
if m.doc.Life != Dead {
return nil, errors.Errorf("machine is not dead")
}
ops := []txn.Op{{
C: m.st.machines.Name,
Id: m.doc.Id,
Assert: isDeadDoc,
}}
sel := bson.D{{"machineid", m.doc.Id}}
iter := m.st.networkInterfaces.Find(sel).Select(bson.D{{"_id", 1}}).Iter()
var doc networkInterfaceDoc
for iter.Next(&doc) {
ops = append(ops, txn.Op{
C: m.st.networkInterfaces.Name,
Id: doc.Id,
Remove: true,
})
}
return ops, iter.Close()
}
// Remove removes the machine from state. It will fail if the machine
// is not Dead.
func (m *Machine) Remove() (err error) {
defer errors.Maskf(&err, "cannot remove machine %s", m.doc.Id)
if m.doc.Life != Dead {
return fmt.Errorf("machine is not dead")
}
ops := []txn.Op{
{
C: m.st.machines.Name,
Id: m.doc.Id,
Assert: txn.DocExists,
Remove: true,
},
{
C: m.st.machines.Name,
Id: m.doc.Id,
Assert: isDeadDoc,
},
{
C: m.st.instanceData.Name,
Id: m.doc.Id,
Remove: true,
},
removeStatusOp(m.st, m.globalKey()),
removeConstraintsOp(m.st, m.globalKey()),
removeRequestedNetworksOp(m.st, m.globalKey()),
annotationRemoveOp(m.st, m.globalKey()),
}
ifacesOps, err := m.removeNetworkInterfacesOps()
if err != nil {
return err
}
ops = append(ops, ifacesOps...)
ops = append(ops, removeContainerRefOps(m.st, m.Id())...)
// The only abort conditions in play indicate that the machine has already
// been removed.
return onAbort(m.st.runTransaction(ops), nil)
}
// Refresh refreshes the contents of the machine from the underlying
// state. It returns an error that satisfies errors.IsNotFound if the
// machine has been removed.
func (m *Machine) Refresh() error {
doc := machineDoc{}
err := m.st.machines.FindId(m.doc.Id).One(&doc)
if err == mgo.ErrNotFound {
return errors.NotFoundf("machine %v", m)
}
if err != nil {
return fmt.Errorf("cannot refresh machine %v: %v", m, err)
}
m.doc = doc
return nil
}
// AgentPresence returns whether the respective remote agent is alive.
func (m *Machine) AgentPresence() (bool, error) {
b, err := m.st.pwatcher.Alive(m.globalKey())
return b, err
}
// WaitAgentPresence blocks until the respective agent is alive.
func (m *Machine) WaitAgentPresence(timeout time.Duration) (err error) {
defer errors.Maskf(&err, "waiting for agent of machine %v", m)
ch := make(chan presence.Change)
m.st.pwatcher.Watch(m.globalKey(), ch)
defer m.st.pwatcher.Unwatch(m.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 <-m.st.pwatcher.Dead():
return m.st.pwatcher.Err()
}
}
panic(fmt.Sprintf("presence reported dead status twice in a row for machine %v", m))
}
// SetAgentPresence signals that the agent for machine m is alive.
// It returns the started pinger.
func (m *Machine) SetAgentPresence() (*presence.Pinger, error) {
p := presence.NewPinger(m.st.presence, m.globalKey())
err := p.Start()
if err != nil {
return nil, err
}
// We preform a manual sync here so that the
// presence pinger has the most up-to-date information when it
// starts. This ensures that commands run immediately after bootstrap
// like status or ensure-availability will have an accurate values
// for agent-state.
//
// TODO: Does not work for multiple state servers. Trigger a sync across all state servers.
if m.IsManager() {
m.st.pwatcher.Sync()
}
return p, nil
}
// InstanceId returns the provider specific instance id for this
// machine, or a NotProvisionedError, if not set.
func (m *Machine) InstanceId() (instance.Id, error) {
// SCHEMACHANGE
// TODO(wallyworld) - remove this backward compatibility code when schema upgrades are possible
// (we first check for InstanceId stored on the machineDoc)
if m.doc.InstanceId != "" {
return m.doc.InstanceId, nil
}
instData, err := getInstanceData(m.st, m.Id())
if (err == nil && instData.InstanceId == "") || errors.IsNotFound(err) {
err = NotProvisionedError(m.Id())
}
if err != nil {
return "", err
}
return instData.InstanceId, nil
}
// InstanceStatus returns the provider specific instance status for this machine,
// or a NotProvisionedError if instance is not yet provisioned.
func (m *Machine) InstanceStatus() (string, error) {
// SCHEMACHANGE
// InstanceId may not be stored in the instanceData doc, so we
// get it using an API on machine which knows to look in the old
// place if necessary.
instId, err := m.InstanceId()
if err != nil {
return "", err
}
instData, err := getInstanceData(m.st, m.Id())
if (err == nil && instId == "") || errors.IsNotFound(err) {
err = NotProvisionedError(m.Id())
}
if err != nil {
return "", err
}
return instData.Status, nil
}
// SetInstanceStatus sets the provider specific instance status for a machine.
func (m *Machine) SetInstanceStatus(status string) (err error) {
defer errors.Maskf(&err, "cannot set instance status for machine %q", m)
// SCHEMACHANGE - we can't do this yet until the schema is updated
// so just do a txn.DocExists for now.
// provisioned := bson.D{{"instanceid", bson.D{{"$ne", ""}}}}
ops := []txn.Op{
{
C: m.st.instanceData.Name,
Id: m.doc.Id,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"status", status}}}},
},
}
if err = m.st.runTransaction(ops); err == nil {
return nil
} else if err != txn.ErrAborted {
return err
}
return NotProvisionedError(m.Id())
}
// Units returns all the units that have been assigned to the machine.
func (m *Machine) Units() (units []*Unit, err error) {
defer errors.Maskf(&err, "cannot get units assigned to machine %v", m)
pudocs := []unitDoc{}
err = m.st.units.Find(bson.D{{"machineid", m.doc.Id}}).All(&pudocs)
if err != nil {
return nil, err
}
for _, pudoc := range pudocs {
units = append(units, newUnit(m.st, &pudoc))
docs := []unitDoc{}
err = m.st.units.Find(bson.D{{"principal", pudoc.Name}}).All(&docs)
if err != nil {
return nil, err
}
for _, doc := range docs {
units = append(units, newUnit(m.st, &doc))
}
}
return units, nil
}
// SetProvisioned sets the provider specific machine id, nonce and also metadata for
// this machine. Once set, the instance id cannot be changed.
//
// When provisioning an instance, a nonce should be created and passed
// when starting it, before adding the machine to the state. This means
// that if the provisioner crashes (or its connection to the state is
// lost) after starting the instance, we can be sure that only a single
// instance will be able to act for that machine.
func (m *Machine) SetProvisioned(id instance.Id, nonce string, characteristics *instance.HardwareCharacteristics) (err error) {
defer errors.Maskf(&err, "cannot set instance data for machine %q", m)
if id == "" || nonce == "" {
return fmt.Errorf("instance id and nonce cannot be empty")
}
if characteristics == nil {
characteristics = &instance.HardwareCharacteristics{}
}
instData := &instanceData{
Id: m.doc.Id,
InstanceId: id,
Arch: characteristics.Arch,
Mem: characteristics.Mem,
RootDisk: characteristics.RootDisk,
CpuCores: characteristics.CpuCores,
CpuPower: characteristics.CpuPower,
Tags: characteristics.Tags,
}
// SCHEMACHANGE
// TODO(wallyworld) - do not check instanceId on machineDoc after schema is upgraded
notSetYet := bson.D{{"instanceid", ""}, {"nonce", ""}}
ops := []txn.Op{
{
C: m.st.machines.Name,
Id: m.doc.Id,
Assert: append(isAliveDoc, notSetYet...),
Update: bson.D{{"$set", bson.D{{"instanceid", id}, {"nonce", nonce}}}},
}, {
C: m.st.instanceData.Name,
Id: m.doc.Id,
Assert: txn.DocMissing,
Insert: instData,
},
}
if err = m.st.runTransaction(ops); err == nil {
m.doc.Nonce = nonce
// SCHEMACHANGE
// TODO(wallyworld) - remove this backward compatibility code when schema upgrades are possible
// (InstanceId is stored on the instanceData document but we duplicate the value on the machineDoc.
m.doc.InstanceId = id
return nil
} else if err != txn.ErrAborted {
return err
} else if alive, err := isAlive(m.st.machines, m.doc.Id); err != nil {
return err
} else if !alive {
return errNotAlive
}
return fmt.Errorf("already set")
}
// SetInstanceInfo is used to provision a machine and in one steps set
// it's instance id, nonce, hardware characteristics, add networks and
// network interfaces as needed.
//
// TODO(dimitern) Do all the operations described in a single
// transaction, rather than using separate calls. Alternatively,
// we can add all the things to create/set in a document in some
// collection and have a worker that takes care of the actual work.
// Merge SetProvisioned() in here or drop it at that point.
func (m *Machine) SetInstanceInfo(
id instance.Id, nonce string, characteristics *instance.HardwareCharacteristics,
networks []NetworkInfo, interfaces []NetworkInterfaceInfo) error {
// Add the networks and interfaces first.
for _, network := range networks {
_, err := m.st.AddNetwork(network)
if err != nil && errors.IsAlreadyExists(err) {
// Ignore already existing networks.
continue
} else if err != nil {
return err
}
}
for _, iface := range interfaces {
_, err := m.AddNetworkInterface(iface)
if err != nil && errors.IsAlreadyExists(err) {
// Ignore already existing network interfaces.
continue
} else if err != nil {
return err
}
}
return m.SetProvisioned(id, nonce, characteristics)
}
// notProvisionedError records an error when a machine is not provisioned.
type notProvisionedError struct {
machineId string
}
func NotProvisionedError(machineId string) error {
return ¬ProvisionedError{machineId}
}
func (e *notProvisionedError) Error() string {
return fmt.Sprintf("machine %v is not provisioned", e.machineId)
}
// IsNotProvisionedError returns true if err is a notProvisionedError.
func IsNotProvisionedError(err error) bool {
_, ok := err.(*notProvisionedError)
return ok
}
func mergedAddresses(machineAddresses, providerAddresses []address) []network.Address {
merged := make([]network.Address, 0, len(providerAddresses)+len(machineAddresses))
var providerValues set.Strings
for _, address := range providerAddresses {
// Older versions of Juju may have stored an empty address so ignore it here.
if address.Value == "" {
continue
}
providerValues.Add(address.Value)
merged = append(merged, address.InstanceAddress())
}
for _, address := range machineAddresses {
if !providerValues.Contains(address.Value) {
merged = append(merged, address.InstanceAddress())
}
}
return merged
}
// Addresses returns any hostnames and ips associated with a machine,
// determined both by the machine itself, and by asking the provider.
//
// The addresses returned by the provider shadow any of the addresses
// that the machine reported with the same address value. Provider-reported
// addresses always come before machine-reported addresses.
func (m *Machine) Addresses() (addresses []network.Address) {
return mergedAddresses(m.doc.MachineAddresses, m.doc.Addresses)
}
// SetAddresses records any addresses related to the machine, sourced
// by asking the provider.
func (m *Machine) SetAddresses(addresses ...network.Address) (err error) {
if err = m.setAddresses(addresses, &m.doc.Addresses, "addresses"); err != nil {
return fmt.Errorf("cannot set addresses of machine %v: %v", m, err)
}
return nil
}
// MachineAddresses returns any hostnames and ips associated with a machine,
// determined by asking the machine itself.
func (m *Machine) MachineAddresses() (addresses []network.Address) {
for _, address := range m.doc.MachineAddresses {
addresses = append(addresses, address.InstanceAddress())
}
return
}
// SetMachineAddresses records any addresses related to the machine, sourced
// by asking the machine.
func (m *Machine) SetMachineAddresses(addresses ...network.Address) (err error) {
if err = m.setAddresses(addresses, &m.doc.MachineAddresses, "machineaddresses"); err != nil {
return fmt.Errorf("cannot set machine addresses of machine %v: %v", m, err)
}
return nil
}
// setAddresses updates the machine's addresses (either Addresses or
// MachineAddresses, depending on the field argument).
func (m *Machine) setAddresses(addresses []network.Address, field *[]address, fieldName string) error {
var changed bool
stateAddresses := instanceAddressesToAddresses(addresses)
buildTxn := func(attempt int) ([]txn.Op, error) {
changed = false
if attempt > 0 {
if err := m.Refresh(); err != nil {
return nil, err
}
}
if m.doc.Life == Dead {
return nil, errDead
}
op := txn.Op{
C: m.st.machines.Name,
Id: m.doc.Id,
Assert: append(bson.D{{fieldName, *field}}, notDeadDoc...),
}
if !addressesEqual(addresses, addressesToInstanceAddresses(*field)) {
op.Update = bson.D{{"$set", bson.D{{fieldName, stateAddresses}}}}
changed = true
}
return []txn.Op{op}, nil
}
switch err := m.st.run(buildTxn); err {
case nil:
case jujutxn.ErrExcessiveContention:
return errors.Annotatef(err, "cannot set %s for machine %s", fieldName, m)
default:
return err
}
if !changed {
return nil
}
*field = stateAddresses
return nil
}
// RequestedNetworks returns the list of network names the machine
// should be on. Unlike networks specified with constraints, these
// networks are required to be present on the machine.
func (m *Machine) RequestedNetworks() ([]string, error) {
return readRequestedNetworks(m.st, m.globalKey())
}