/
state.go
2074 lines (1889 loc) · 62.2 KB
/
state.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-2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// Package state enables reading, observing, and changing
// the state stored in MongoDB of a whole model
// managed by juju.
package state
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/juju/errors"
"github.com/juju/loggo"
jujutxn "github.com/juju/txn"
"github.com/juju/utils"
"github.com/juju/utils/clock"
"github.com/juju/utils/os"
"github.com/juju/utils/series"
"github.com/juju/utils/set"
"github.com/juju/version"
"gopkg.in/juju/charm.v6-unstable"
csparams "gopkg.in/juju/charmrepo.v2-unstable/csclient/params"
"gopkg.in/juju/names.v2"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/audit"
"github.com/juju/juju/constraints"
"github.com/juju/juju/core/lease"
"github.com/juju/juju/instance"
"github.com/juju/juju/mongo"
"github.com/juju/juju/network"
"github.com/juju/juju/permission"
"github.com/juju/juju/state/cloudimagemetadata"
stateaudit "github.com/juju/juju/state/internal/audit"
statelease "github.com/juju/juju/state/lease"
"github.com/juju/juju/state/workers"
"github.com/juju/juju/status"
jujuversion "github.com/juju/juju/version"
)
var logger = loggo.GetLogger("juju.state")
const (
// jujuDB is the name of the main juju database.
jujuDB = "juju"
// presenceDB is the name of the database used to hold presence pinger data.
presenceDB = "presence"
presenceC = "presence"
// blobstoreDB is the name of the blobstore GridFS database.
blobstoreDB = "blobstore"
// applicationLeadershipNamespace is the name of the lease.Client namespace
// used by the leadership manager.
applicationLeadershipNamespace = "application-leadership"
// singularControllerNamespace is the name of the lease.Client namespace
// used by the singular manager
singularControllerNamespace = "singular-controller"
)
type providerIdDoc struct {
ID string `bson:"_id"` // format: "<model-uuid>:<global-key>:<provider-id>"
}
// State represents the state of an model
// managed by juju.
type State struct {
clock clock.Clock
modelTag names.ModelTag
controllerModelTag names.ModelTag
controllerTag names.ControllerTag
mongoInfo *mongo.MongoInfo
session *mgo.Session
database Database
policy Policy
newPolicy NewPolicyFunc
// cloudName is the name of the cloud on which the model
// represented by this state runs.
cloudName string
// leaseClientId is used by the lease infrastructure to
// differentiate between machines whose clocks may be
// relatively-skewed.
leaseClientId string
// workers is responsible for keeping the various sub-workers
// available by starting new ones as they fail. It doesn't do
// that yet, but having a type that collects them together is the
// first step.
//
// note that the allManager stuff below probably ought to be
// folded in as well, but that feels like its own task.
workers workers.Workers
// mu guards allManager, allModelManager & allModelWatcherBacking
mu sync.Mutex
allManager *storeManager
allModelManager *storeManager
allModelWatcherBacking Backing
// TODO(anastasiamac 2015-07-16) As state gets broken up, remove this.
CloudImageMetadataStorage cloudimagemetadata.Storage
}
// StateServingInfo holds information needed by a controller.
// This type is a copy of the type of the same name from the api/params package.
// It is replicated here to avoid the state pacakge depending on api/params.
//
// NOTE(fwereade): the api/params type exists *purely* for representing
// this data over the wire, and has a legitimate reason to exist. This
// type does not: it's non-implementation-specific and shoudl be defined
// under core/ somewhere, so it can be used both here and in the agent
// without dragging unnecessary/irrelevant packages into scope.
type StateServingInfo struct {
APIPort int
StatePort int
Cert string
PrivateKey string
CAPrivateKey string
// this will be passed as the KeyFile argument to MongoDB
SharedSecret string
SystemIdentity string
}
// IsController returns true if this state instance has the bootstrap
// model UUID.
func (st *State) IsController() bool {
return st.modelTag == st.controllerModelTag
}
// ControllerUUID returns the UUID for the controller
// of this state instance.
func (st *State) ControllerUUID() string {
return st.controllerTag.Id()
}
func (st *State) ControllerTag() names.ControllerTag {
return st.controllerTag
}
func ControllerAccess(st *State, tag names.Tag) (permission.UserAccess, error) {
return st.UserAccess(tag.(names.UserTag), st.controllerTag)
}
// RemoveAllModelDocs removes all documents from multi-model
// collections. The model should be put into a dying state before call
// this method. Otherwise, there is a race condition in which collections
// could be added to during or after the running of this method.
func (st *State) RemoveAllModelDocs() error {
err := st.removeAllModelDocs(bson.D{{"life", Dead}})
if errors.Cause(err) == txn.ErrAborted {
return errors.New("can't remove model: model not dead")
}
return errors.Trace(err)
}
// RemoveImportingModelDocs removes all documents from multi-model collections
// for the current model. This method asserts that the model's migration mode
// is "importing".
func (st *State) RemoveImportingModelDocs() error {
err := st.removeAllModelDocs(bson.D{{"migration-mode", MigrationModeImporting}})
if errors.Cause(err) == txn.ErrAborted {
return errors.New("can't remove model: model not being imported for migration")
}
return errors.Trace(err)
}
// RemoveExportingModelDocs removes all documents from multi-model collections
// for the current model. This method asserts that the model's migration mode
// is "exporting".
func (st *State) RemoveExportingModelDocs() error {
err := st.removeAllModelDocs(bson.D{{"migration-mode", MigrationModeExporting}})
if errors.Cause(err) == txn.ErrAborted {
return errors.New("can't remove model: model not being exported for migration")
}
return errors.Trace(err)
}
func (st *State) removeAllModelDocs(modelAssertion bson.D) error {
modelUUID := st.ModelUUID()
// Remove each collection in its own transaction.
for name, info := range st.database.Schema() {
if info.global || info.rawAccess {
continue
}
ops, err := st.removeAllInCollectionOps(name)
if err != nil {
return errors.Trace(err)
}
// Make sure we gate everything on the model assertion.
ops = append([]txn.Op{{
C: modelsC,
Id: modelUUID,
Assert: modelAssertion,
}}, ops...)
err = st.runTransaction(ops)
if err != nil {
return errors.Trace(err)
}
}
// Remove from the raw (non-transactional) collections.
for name, info := range st.database.Schema() {
if !info.global && info.rawAccess {
if err := st.removeAllInCollectionRaw(name); err != nil {
return errors.Trace(err)
}
}
}
// Remove all user permissions for the model.
permPattern := bson.M{
"_id": bson.M{"$regex": "^" + permissionID(modelKey(modelUUID), "")},
}
ops, err := st.removeInCollectionOps(permissionsC, permPattern)
if err != nil {
return errors.Trace(err)
}
err = st.runTransaction(ops)
if err != nil {
return errors.Trace(err)
}
// Now remove remove the model.
env, err := st.Model()
if err != nil {
return errors.Trace(err)
}
id := userModelNameIndex(env.Owner().Canonical(), env.Name())
ops = []txn.Op{{
// Cleanup the owner:envName unique key.
C: usermodelnameC,
Id: id,
Remove: true,
}, {
C: modelEntityRefsC,
Id: modelUUID,
Remove: true,
}, {
C: modelsC,
Id: modelUUID,
Assert: modelAssertion,
Remove: true,
}}
if !st.IsController() {
ops = append(ops, decHostedModelCountOp())
}
return st.runTransaction(ops)
}
// removeAllInCollectionRaw removes all the documents from the given
// named collection.
func (st *State) removeAllInCollectionRaw(name string) error {
coll, closer := st.getCollection(name)
defer closer()
_, err := coll.Writeable().RemoveAll(nil)
return errors.Trace(err)
}
// removeAllInCollectionOps appends to ops operations to
// remove all the documents in the given named collection.
func (st *State) removeAllInCollectionOps(name string) ([]txn.Op, error) {
return st.removeInCollectionOps(name, nil)
}
// removeInCollectionOps generates operations to remove all documents
// from the named collection matching a specific selector.
func (st *State) removeInCollectionOps(name string, sel interface{}) ([]txn.Op, error) {
coll, closer := st.getCollection(name)
defer closer()
var ids []bson.M
err := coll.Find(sel).Select(bson.D{{"_id", 1}}).All(&ids)
if err != nil {
return nil, errors.Trace(err)
}
var ops []txn.Op
for _, id := range ids {
ops = append(ops, txn.Op{
C: name,
Id: id["_id"],
Remove: true,
})
}
return ops, nil
}
// ForModel returns a connection to mongo for the specified model. The
// connection uses the same credentials and policy as the existing connection.
func (st *State) ForModel(modelTag names.ModelTag) (*State, error) {
session := st.session.Copy()
newSt, err := newState(
modelTag, st.controllerModelTag, session, st.mongoInfo, st.newPolicy, st.clock,
)
if err != nil {
return nil, errors.Trace(err)
}
if err := newSt.start(st.controllerTag); err != nil {
return nil, errors.Trace(err)
}
return newSt, nil
}
// start makes a *State functional post-creation, by:
// * setting controllerTag, cloudName and leaseClientId
// * starting lease managers and watcher backends
// * creating cloud metadata storage
//
// start will close the *State if it fails.
func (st *State) start(controllerTag names.ControllerTag) (err error) {
defer func() {
if err == nil {
return
}
if err2 := st.Close(); err2 != nil {
logger.Errorf("closing State for %s: %v", st.modelTag, err2)
}
}()
st.controllerTag = controllerTag
if identity := st.mongoInfo.Tag; identity != nil {
// TODO(fwereade): it feels a bit wrong to take this from MongoInfo -- I
// think it's just coincidental that the mongodb user happens to map to
// the machine that's executing the code -- but there doesn't seem to be
// an accessible alternative.
st.leaseClientId = identity.String()
} else {
// If we're running state anonymously, we can still use the lease
// manager; but we need to make sure we use a unique client ID, and
// will thus not be very performant.
logger.Infof("running state anonymously; using unique client id")
uuid, err := utils.NewUUID()
if err != nil {
return errors.Trace(err)
}
st.leaseClientId = fmt.Sprintf("anon-%s", uuid.String())
}
// now we've set up leaseClientId, we can use workersFactory
logger.Infof("starting standard state workers")
factory := workersFactory{
st: st,
clock: st.clock,
}
workers, err := workers.NewRestartWorkers(workers.RestartConfig{
Factory: factory,
Logger: loggo.GetLogger(logger.Name() + ".workers"),
Clock: st.clock,
Delay: time.Second,
})
if err != nil {
return errors.Annotatef(err, "cannot create standard state workers")
}
st.workers = workers
logger.Infof("creating cloud image metadata storage")
st.CloudImageMetadataStorage = cloudimagemetadata.NewStorage(
cloudimagemetadataC,
&environMongo{st},
)
logger.Infof("started state for %s successfully", st.modelTag)
return nil
}
// ApplicationLeaders returns a map of the application name to the
// unit name that is the current leader.
func (st *State) ApplicationLeaders() (map[string]string, error) {
client, err := st.getLeadershipLeaseClient()
if err != nil {
return nil, errors.Trace(err)
}
leases := client.Leases()
result := make(map[string]string, len(leases))
for key, value := range leases {
result[key] = value.Holder
}
return result, nil
}
func (st *State) getLeadershipLeaseClient() (lease.Client, error) {
client, err := statelease.NewClient(statelease.ClientConfig{
Id: st.leaseClientId,
Namespace: applicationLeadershipNamespace,
Collection: leasesC,
Mongo: &environMongo{st},
Clock: st.clock,
})
if err != nil {
return nil, errors.Annotatef(err, "cannot create leadership lease client")
}
return client, nil
}
func (st *State) getSingularLeaseClient() (lease.Client, error) {
client, err := statelease.NewClient(statelease.ClientConfig{
Id: st.leaseClientId,
Namespace: singularControllerNamespace,
Collection: leasesC,
Mongo: &environMongo{st},
Clock: st.clock,
})
if err != nil {
return nil, errors.Annotatef(err, "cannot create singular lease client")
}
return client, nil
}
// ModelTag() returns the model tag for the model controlled by
// this state instance.
func (st *State) ModelTag() names.ModelTag {
return st.modelTag
}
// ModelUUID returns the model UUID for the model
// controlled by this state instance.
func (st *State) ModelUUID() string {
return st.modelTag.Id()
}
// userModelNameIndex returns a string to be used as a usermodelnameC unique index.
func userModelNameIndex(username, envName string) string {
return strings.ToLower(username) + ":" + envName
}
// EnsureModelRemoved returns an error if any multi-model
// documents for this model are found. It is intended only to be used in
// tests and exported so it can be used in the tests of other packages.
func (st *State) EnsureModelRemoved() error {
found := map[string]int{}
var foundOrdered []string
for name, info := range st.database.Schema() {
if info.global {
continue
}
coll, closer := st.getCollection(name)
defer closer()
n, err := coll.Find(nil).Count()
if err != nil {
return errors.Trace(err)
}
if n != 0 {
found[name] = n
foundOrdered = append(foundOrdered, name)
}
}
if len(found) != 0 {
errMessage := fmt.Sprintf("found documents for model with uuid %s:", st.ModelUUID())
sort.Strings(foundOrdered)
for _, name := range foundOrdered {
number := found[name]
errMessage += fmt.Sprintf(" %d %s doc,", number, name)
}
// Remove trailing comma.
errMessage = errMessage[:len(errMessage)-1]
return errors.New(errMessage)
}
return nil
}
// getPresenceCollection returns the raw mongodb presence collection,
// which is needed to interact with the state/presence package.
func (st *State) getPresenceCollection() *mgo.Collection {
return st.session.DB(presenceDB).C(presenceC)
}
// getTxnLogCollection returns the raw mongodb txns collection, which is
// needed to interact with the state/watcher package.
func (st *State) getTxnLogCollection() *mgo.Collection {
return st.session.DB(jujuDB).C(txnLogC)
}
// newDB returns a database connection using a new session, along with
// a closer function for the session. This is useful where you need to work
// with various collections in a single session, so don't want to call
// getCollection multiple times.
func (st *State) newDB() (Database, func()) {
return st.database.Copy()
}
// Ping probes the state's database connection to ensure
// that it is still alive.
func (st *State) Ping() error {
return st.session.Ping()
}
// MongoVersion return the string repre
func (st *State) MongoVersion() (string, error) {
binfo, err := st.session.BuildInfo()
if err != nil {
return "", errors.Annotate(err, "cannot obtain mongo build info")
}
return binfo.Version, nil
}
// MongoSession returns the underlying mongodb session
// used by the state. It is exposed so that external code
// can maintain the mongo replica set and should not
// otherwise be used.
func (st *State) MongoSession() *mgo.Session {
return st.session
}
func (st *State) Watch() *Multiwatcher {
st.mu.Lock()
if st.allManager == nil {
st.allManager = newStoreManager(newAllWatcherStateBacking(st))
}
st.mu.Unlock()
return NewMultiwatcher(st.allManager)
}
func (st *State) WatchAllModels() *Multiwatcher {
st.mu.Lock()
if st.allModelManager == nil {
st.allModelWatcherBacking = NewAllModelWatcherStateBacking(st)
st.allModelManager = newStoreManager(st.allModelWatcherBacking)
}
st.mu.Unlock()
return NewMultiwatcher(st.allModelManager)
}
// versionInconsistentError indicates one or more agents have a
// different version from the current one (even empty, when not yet
// set).
type versionInconsistentError struct {
currentVersion version.Number
agents []string
}
func (e *versionInconsistentError) Error() string {
sort.Strings(e.agents)
return fmt.Sprintf("some agents have not upgraded to the current model version %s: %s", e.currentVersion, strings.Join(e.agents, ", "))
}
// newVersionInconsistentError returns a new instance of
// versionInconsistentError.
func newVersionInconsistentError(currentVersion version.Number, agents []string) *versionInconsistentError {
return &versionInconsistentError{currentVersion, agents}
}
// IsVersionInconsistentError returns if the given error is
// versionInconsistentError.
func IsVersionInconsistentError(e interface{}) bool {
value := e
// In case of a wrapped error, check the cause first.
cause := errors.Cause(e.(error))
if cause != nil {
value = cause
}
_, ok := value.(*versionInconsistentError)
return ok
}
func (st *State) checkCanUpgrade(currentVersion, newVersion string) error {
matchCurrent := "^" + regexp.QuoteMeta(currentVersion) + "-"
matchNew := "^" + regexp.QuoteMeta(newVersion) + "-"
// Get all machines and units with a different or empty version.
sel := bson.D{{"$or", []bson.D{
{{"tools", bson.D{{"$exists", false}}}},
{{"$and", []bson.D{
{{"tools.version", bson.D{{"$not", bson.RegEx{matchCurrent, ""}}}}},
{{"tools.version", bson.D{{"$not", bson.RegEx{matchNew, ""}}}}},
}}},
}}}
var agentTags []string
for _, name := range []string{machinesC, unitsC} {
collection, closer := st.getCollection(name)
defer closer()
var doc struct {
DocID string `bson:"_id"`
}
iter := collection.Find(sel).Select(bson.D{{"_id", 1}}).Iter()
for iter.Next(&doc) {
localID, err := st.strictLocalID(doc.DocID)
if err != nil {
return errors.Trace(err)
}
switch name {
case machinesC:
agentTags = append(agentTags, names.NewMachineTag(localID).String())
case unitsC:
agentTags = append(agentTags, names.NewUnitTag(localID).String())
}
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
}
if len(agentTags) > 0 {
err := newVersionInconsistentError(version.MustParse(currentVersion), agentTags)
return errors.Trace(err)
}
return nil
}
var errUpgradeInProgress = errors.New(params.CodeUpgradeInProgress)
// IsUpgradeInProgressError returns true if the error is caused by an
// in-progress upgrade.
func IsUpgradeInProgressError(err error) bool {
return errors.Cause(err) == errUpgradeInProgress
}
// SetModelAgentVersion changes the agent version for the model to the
// given version, only if the model is in a stable state (all agents are
// running the current version). If this is a hosted model, newVersion
// cannot be higher than the controller version.
func (st *State) SetModelAgentVersion(newVersion version.Number) (err error) {
if newVersion.Compare(jujuversion.Current) > 0 && !st.IsController() {
return errors.Errorf("a hosted model cannot have a higher version than the server model: %s > %s",
newVersion.String(),
jujuversion.Current,
)
}
buildTxn := func(attempt int) ([]txn.Op, error) {
settings, err := readSettings(st, settingsC, modelGlobalKey)
if err != nil {
return nil, errors.Trace(err)
}
agentVersion, ok := settings.Get("agent-version")
if !ok {
return nil, errors.Errorf("no agent version set in the model")
}
currentVersion, ok := agentVersion.(string)
if !ok {
return nil, errors.Errorf("invalid agent version format: expected string, got %v", agentVersion)
}
if newVersion.String() == currentVersion {
// Nothing to do.
return nil, jujutxn.ErrNoOperations
}
if err := st.checkCanUpgrade(currentVersion, newVersion.String()); err != nil {
return nil, errors.Trace(err)
}
ops := []txn.Op{
// Can't set agent-version if there's an active upgradeInfo doc.
{
C: upgradeInfoC,
Id: currentUpgradeId,
Assert: txn.DocMissing,
}, {
C: settingsC,
Id: st.docID(modelGlobalKey),
Assert: bson.D{{"version", settings.version}},
Update: bson.D{
{"$set", bson.D{{"settings.agent-version", newVersion.String()}}},
},
},
}
return ops, nil
}
if err = st.run(buildTxn); err == jujutxn.ErrExcessiveContention {
// Although there is a small chance of a race here, try to
// return a more helpful error message in the case of an
// active upgradeInfo document being in place.
if upgrading, _ := st.IsUpgrading(); upgrading {
err = errUpgradeInProgress
} else {
err = errors.Annotate(err, "cannot set agent version")
}
}
return errors.Trace(err)
}
// ModelConstraints returns the current model constraints.
func (st *State) ModelConstraints() (constraints.Value, error) {
cons, err := readConstraints(st, modelGlobalKey)
return cons, errors.Trace(err)
}
// SetModelConstraints replaces the current model constraints.
func (st *State) SetModelConstraints(cons constraints.Value) error {
unsupported, err := st.validateConstraints(cons)
if len(unsupported) > 0 {
logger.Warningf(
"setting model constraints: unsupported constraints: %v", strings.Join(unsupported, ","))
} else if err != nil {
return errors.Trace(err)
}
return writeConstraints(st, modelGlobalKey, cons)
}
func (st *State) allMachines(machinesCollection mongo.Collection) ([]*Machine, error) {
mdocs := machineDocSlice{}
err := machinesCollection.Find(nil).All(&mdocs)
if err != nil {
return nil, errors.Annotatef(err, "cannot get all machines")
}
sort.Sort(mdocs)
machines := make([]*Machine, len(mdocs))
for i, doc := range mdocs {
machines[i] = newMachine(st, &doc)
}
return machines, nil
}
// AllMachines returns all machines in the model
// ordered by id.
func (st *State) AllMachines() ([]*Machine, error) {
machinesCollection, closer := st.getCollection(machinesC)
defer closer()
return st.allMachines(machinesCollection)
}
// AllMachinesFor returns all machines for the model represented
// by the given modeluuid
func (st *State) AllMachinesFor(modelUUID string) ([]*Machine, error) {
machinesCollection, closer := st.getCollectionFor(modelUUID, machinesC)
defer closer()
return st.allMachines(machinesCollection)
}
type machineDocSlice []machineDoc
func (ms machineDocSlice) Len() int { return len(ms) }
func (ms machineDocSlice) Swap(i, j int) { ms[i], ms[j] = ms[j], ms[i] }
func (ms machineDocSlice) Less(i, j int) bool {
return machineIdLessThan(ms[i].Id, ms[j].Id)
}
// machineIdLessThan returns true if id1 < id2, false otherwise.
// Machine ids may include "/" separators if they are for a container so
// the comparison is done by comparing the id component values from
// left to right (most significant part to least significant). Ids for
// host machines are always less than ids for their containers.
func machineIdLessThan(id1, id2 string) bool {
// Most times, we are dealing with host machines and not containers, so we will
// try interpreting the ids as ints - this will be faster than dealing with the
// container ids below.
mint1, err1 := strconv.Atoi(id1)
mint2, err2 := strconv.Atoi(id2)
if err1 == nil && err2 == nil {
return mint1 < mint2
}
// We have at least one container id so it gets complicated.
idParts1 := strings.Split(id1, "/")
idParts2 := strings.Split(id2, "/")
nrParts1 := len(idParts1)
nrParts2 := len(idParts2)
minLen := nrParts1
if nrParts2 < minLen {
minLen = nrParts2
}
for x := 0; x < minLen; x++ {
m1 := idParts1[x]
m2 := idParts2[x]
if m1 == m2 {
continue
}
// See if the id part is a container type, and if so compare directly.
if x%2 == 1 {
return m1 < m2
}
// Compare the integer ids.
// There's nothing we can do with errors at this point.
mint1, _ := strconv.Atoi(m1)
mint2, _ := strconv.Atoi(m2)
return mint1 < mint2
}
return nrParts1 < nrParts2
}
// Machine returns the machine with the given id.
func (st *State) Machine(id string) (*Machine, error) {
mdoc, err := st.getMachineDoc(id)
if err != nil {
return nil, err
}
return newMachine(st, mdoc), nil
}
func (st *State) getMachineDoc(id string) (*machineDoc, error) {
machinesCollection, closer := st.getCollection(machinesC)
defer closer()
var err error
mdoc := &machineDoc{}
err = machinesCollection.FindId(id).One(mdoc)
switch err {
case nil:
return mdoc, nil
case mgo.ErrNotFound:
return nil, errors.NotFoundf("machine %s", id)
default:
return nil, errors.Annotatef(err, "cannot get machine %s", id)
}
}
// FindEntity returns the entity with the given tag.
//
// The returned value can be of type *Machine, *Unit,
// *User, *Service, *Model, or *Action, depending
// on the tag.
func (st *State) FindEntity(tag names.Tag) (Entity, error) {
id := tag.Id()
switch tag := tag.(type) {
case names.MachineTag:
return st.Machine(id)
case names.UnitTag:
return st.Unit(id)
case names.UserTag:
return st.User(tag)
case names.ApplicationTag:
return st.Application(id)
case names.ModelTag:
env, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
// Return an invalid entity error if the requested model is not
// the current one.
if id != env.UUID() {
if utils.IsValidUUIDString(id) {
return nil, errors.NotFoundf("model %q", id)
}
// TODO(axw) 2013-12-04 #1257587
// We should not accept model tags that do not match the
// model's UUID. We accept anything for now, to cater
// both for past usage, and for potentially supporting aliases.
logger.Warningf("model-tag does not match current model UUID: %q != %q", id, env.UUID())
conf, err := st.ModelConfig()
if err != nil {
logger.Warningf("ModelConfig failed: %v", err)
} else if id != conf.Name() {
logger.Warningf("model-tag does not match current model name: %q != %q", id, conf.Name())
}
}
return env, nil
case names.RelationTag:
return st.KeyRelation(id)
case names.ActionTag:
return st.ActionByTag(tag)
case names.CharmTag:
if url, err := charm.ParseURL(id); err != nil {
logger.Warningf("Parsing charm URL %q failed: %v", id, err)
return nil, errors.NotFoundf("could not find charm %q in state", id)
} else {
return st.Charm(url)
}
case names.VolumeTag:
return st.Volume(tag)
case names.FilesystemTag:
return st.Filesystem(tag)
default:
return nil, errors.Errorf("unsupported tag %T", tag)
}
}
// tagToCollectionAndId, given an entity tag, returns the collection name and id
// of the entity document.
func (st *State) tagToCollectionAndId(tag names.Tag) (string, interface{}, error) {
if tag == nil {
return "", nil, errors.Errorf("tag is nil")
}
coll := ""
id := tag.Id()
switch tag := tag.(type) {
case names.MachineTag:
coll = machinesC
id = st.docID(id)
case names.ApplicationTag:
coll = applicationsC
id = st.docID(id)
case names.UnitTag:
coll = unitsC
id = st.docID(id)
case names.UserTag:
coll = usersC
if !tag.IsLocal() {
return "", nil, fmt.Errorf("%q is not a local user", tag.Canonical())
}
id = tag.Name()
case names.RelationTag:
coll = relationsC
id = st.docID(id)
case names.ModelTag:
coll = modelsC
case names.ActionTag:
coll = actionsC
id = tag.Id()
case names.CharmTag:
coll = charmsC
id = tag.Id()
default:
return "", nil, errors.Errorf("%q is not a valid collection tag", tag)
}
return coll, id, nil
}
// addPeerRelationsOps returns the operations necessary to add the
// specified service peer relations to the state.
func (st *State) addPeerRelationsOps(applicationname string, peers map[string]charm.Relation) ([]txn.Op, error) {
var ops []txn.Op
for _, rel := range peers {
relId, err := st.sequence("relation")
if err != nil {
return nil, errors.Trace(err)
}
eps := []Endpoint{{
ApplicationName: applicationname,
Relation: rel,
}}
relKey := relationKey(eps)
relDoc := &relationDoc{
DocID: st.docID(relKey),
Key: relKey,
ModelUUID: st.ModelUUID(),
Id: relId,
Endpoints: eps,
Life: Alive,
}
ops = append(ops, txn.Op{
C: relationsC,
Id: relDoc.DocID,
Assert: txn.DocMissing,
Insert: relDoc,
})
}
return ops, nil
}
type AddApplicationArgs struct {
Name string
Series string
Charm *Charm
Channel csparams.Channel
Storage map[string]StorageConstraints
EndpointBindings map[string]string
Settings charm.Settings
NumUnits int
Placement []*instance.Placement
Constraints constraints.Value
Resources map[string]string
}
// AddApplication creates a new application, running the supplied charm, with the
// supplied name (which must be unique). If the charm defines peer relations,
// they will be created automatically.
func (st *State) AddApplication(args AddApplicationArgs) (_ *Application, err error) {
defer errors.DeferredAnnotatef(&err, "cannot add application %q", args.Name)
// Sanity checks.
if !names.IsValidApplication(args.Name) {
return nil, errors.Errorf("invalid name")
}
if args.Charm == nil {
return nil, errors.Errorf("charm is nil")
}
if err := validateCharmVersion(args.Charm); err != nil {
return nil, errors.Trace(err)
}
if exists, err := isNotDead(st, applicationsC, args.Name); err != nil {
return nil, errors.Trace(err)
} else if exists {
return nil, errors.Errorf("application already exists")
}
if err := checkModelActive(st); err != nil {
return nil, errors.Trace(err)
}
if args.Storage == nil {
args.Storage = make(map[string]StorageConstraints)
}
if err := addDefaultStorageConstraints(st, args.Storage, args.Charm.Meta()); err != nil {
return nil, errors.Trace(err)
}
if err := validateStorageConstraints(st, args.Storage, args.Charm.Meta()); err != nil {
return nil, errors.Trace(err)
}
storagePools := make(set.Strings)
for _, storageParams := range args.Storage {
storagePools.Add(storageParams.Pool)
}
if args.Series == "" {
// args.Series is not set, so use the series in the URL.
args.Series = args.Charm.URL().Series
if args.Series == "" {
// Should not happen, but just in case.
return nil, errors.New("series is empty")