forked from juju/juju
/
machine.go
2305 lines (2083 loc) · 72.1 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"
"sort"
"strings"
"time"
"github.com/juju/charm/v9"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/mgo/v2"
"github.com/juju/mgo/v2/bson"
"github.com/juju/mgo/v2/txn"
"github.com/juju/names/v4"
jujutxn "github.com/juju/txn/v2"
"github.com/juju/utils/v2"
"github.com/juju/version/v2"
"github.com/kr/pretty"
"github.com/DavinZhang/juju/api"
"github.com/DavinZhang/juju/core/actions"
"github.com/DavinZhang/juju/core/constraints"
corecontainer "github.com/DavinZhang/juju/core/container"
"github.com/DavinZhang/juju/core/instance"
"github.com/DavinZhang/juju/core/model"
"github.com/DavinZhang/juju/core/network"
"github.com/DavinZhang/juju/core/status"
"github.com/DavinZhang/juju/environs/bootstrap"
"github.com/DavinZhang/juju/mongo"
stateerrors "github.com/DavinZhang/juju/state/errors"
"github.com/DavinZhang/juju/tools"
)
// Machine represents the state of a machine.
type Machine struct {
st *State
doc machineDoc
}
// MachineJob values define responsibilities that machines may be
// expected to fulfil.
type MachineJob int
const (
_ MachineJob = iota
JobHostUnits
JobManageModel
)
var (
jobNames = map[MachineJob]model.MachineJob{
JobHostUnits: model.JobHostUnits,
JobManageModel: model.JobManageModel,
}
jobMigrationValue = map[MachineJob]string{
JobHostUnits: "host-units",
JobManageModel: "api-server",
}
)
// ToParams returns the job as model.MachineJob.
func (job MachineJob) ToParams() model.MachineJob {
if jujuJob, ok := jobNames[job]; ok {
return jujuJob
}
return model.MachineJob(fmt.Sprintf("<unknown job %d>", int(job)))
}
// paramsJobsFromJobs converts state jobs to juju jobs.
func paramsJobsFromJobs(jobs []MachineJob) []model.MachineJob {
jujuJobs := make([]model.MachineJob, len(jobs))
for i, machineJob := range jobs {
jujuJobs[i] = machineJob.ToParams()
}
return jujuJobs
}
// MigrationValue converts the state job into a useful human readable
// string for model migration.
func (job MachineJob) MigrationValue() string {
if value, ok := jobMigrationValue[job]; ok {
return value
}
return "unknown"
}
func (job MachineJob) String() string {
return string(job.ToParams())
}
// manualMachinePrefix signals as prefix of Nonce that a machine is
// manually provisioned.
const manualMachinePrefix = "manual:"
// machineDoc represents the internal state of a machine in MongoDB.
// Note the correspondence with MachineInfo in apiserver/juju.
type machineDoc struct {
DocID string `bson:"_id"`
Id string `bson:"machineid"`
ModelUUID string `bson:"model-uuid"`
Nonce string
Series string
ContainerType string
Principals []string
Life Life
Tools *tools.Tools `bson:",omitempty"`
Jobs []MachineJob
PasswordHash string
Clean bool
ForceDestroyed bool `bson:"force-destroyed"`
// Volumes contains the names of volumes attached to the machine.
Volumes []string `bson:"volumes,omitempty"`
// Filesystems contains the names of filesystems attached to the machine.
Filesystems []string `bson:"filesystems,omitempty"`
// 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
// PreferredPublicAddress is the preferred address to be used for
// the machine when a public address is requested.
PreferredPublicAddress address `bson:",omitempty"`
// PreferredPrivateAddress is the preferred address to be used for
// the machine when a private address is requested.
PreferredPrivateAddress address `bson:",omitempty"`
// 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"`
// AgentStartedAt records the time when the machine agent started.
AgentStartedAt time.Time `bson:"agent-started-at,omitempty"`
// Hostname records the machine's hostname as reported by the machine agent.
Hostname string `bson:"hostname,omitempty"`
}
func newMachine(st *State, doc *machineDoc) *Machine {
machine := &Machine{
st: st,
doc: *doc,
}
return machine
}
// Id returns the machine id.
func (m *Machine) Id() string {
return m.doc.Id
}
// Principals returns the principals for the machine.
func (m *Machine) Principals() []string {
return m.doc.Principals
}
// 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)
}
// ModelUUID returns the unique identifier
// for the model that this machine is in.
func (m *Machine) ModelUUID() string {
return m.doc.ModelUUID
}
// ForceDestroyed returns whether the destruction of a dying/dead
// machine was forced. It's always false for a machine that's alive.
func (m *Machine) ForceDestroyed() bool {
return m.doc.ForceDestroyed
}
func (m *Machine) forceDestroyedOps() []txn.Op {
return []txn.Op{{
C: machinesC,
Id: m.doc.DocID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"force-destroyed", true}}}},
}}
}
// machineGlobalKey returns the global database key for the identified machine.
func machineGlobalKey(id string) string {
return "m#" + id
}
// machineGlobalInstanceKey returns the global database key for the identified
// machine's instance.
func machineGlobalInstanceKey(id string) string {
return machineGlobalKey(id) + "#instance"
}
// globalInstanceKey returns the global database key for the machine's instance.
func (m *Machine) globalInstanceKey() string {
return machineGlobalInstanceKey(m.doc.Id)
}
// machineGlobalModificationKey returns the global database key for the
// identified machine's modification changes.
func machineGlobalModificationKey(id string) string {
return machineGlobalKey(id) + "#modification"
}
// globalModificationKey returns the global database key for the machine's
// modification changes.
func (m *Machine) globalModificationKey() string {
return machineGlobalModificationKey(m.doc.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 {
DocID string `bson:"_id"`
MachineId string `bson:"machineid"`
InstanceId instance.Id `bson:"instanceid"`
DisplayName string `bson:"display-name"`
ModelUUID string `bson:"model-uuid"`
Arch *string `bson:"arch,omitempty"`
Mem *uint64 `bson:"mem,omitempty"`
RootDisk *uint64 `bson:"rootdisk,omitempty"`
RootDiskSource *string `bson:"rootdisksource,omitempty"`
CpuCores *uint64 `bson:"cpucores,omitempty"`
CpuPower *uint64 `bson:"cpupower,omitempty"`
Tags *[]string `bson:"tags,omitempty"`
AvailZone *string `bson:"availzone,omitempty"`
// KeepInstance is set to true if, on machine removal from Juju,
// the cloud instance should be retained.
KeepInstance bool `bson:"keep-instance,omitempty"`
// CharmProfiles contains the names of LXD profiles used by this machine.
// Profiles would have been defined in the charm deployed to this machine.
CharmProfiles []string `bson:"charm-profiles,omitempty"`
}
func hardwareCharacteristics(instData instanceData) *instance.HardwareCharacteristics {
return &instance.HardwareCharacteristics{
Arch: instData.Arch,
Mem: instData.Mem,
RootDisk: instData.RootDisk,
RootDiskSource: instData.RootDiskSource,
CpuCores: instData.CpuCores,
CpuPower: instData.CpuPower,
Tags: instData.Tags,
AvailabilityZone: instData.AvailZone,
}
}
// 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) {
instanceDataCollection, closer := st.db().GetCollection(instanceDataC)
defer closer()
var instData instanceData
err := instanceDataCollection.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
}
// removeInstanceDataOp returns the operation needed to remove the
// instance data document associated with the given globalKey.
func removeInstanceDataOp(globalKey string) txn.Op {
return txn.Op{
C: instanceDataC,
Id: globalKey,
Remove: true,
}
}
// AllInstanceData retrieves all instance data in the model
// and provides a way to query hardware characteristics and
// charm profiles by machine.
func (m *Model) AllInstanceData() (*ModelInstanceData, error) {
coll, closer := m.st.db().GetCollection(instanceDataC)
defer closer()
var docs []instanceData
err := coll.Find(nil).All(&docs)
if err != nil {
return nil, errors.Annotate(err, "cannot get all instance data for model")
}
all := &ModelInstanceData{
data: make(map[string]instanceData),
}
for _, doc := range docs {
all.data[doc.MachineId] = doc
}
return all, nil
}
// ModelInstanceData represents all the instance data for a model
// keyed on machine ID.
type ModelInstanceData struct {
data map[string]instanceData
}
// HardwareCharacteristics returns the hardware characteristics of the
// machine. If it isn't found in the map, a nil is returned.
func (d *ModelInstanceData) HardwareCharacteristics(machineID string) *instance.HardwareCharacteristics {
instData, found := d.data[machineID]
if !found {
return nil
}
return hardwareCharacteristics(instData)
}
// CharmProfiles returns the names of the profiles that are defined for
// the machine. If the machine isn't found in the map, a nil is returned.
func (d *ModelInstanceData) CharmProfiles(machineID string) []string {
instData, found := d.data[machineID]
if !found {
return nil
}
return instData.CharmProfiles
}
// InstanceNames returns both the provider instance id and the user
// friendly name. If the machine isn't found, empty strings are returned.
func (d *ModelInstanceData) InstanceNames(machineID string) (instance.Id, string) {
instData, found := d.data[machineID]
if !found {
return "", ""
}
return instData.InstanceId, instData.DisplayName
}
// 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 m.MachineTag()
}
// MachineTag returns the more specific MachineTag type as opposed
// to the more generic Tag type.
func (m *Machine) MachineTag() names.MachineTag {
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
}
// SetKeepInstance sets whether the cloud machine instance
// will be retained when the machine is removed from Juju.
// This is only relevant if an instance exists.
func (m *Machine) SetKeepInstance(keepInstance bool) error {
ops := []txn.Op{{
C: instanceDataC,
Id: m.doc.DocID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"keep-instance", keepInstance}}}},
}}
if err := m.st.db().RunTransaction(ops); err != nil {
// If instance doc doesn't exist, that's ok; there's nothing to keep,
// but that's not an error we care about.
return errors.Annotatef(onAbort(err, nil), "cannot set KeepInstance on machine %v", m)
}
return nil
}
// KeepInstance reports whether a machine, when removed from
// Juju, will cause the corresponding cloud instance to be stopped.
func (m *Machine) KeepInstance() (bool, error) {
instData, err := getInstanceData(m.st, m.Id())
if err != nil {
return false, err
}
return instData.KeepInstance, nil
}
// CharmProfiles returns the names of any LXD profiles used by the machine,
// which were defined in the charm deployed to that machine.
func (m *Machine) CharmProfiles() ([]string, error) {
instData, err := getInstanceData(m.st, m.Id())
if errors.IsNotFound(err) {
err = errors.NotProvisionedf("machine %v", m.Id())
}
if err != nil {
return nil, err
}
return instData.CharmProfiles, nil
}
// SetCharmProfiles sets the names of the charm profiles used on a machine
// in its instanceData.
func (m *Machine) SetCharmProfiles(profiles []string) error {
if len(profiles) == 0 {
return nil
}
buildTxn := func(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err := m.Refresh(); err != nil {
return nil, errors.Trace(err)
}
}
// Exit early if the Machine profiles doesn't need to change.
mProfiles, err := m.CharmProfiles()
if err != nil {
return nil, errors.Trace(err)
}
mProfilesSet := set.NewStrings(mProfiles...)
if mProfilesSet.Union(set.NewStrings(profiles...)).Size() == mProfilesSet.Size() {
return nil, jujutxn.ErrNoOperations
}
ops := []txn.Op{{
C: instanceDataC,
Id: m.doc.DocID,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"charm-profiles", profiles}}}},
}}
return ops, nil
}
err := m.st.db().Run(buildTxn)
return errors.Annotatef(err, "cannot update profiles for %q to %s", m, strings.Join(profiles, ", "))
}
// IsManager returns true if the machine has JobManageModel.
func (m *Machine) IsManager() bool {
return isController(&m.doc)
}
// IsManual returns true if the machine was manually provisioned.
func (m *Machine) IsManual() (bool, error) {
// To avoid unnecessary db lookups, a little of the
// logic from isManualMachine() below is duplicated here
// so we can exit early if possible.
if strings.HasPrefix(m.doc.Nonce, manualMachinePrefix) {
return true, nil
}
if m.doc.Id != "0" {
return false, nil
}
modelSettings, err := readSettings(m.st.db(), settingsC, modelGlobalKey)
if err != nil {
return false, errors.Trace(err)
}
providerRaw, _ := modelSettings.Get("type")
providerType, _ := providerRaw.(string)
return isManualMachine(m.doc.Id, m.doc.Nonce, providerType), nil
}
func isManualMachine(id, nonce, providerType string) bool {
// Apart from the bootstrap machine, manually provisioned
// machines have a nonce prefixed with "manual:". This is
// unique to manual provisioning.
if strings.HasPrefix(nonce, manualMachinePrefix) {
return true
}
// 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.
return id == "0" && (providerType == "null" || providerType == "manual")
}
// 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 binaries 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.Release == "" || 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.DeferredAnnotatef(&err, "cannot set agent version for machine %v", m)
ops, tools, err := m.setAgentVersionOps(v)
if err != nil {
return errors.Trace(err)
}
// A "raw" transaction is needed here because this function gets
// called before database migrations have run so we don't
// necessarily want the model UUID added to the id.
if err := m.st.runRawTransaction(ops); err != nil {
return onAbort(err, stateerrors.ErrDead)
}
m.doc.Tools = tools
return nil
}
func (m *Machine) setAgentVersionOps(v version.Binary) ([]txn.Op, *tools.Tools, error) {
if err := checkVersionValidity(v); err != nil {
return nil, nil, err
}
tools := &tools.Tools{Version: v}
ops := []txn.Op{{
C: machinesC,
Id: m.doc.DocID,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"tools", tools}}}},
}}
return ops, tools, nil
}
// SetMongoPassword sets the password the agent responsible for the machine
// should use to communicate with the controllers. Previous passwords
// are invalidated.
func (m *Machine) SetMongoPassword(password string) error {
if !m.IsManager() {
return errors.NotSupportedf("setting mongo password for non-controller machine %v", m)
}
return mongo.SetAdminMongoPassword(m.st.session, 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 errors.Errorf("password is only %d bytes long, and is not a valid Agent password", len(password))
}
passwordHash := utils.AgentPasswordHash(password)
op := m.UpdateOperation()
op.PasswordHash = &passwordHash
if err := m.st.ApplyOperation(op); err != nil {
return errors.Trace(err)
}
m.doc.PasswordHash = passwordHash
return nil
}
func (m *Machine) setPasswordHashOps(passwordHash string) ([]txn.Op, error) {
if m.doc.Life == Dead {
return nil, stateerrors.ErrDead
}
ops := []txn.Op{{
C: machinesC,
Id: m.doc.DocID,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"passwordhash", passwordHash}}}},
}}
return ops, nil
}
// PasswordValid returns whether the given password is valid
// for the given machine.
func (m *Machine) PasswordValid(password string) bool {
agentHash := utils.AgentPasswordHash(password)
return agentHash == m.doc.PasswordHash
}
// 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 JobManageModel.
// If the machine has assigned units, Destroy will return
// a HasAssignedUnitsError. If the machine has containers, Destroy
// will return HasContainersError.
func (m *Machine) Destroy() error {
return errors.Trace(m.advanceLifecycle(Dying, false, false, 0))
}
// DestroyWithContainers sets the machine lifecycle to Dying if it is Alive.
// It does nothing otherwise. DestroyWithContainers will fail if the machine
// has principal units assigned, or if the machine has JobManageModel. If the
// machine has assigned units, DestroyWithContainers will return a
// HasAssignedUnitsError. The machine is allowed to have containers. Use with
// caution. Intended for model tear down.
func (m *Machine) DestroyWithContainers() error {
return m.advanceLifecycle(Dying, false, true, 0)
}
// ForceDestroy queues the machine for complete removal, including the
// destruction of all units and containers on the machine.
func (m *Machine) ForceDestroy(maxWait time.Duration) error {
ops, err := m.forceDestroyOps(maxWait)
if err != nil {
return errors.Trace(err)
}
if err := m.st.db().RunTransaction(ops); err != txn.ErrAborted {
return errors.Annotatef(err, "failed to run transaction: %s", pretty.Sprint(ops))
}
return nil
}
func (m *Machine) forceDestroyOps(maxWait time.Duration) ([]txn.Op, error) {
if m.IsManager() {
controllerIds, err := m.st.ControllerIds()
if err != nil {
return nil, errors.Annotatef(err, "reading controller info")
}
if len(controllerIds) <= 1 {
return nil, errors.Errorf("controller %s is the only controller", m.Id())
}
// We set the machine to Dying if it isn't already dead.
var machineOp txn.Op
if m.Life() < Dead {
// Make sure we don't want the vote, and we are queued to be Dying.
// Since we are force deleting, life assert should be current machine's life.
machineOp = txn.Op{
C: machinesC,
Id: m.doc.DocID,
Assert: bson.D{{"life", bson.D{{"$in", []Life{Alive, Dying}}}}},
Update: bson.D{{"$set", bson.D{{"life", Dying}}}},
}
}
controllerOp := txn.Op{
C: controllersC,
Id: modelGlobalKey,
Assert: bson.D{{"controller-ids", controllerIds}},
}
// Note that ForceDestroy does *not* cleanup the replicaset, so it might cause problems.
// However, we're letting the user handle times when the machine agent isn't running, etc.
// We may need to update the peergrouper for this.
return []txn.Op{
machineOp,
controllerOp,
setControllerWantsVoteOp(m.st, m.Id(), false),
newCleanupOp(cleanupForceDestroyedMachine, m.doc.Id, maxWait),
}, nil
} else {
// Make sure the machine doesn't become a manager while we're destroying it
return []txn.Op{{
C: machinesC,
Id: m.doc.DocID,
Assert: bson.D{{"jobs", bson.D{{"$nin", []MachineJob{JobManageModel}}}}},
}, newCleanupOp(cleanupForceDestroyedMachine, m.doc.Id, maxWait),
}, nil
}
}
// 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 JobManageModel.
// If the machine has assigned units, EnsureDead will return
// a HasAssignedUnitsError.
func (m *Machine) EnsureDead() error {
return m.advanceLifecycle(Dead, false, false, 0)
}
// Containers returns the container ids belonging to a parent machine.
// TODO(wallyworld): move this method to a service
func (m *Machine) Containers() ([]string, error) {
containerRefs, closer := m.st.db().GetCollection(containerRefsC)
defer closer()
var mc machineContainers
err := containerRefs.FindId(m.doc.DocID).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 := corecontainer.ParentId(m.Id())
return parentId, parentId != ""
}
// IsContainer returns true if the machine is a container.
func (m *Machine) IsContainer() bool {
_, isContainer := m.ParentId()
return isContainer
}
// 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. dyingAllowContainers indicates
// whether the machine can have containers when moving to the dying state.
// Not allowed for moving to dead.
func (original *Machine) advanceLifecycle(life Life, force, dyingAllowContainers bool, maxWait time.Duration) (err error) {
logger.Debugf("%s.advanceLifecycle(%s, %t, %t)", original.Id(), life, force, dyingAllowContainers)
if life == Dead && dyingAllowContainers {
return errors.BadRequestf("life cannot be Dead if dyingAllowContainers true.")
}
// A machine can be set to dying with containers, but cannot have any when
// advanced to dead.
if !dyingAllowContainers && life == Dying {
if err := original.advanceLifecycleIfNoContainers(); err != nil {
return err
}
}
locked, err := original.IsLockedForSeriesUpgrade()
if err != nil {
return errors.Annotatef(err, "reading machine %s upgrade-series lock", original.Id())
}
if locked {
return errors.Errorf("machine %s is locked for series upgrade", original.Id())
}
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
}
}()
ops := m.advanceLifecyleInitialOps(life)
// 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) {
var asserts bson.D
// 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 m, err = m.st.Machine(m.doc.Id); errors.IsNotFound(err) {
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, err
}
node, err := m.st.ControllerNode(m.doc.Id)
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
hasVote := err == nil && node.HasVote()
// 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
}
// Manager nodes are allowed to go to dying even when they have
// the vote, as that is used as the signal that they should lose
// their vote.
asserts = append(asserts, isAliveDoc...)
case Dead:
if m.doc.Life == Dead {
return nil, jujutxn.ErrNoOperations
}
if hasVote {
return nil, fmt.Errorf("machine %s is still a voting controller member", m.doc.Id)
}
if m.IsManager() {
return nil, errors.Errorf("machine %s is still a controller member", m.Id())
}
asserts = append(asserts, bson.DocElem{
Name: "jobs", Value: bson.D{{Name: "$nin", Value: []MachineJob{JobManageModel}}}})
asserts = append(asserts, notDeadDoc...)
ops = append(ops, controllerAdvanceLifecyleVoteOp())
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 there are no alive units left on the machine, or all the applications are dying,
// then the machine may be soon destroyed by a cleanup worker.
// In that case, we don't want to return any error about not being able to
// destroy a machine with units as it will be a lie.
if life == Dying {
canDie := true
if isController(&m.doc) || hasVote {
// If we're responsible for managing the model, make sure we ask to drop our vote
ops[0].Update = bson.D{
{"$set", bson.D{{"life", life}}},
}
controllerOp, err := m.controllerIDsOp()
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops, controllerOp)
ops = append(ops, setControllerWantsVoteOp(m.st, m.doc.Id, false))
}
var principalUnitNames []string
for _, principalUnit := range m.doc.Principals {
principalUnitNames = append(principalUnitNames, principalUnit)
canDie, err = m.assessCanDieUnit(principalUnit)
if err != nil {
return nil, errors.Trace(err)
}
if !canDie {
break
}
}
if canDie && !dyingAllowContainers {
if err := m.advanceLifecycleIfNoContainers(); err != nil && !IsHasContainersError(err) {
return nil, err
} else if IsHasContainersError(err) {
canDie = false
}
ops = append(ops, m.noContainersOp())
}
cleanupOp := newCleanupOp(cleanupDyingMachine, m.doc.Id, force, maxWait)
ops = append(ops, cleanupOp)
if canDie {
ops[0].Assert = append(asserts, advanceLifecycleUnitAsserts(principalUnitNames))
txnLogger.Debugf("txn moving machine %q to %s", m.Id(), life)
return ops, nil
}
}
if len(m.doc.Principals) > 0 {
return nil, newHasAssignedUnitsError(m.doc.Id, m.doc.Principals)
}
asserts = append(asserts, noUnitAsserts())
if life == Dead {
// A machine may not become Dead until it has no
// containers.
if err := m.advanceLifecycleIfNoContainers(); err != nil {
return nil, err
}
ops = append(ops, m.noContainersOp())
if isController(&m.doc) {
return nil, errors.Errorf("machine %s is still responsible for being a controller", m.Id())
}
// A machine may not become Dead until it has no more
// attachments to detachable storage.
storageAsserts, err := m.assertNoPersistentStorage()
if err != nil {
return nil, errors.Trace(err)
}
asserts = append(asserts, storageAsserts...)
}
// Add the additional asserts needed for this transaction.
ops[0].Assert = asserts
return ops, nil
}
if err = m.st.db().Run(buildTxn); err == jujutxn.ErrExcessiveContention {
err = errors.Annotatef(err, "machine %s cannot advance lifecycle", m)
}
return err
}
func (m *Machine) advanceLifecyleInitialOps(life Life) []txn.Op {
return []txn.Op{
{
C: machinesC,
Id: m.doc.DocID,
Update: bson.D{{"$set", bson.D{{"life", life}}}},
},
{
C: machineUpgradeSeriesLocksC,
Id: m.doc.Id,
Assert: txn.DocMissing,
},
}
}
func controllerAdvanceLifecyleVoteOp() txn.Op {
return txn.Op{
C: controllersC,
Id: modelGlobalKey,
Assert: bson.D{
{"has-vote", bson.M{"$ne": true}},
{"wants-vote", bson.M{"$ne": true}},
},
}
}
// controllerIDsOp returns an Op to assert that the machine's
// controllerIDs do not change.
func (m *Machine) controllerIDsOp() (txn.Op, error) {
controllerIds, err := m.st.ControllerIds()
if err != nil {
return txn.Op{}, errors.Annotatef(err, "reading controller info")
}
if len(controllerIds) <= 1 {
return txn.Op{}, errors.Errorf("controller %s is the only controller", m.Id())
}
return txn.Op{
C: controllersC,
Id: modelGlobalKey,
Assert: bson.D{{"controller-ids", controllerIds}},
}, nil
}
// noContainersOp returns an Op to assert that the machine
// has no containers.
func (m *Machine) noContainersOp() txn.Op {
return txn.Op{
C: containerRefsC,
Id: m.doc.DocID,
Assert: bson.D{{"$or", []bson.D{
{{"children", bson.D{{"$size", 0}}}},
{{"children", bson.D{{"$exists", false}}}},
}}},
}
}
// assessCanDieUnit returns true if the machine can die, based on
// evaluating the provided unit.
func (m *Machine) assessCanDieUnit(principalUnit string) (bool, error) {
canDie := true
u, err := m.st.Unit(principalUnit)
if err != nil {
return false, errors.Annotatef(err, "reading machine %s principal unit %v", m, m.doc.Principals[0])
}
app, err := u.Application()
if err != nil {
return false, errors.Annotatef(err, "reading machine %s principal unit application %v", m, u.doc.Application)
}
if u.Life() == Alive && app.Life() == Alive {
canDie = false
}
return canDie, nil
}
// noUnitAsserts returns bson DocElem which assert that there are
// no units for the machine.
func noUnitAsserts() bson.DocElem {
return bson.DocElem{
Name: "$or", Value: []bson.D{
{{"principals", bson.D{{"$size", 0}}}},
{{"principals", bson.D{{"$exists", false}}}},
},
}
}
// advanceLifecycleUnitAsserts returns bson DocElem which assert that there are
// no units for the machine, or that the list of units has not changed.
func advanceLifecycleUnitAsserts(principalUnitNames []string) bson.DocElem {
return bson.DocElem{
Name: "$or", Value: []bson.D{
{{Name: "principals", Value: principalUnitNames}},
{{Name: "principals", Value: bson.D{{"$size", 0}}}},
{{Name: "principals", Value: bson.D{{"$exists", false}}}},
},
}
}
// advanceLifecycleIfNoContainers determines if the machine has
// containers, if so, returns the appropriate error.
func (m *Machine) advanceLifecycleIfNoContainers() error {
containers, err := m.Containers()
if err != nil {