forked from juju/juju
/
upgrades.go
1845 lines (1683 loc) · 50.8 KB
/
upgrades.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 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/juju/permission"
"github.com/juju/loggo"
"github.com/juju/replicaset"
"gopkg.in/juju/charm.v6"
"gopkg.in/juju/names.v2"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/cloud"
"github.com/juju/juju/controller"
corelease "github.com/juju/juju/core/lease"
"github.com/juju/juju/core/status"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/mongo/utils"
"github.com/juju/juju/state/globalclock"
"github.com/juju/juju/state/lease"
"github.com/juju/juju/storage/provider"
)
var upgradesLogger = loggo.GetLogger("juju.state.upgrade")
// runForAllModelStates will run runner function for every model passing a state
// for that model.
func runForAllModelStates(pool *StatePool, runner func(st *State) error) error {
st := pool.SystemState()
models, closer := st.db().GetCollection(modelsC)
defer closer()
var modelDocs []bson.M
err := models.Find(nil).Select(bson.M{"_id": 1}).All(&modelDocs)
if err != nil {
return errors.Annotate(err, "failed to read models")
}
for _, modelDoc := range modelDocs {
modelUUID := modelDoc["_id"].(string)
model, err := pool.Get(modelUUID)
if err != nil {
return errors.Annotatef(err, "failed to open model %q", modelUUID)
}
defer func() {
model.Release()
}()
if err := runner(model.State); err != nil {
return errors.Annotatef(err, "model UUID %q", modelUUID)
}
}
return nil
}
// readBsonDField returns the value of a given field in a bson.D.
func readBsonDField(d bson.D, name string) (interface{}, bool) {
for i := range d {
field := &d[i]
if field.Name == name {
return field.Value, true
}
}
return nil, false
}
// replaceBsonDField replaces a field in bson.D.
func replaceBsonDField(d bson.D, name string, value interface{}) error {
for i, field := range d {
if field.Name == name {
newField := field
newField.Value = value
d[i] = newField
return nil
}
}
return errors.NotFoundf("field %q", name)
}
// RenameAddModelPermission renames any permissions called addmodel to add-model.
func RenameAddModelPermission(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(permissionsC)
defer closer()
upgradesLogger.Infof("migrating addmodel permission")
iter := coll.Find(bson.M{"access": "addmodel"}).Iter()
defer iter.Close()
var ops []txn.Op
var doc bson.M
for iter.Next(&doc) {
id, ok := doc["_id"]
if !ok {
return errors.New("no id found in permission doc")
}
ops = append(ops, txn.Op{
C: permissionsC,
Id: id,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"access", "add-model"}}}},
})
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
return st.runRawTransaction(ops)
}
// StripLocalUserDomain removes any @local suffix from any relevant document field values.
func StripLocalUserDomain(pool *StatePool) error {
st := pool.SystemState()
var ops []txn.Op
more, err := stripLocalFromFields(st, cloudCredentialsC, "_id", "owner")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, modelsC, "owner", "cloud-credential")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, usermodelnameC, "_id")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, controllerUsersC, "_id", "user", "createdby")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, modelUsersC, "_id", "user", "createdby")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, permissionsC, "_id", "subject-global-key")
if err != nil {
return err
}
ops = append(ops, more...)
more, err = stripLocalFromFields(st, modelUserLastConnectionC, "_id", "user")
if err != nil {
return err
}
ops = append(ops, more...)
return st.runRawTransaction(ops)
}
func stripLocalFromFields(st *State, collName string, fields ...string) ([]txn.Op, error) {
coll, closer := st.db().GetRawCollection(collName)
defer closer()
upgradesLogger.Infof("migrating document fields of the %s collection", collName)
iter := coll.Find(nil).Iter()
defer iter.Close()
var ops []txn.Op
var doc bson.D
for iter.Next(&doc) {
// Get a copy of the current doc id so we can see if it has changed.
var newId interface{}
id, ok := readBsonDField(doc, "_id")
if ok {
newId = id
}
// Take a copy of the current doc fields.
newDoc := make(bson.D, len(doc))
for i, f := range doc {
newDoc[i] = f
}
// Iterate over the fields that need to be updated and
// record any updates to be made.
var update bson.D
for _, field := range fields {
isId := field == "_id"
fieldVal, ok := readBsonDField(doc, field)
if !ok {
continue
}
updatedVal := strings.Replace(fieldVal.(string), "@local", "", -1)
if err := replaceBsonDField(newDoc, field, updatedVal); err != nil {
return nil, err
}
if isId {
newId = updatedVal
} else {
if fieldVal != updatedVal {
update = append(update, bson.DocElem{
"$set", bson.D{{field, updatedVal}},
})
}
}
}
// For documents where the id has not changed, we can
// use an update operation.
if newId == id {
if len(update) > 0 {
ops = append(ops, txn.Op{
C: collName,
Id: id,
Assert: txn.DocExists,
Update: update,
})
}
} else {
// Where the id has changed, we need to remove the old and
// insert the new document.
ops = append(ops, []txn.Op{{
C: collName,
Id: id,
Assert: txn.DocExists,
Remove: true,
}, {
C: collName,
Id: newId,
Assert: txn.DocMissing,
Insert: newDoc,
}}...)
}
}
if err := iter.Close(); err != nil {
return nil, errors.Trace(err)
}
return ops, nil
}
// AddMigrationAttempt adds an "attempt" field to migration documents
// which are missing one.
func AddMigrationAttempt(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(migrationsC)
defer closer()
query := coll.Find(bson.M{"attempt": bson.M{"$exists": false}})
query = query.Select(bson.M{"_id": 1})
iter := query.Iter()
defer iter.Close()
var ops []txn.Op
var doc bson.M
for iter.Next(&doc) {
id := doc["_id"]
attempt, err := extractMigrationAttempt(id)
if err != nil {
upgradesLogger.Warningf("%s (skipping)", err)
continue
}
ops = append(ops, txn.Op{
C: migrationsC,
Id: id,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{{"attempt", attempt}}}},
})
}
if err := iter.Close(); err != nil {
return errors.Annotate(err, "iterating migrations")
}
return errors.Trace(st.runRawTransaction(ops))
}
func extractMigrationAttempt(id interface{}) (int, error) {
idStr, ok := id.(string)
if !ok {
return 0, errors.Errorf("invalid migration doc id type: %v", id)
}
_, attemptStr, ok := splitDocID(idStr)
if !ok {
return 0, errors.Errorf("invalid migration doc id: %v", id)
}
attempt, err := strconv.Atoi(attemptStr)
if err != nil {
return 0, errors.Errorf("invalid migration attempt number: %v", id)
}
return attempt, nil
}
// AddLocalCharmSequences creates any missing sequences in the
// database for tracking already used local charm revisions.
func AddLocalCharmSequences(pool *StatePool) error {
st := pool.SystemState()
charmsColl, closer := st.db().GetRawCollection(charmsC)
defer closer()
query := bson.M{
"url": bson.M{"$regex": "^local:"},
}
var docs []bson.M
err := charmsColl.Find(query).Select(bson.M{
"_id": 1,
"life": 1,
}).All(&docs)
if err != nil {
return errors.Trace(err)
}
// model UUID -> charm URL base -> max revision
maxRevs := make(map[string]map[string]int)
var deadIds []string
for _, doc := range docs {
id, ok := doc["_id"].(string)
if !ok {
upgradesLogger.Errorf("invalid charm id: %v", doc["_id"])
continue
}
modelUUID, urlStr, ok := splitDocID(id)
if !ok {
upgradesLogger.Errorf("unable to split charm _id: %v", id)
continue
}
url, err := charm.ParseURL(urlStr)
if err != nil {
upgradesLogger.Errorf("unable to parse charm URL: %v", err)
continue
}
if _, exists := maxRevs[modelUUID]; !exists {
maxRevs[modelUUID] = make(map[string]int)
}
baseURL := url.WithRevision(-1).String()
curRev := maxRevs[modelUUID][baseURL]
if url.Revision > curRev {
maxRevs[modelUUID][baseURL] = url.Revision
}
if life, ok := doc["life"].(int); !ok {
upgradesLogger.Errorf("invalid life for charm: %s", id)
continue
} else if life == int(Dead) {
deadIds = append(deadIds, id)
}
}
sequences, closer := st.db().GetRawCollection(sequenceC)
defer closer()
for modelUUID, modelRevs := range maxRevs {
for baseURL, maxRevision := range modelRevs {
name := charmRevSeqName(baseURL)
updater := newDbSeqUpdater(sequences, modelUUID, name)
err := updater.ensure(maxRevision + 1)
if err != nil {
return errors.Annotatef(err, "setting sequence %s", name)
}
}
}
// Remove dead charm documents
var ops []txn.Op
for _, id := range deadIds {
ops = append(ops, txn.Op{
C: charmsC,
Id: id,
Remove: true,
})
}
err = st.runRawTransaction(ops)
return errors.Annotate(err, "removing dead charms")
}
// UpdateLegacyLXDCloudCredentials updates the cloud credentials for the
// LXD-based controller, and updates the cloud endpoint with the given
// value.
func UpdateLegacyLXDCloudCredentials(
st *State,
endpoint string,
credential cloud.Credential,
) error {
cloudOps, err := updateLegacyLXDCloudsOps(st, endpoint)
if err != nil {
return errors.Trace(err)
}
credOps, err := updateLegacyLXDCredentialsOps(st, credential)
if err != nil {
return errors.Trace(err)
}
return st.db().RunTransaction(append(cloudOps, credOps...))
}
func updateLegacyLXDCloudsOps(st *State, endpoint string) ([]txn.Op, error) {
clouds, err := st.Clouds()
if err != nil {
return nil, errors.Trace(err)
}
var ops []txn.Op
for _, c := range clouds {
if c.Type != "lxd" {
continue
}
authTypes := []string{string(cloud.CertificateAuthType)}
set := bson.D{{"auth-types", authTypes}}
if c.Endpoint == "" {
set = append(set, bson.DocElem{"endpoint", endpoint})
}
for _, region := range c.Regions {
if region.Endpoint == "" {
set = append(set, bson.DocElem{
"regions." + utils.EscapeKey(region.Name) + ".endpoint",
endpoint,
})
}
}
upgradesLogger.Infof("updating cloud %q: %v", c.Name, set)
ops = append(ops, txn.Op{
C: cloudsC,
Id: c.Name,
Assert: txn.DocExists,
Update: bson.D{{"$set", set}},
})
}
return ops, nil
}
func updateLegacyLXDCredentialsOps(st *State, cred cloud.Credential) ([]txn.Op, error) {
var ops []txn.Op
coll, closer := st.db().GetRawCollection(cloudCredentialsC)
defer closer()
iter := coll.Find(bson.M{"auth-type": "empty"}).Iter()
defer iter.Close()
var doc cloudCredentialDoc
for iter.Next(&doc) {
cloudCredentialTag, err := doc.cloudCredentialTag()
if err != nil {
upgradesLogger.Debugf("%v", err)
continue
}
c, err := st.Cloud(doc.Cloud)
if err != nil {
return nil, errors.Trace(err)
}
if c.Type != "lxd" {
continue
}
op := updateCloudCredentialOp(cloudCredentialTag, cred)
upgradesLogger.Infof("updating credential %q: %v", cloudCredentialTag, op)
ops = append(ops, op)
}
if err := iter.Close(); err != nil {
return nil, errors.Trace(err)
}
return ops, nil
}
func upgradeNoProxy(np string) string {
if np == "" {
return "127.0.0.1,localhost,::1"
}
nps := set.NewStrings("127.0.0.1", "localhost", "::1")
for _, i := range strings.Split(np, ",") {
nps.Add(i)
}
// sorting is not a big overhead in this case and eases testing.
return strings.Join(nps.SortedValues(), ",")
}
// UpgradeNoProxyDefaults changes the default values of no_proxy
// to hold localhost values as defaults.
func UpgradeNoProxyDefaults(pool *StatePool) error {
st := pool.SystemState()
var ops []txn.Op
coll, closer := st.db().GetRawCollection(settingsC)
defer closer()
iter := coll.Find(bson.D{}).Iter()
defer iter.Close()
var doc settingsDoc
for iter.Next(&doc) {
noProxyVal := doc.Settings[config.NoProxyKey]
noProxy, ok := noProxyVal.(string)
if !ok {
continue
}
noProxy = upgradeNoProxy(noProxy)
doc.Settings[config.NoProxyKey] = noProxy
ops = append(ops, txn.Op{
C: settingsC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
}
// AddNonDetachableStorageMachineId sets the "machineid" field on
// volume and filesystem docs that are inherently bound to that
// machine.
func AddNonDetachableStorageMachineId(pool *StatePool) error {
return runForAllModelStates(pool, addNonDetachableStorageMachineId)
}
func addNonDetachableStorageMachineId(st *State) error {
sb, err := NewStorageBackend(st)
if err != nil {
return errors.Trace(err)
}
getPool := func(d bson.M) string {
var pool string
info, _ := d["info"].(bson.M)
params, _ := d["params"].(bson.M)
if info != nil {
pool = info["pool"].(string)
} else if params != nil {
pool = params["pool"].(string)
}
return pool
}
var needsUpgradeTerm = bson.D{
{"machineid", bson.D{{"$exists", false}}},
{"hostid", bson.D{{"$exists", false}}},
}
var ops []txn.Op
volumeColl, cleanup := st.db().GetCollection(volumesC)
defer cleanup()
var volData []bson.M
err = volumeColl.Find(needsUpgradeTerm).All(&volData)
if err != nil && err != mgo.ErrNotFound {
return errors.Trace(err)
}
volumeAttachColl, cleanup := st.db().GetCollection(volumeAttachmentsC)
defer cleanup()
var volAttachData []bson.M
err = volumeAttachColl.Find(nil).All(&volAttachData)
if err != nil && err != mgo.ErrNotFound {
return errors.Trace(err)
}
attachDataForVolumes := make(map[string][]bson.M)
for _, vad := range volAttachData {
volId := vad["volumeid"].(string)
data := attachDataForVolumes[volId]
data = append(data, vad)
attachDataForVolumes[volId] = data
}
for _, v := range volData {
detachable, err := isDetachableVolumePool(sb, getPool(v))
if err != nil {
return errors.Trace(err)
}
if detachable {
continue
}
attachInfo := attachDataForVolumes[v["name"].(string)]
if len(attachInfo) != 1 {
// There should be exactly one attachment since the
// filesystem is non-detachable, but be defensive
// and leave the document alone if our expectations
// are not met.
continue
}
machineId := attachInfo[0]["machineid"]
if machineId == "" {
machineId = attachInfo[0]["hostid"]
}
ops = append(ops, txn.Op{
C: volumesC,
Id: v["name"],
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{
{"machineid", machineId},
}}},
})
}
filesystemColl, cleanup := st.db().GetCollection(filesystemsC)
defer cleanup()
var fsData []bson.M
err = filesystemColl.Find(needsUpgradeTerm).All(&fsData)
if err != nil && err != mgo.ErrNotFound {
return errors.Trace(err)
}
filesystemAttachColl, cleanup := st.db().GetCollection(filesystemAttachmentsC)
defer cleanup()
var filesystemAttachData []bson.M
err = filesystemAttachColl.Find(nil).All(&filesystemAttachData)
if err != nil && err != mgo.ErrNotFound {
return errors.Trace(err)
}
attachDataForFilesystems := make(map[string][]bson.M)
for _, fad := range filesystemAttachData {
filesystemId := fad["filesystemid"].(string)
data := attachDataForFilesystems[filesystemId]
data = append(data, fad)
attachDataForFilesystems[filesystemId] = data
}
for _, f := range fsData {
if detachable, err := isDetachableFilesystemPool(sb, getPool(f)); err != nil {
return errors.Trace(err)
} else if detachable {
continue
}
attachInfo := attachDataForFilesystems[f["filesystemid"].(string)]
if len(attachInfo) != 1 {
// There should be exactly one attachment since the
// filesystem is non-detachable, but be defensive
// and leave the document alone if our expectations
// are not met.
continue
}
machineId := attachInfo[0]["machineid"]
if machineId == "" {
machineId = attachInfo[0]["hostid"]
}
ops = append(ops, txn.Op{
C: filesystemsC,
Id: f["filesystemid"],
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{
{"machineid", machineId},
}}},
})
}
if len(ops) > 0 {
return errors.Trace(st.db().RunTransaction(ops))
}
return nil
}
// RemoveNilValueApplicationSettings removes any application setting
// key-value pairs from "settings" where value is nil.
func RemoveNilValueApplicationSettings(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(settingsC)
defer closer()
iter := coll.Find(bson.M{"_id": bson.M{"$regex": "^.*:a#.*"}}).Iter()
defer iter.Close()
var ops []txn.Op
var doc settingsDoc
for iter.Next(&doc) {
settingsChanged := false
for key, value := range doc.Settings {
if value != nil {
continue
}
settingsChanged = true
delete(doc.Settings, key)
}
if settingsChanged {
ops = append(ops, txn.Op{
C: settingsC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
}
// AddControllerLogCollectionsSizeSettings adds the controller
// settings to control log pruning and txn log size if they are missing.
func AddControllerLogCollectionsSizeSettings(pool *StatePool) error {
st := pool.SystemState()
coll, closer := st.db().GetRawCollection(controllersC)
defer closer()
var doc settingsDoc
if err := coll.FindId(controllerSettingsGlobalKey).One(&doc); err != nil {
if err == mgo.ErrNotFound {
return nil
}
return errors.Trace(err)
}
var ops []txn.Op
settingsChanged := maybeUpdateSettings(doc.Settings, controller.MaxLogsAge, fmt.Sprintf("%vh", controller.DefaultMaxLogsAgeDays*24))
settingsChanged =
maybeUpdateSettings(doc.Settings, controller.MaxLogsSize, fmt.Sprintf("%vM", controller.DefaultMaxLogCollectionMB)) || settingsChanged
settingsChanged =
maybeUpdateSettings(doc.Settings, controller.MaxTxnLogSize, fmt.Sprintf("%vM", controller.DefaultMaxTxnLogCollectionMB)) || settingsChanged
if settingsChanged {
ops = append(ops, txn.Op{
C: controllersC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
}
func maybeUpdateSettings(settings map[string]interface{}, key string, value interface{}) bool {
if _, ok := settings[key]; !ok {
settings[key] = value
return true
}
return false
}
// applyToAllModelSettings iterates the model settings documents and applys the
// passed in function to them. If the function returns 'true' it indicates the
// settings have been modified, and they should be written back to the
// database.
// Note that if there are any problems with updating settings, then none of the
// changes will be applied, as they are all updated in a single transaction.
func applyToAllModelSettings(st *State, change func(*settingsDoc) (bool, error)) error {
uuids, err := st.AllModelUUIDs()
if err != nil {
return errors.Trace(err)
}
coll, closer := st.db().GetRawCollection(settingsC)
defer closer()
var ids []string
for _, uuid := range uuids {
ids = append(ids, uuid+":e")
}
iter := coll.Find(bson.M{"_id": bson.M{"$in": ids}}).Iter()
defer iter.Close()
var ops []txn.Op
var doc settingsDoc
for iter.Next(&doc) {
settingsChanged, err := change(&doc)
if err != nil {
return errors.Trace(err)
}
if settingsChanged {
ops = append(ops, txn.Op{
C: settingsC,
Id: doc.DocID,
Assert: txn.DocExists,
Update: bson.M{"$set": bson.M{"settings": doc.Settings}},
})
}
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
if len(ops) > 0 {
return errors.Trace(st.runRawTransaction(ops))
}
return nil
}
// AddStatusHistoryPruneSettings adds the model settings
// to control log pruning if they are missing.
func AddStatusHistoryPruneSettings(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
settingsChanged :=
maybeUpdateSettings(doc.Settings, config.MaxStatusHistoryAge, config.DefaultStatusHistoryAge)
settingsChanged =
maybeUpdateSettings(doc.Settings, config.MaxStatusHistorySize, config.DefaultStatusHistorySize) || settingsChanged
return settingsChanged, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
}
// AddActionPruneSettings adds the model settings
// to control log pruning if they are missing.
func AddActionPruneSettings(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
settingsChanged :=
maybeUpdateSettings(doc.Settings, config.MaxActionResultsAge, config.DefaultActionResultsAge)
settingsChanged =
maybeUpdateSettings(doc.Settings, config.MaxActionResultsSize, config.DefaultActionResultsSize) || settingsChanged
return settingsChanged, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
}
// AddUpdateStatusHookSettings adds the model settings
// to control how often to run the update-status hook
// if they are missing.
func AddUpdateStatusHookSettings(pool *StatePool) error {
st := pool.SystemState()
err := applyToAllModelSettings(st, func(doc *settingsDoc) (bool, error) {
settingsChanged :=
maybeUpdateSettings(doc.Settings, config.UpdateStatusHookInterval, config.DefaultUpdateStatusHookInterval)
return settingsChanged, nil
})
if err != nil {
return errors.Trace(err)
}
return nil
}
// AddStorageInstanceConstraints sets the "constraints" field on
// storage instance docs.
func AddStorageInstanceConstraints(pool *StatePool) error {
return runForAllModelStates(pool, addStorageInstanceConstraints)
}
func addStorageInstanceConstraints(st *State) error {
sb, err := NewStorageBackend(st)
if err != nil {
return errors.Trace(err)
}
storageInstances, err := sb.storageInstances(bson.D{
{"constraints", bson.D{{"$exists", false}}},
})
if err != nil {
return errors.Trace(err)
}
var ops []txn.Op
for _, s := range storageInstances {
var siCons storageInstanceConstraints
var defaultPool string
switch s.Kind() {
case StorageKindBlock:
v, err := sb.storageInstanceVolume(s.StorageTag())
if err == nil {
if v.doc.Info != nil {
siCons.Pool = v.doc.Info.Pool
siCons.Size = v.doc.Info.Size
} else if v.doc.Params != nil {
siCons.Pool = v.doc.Params.Pool
siCons.Size = v.doc.Params.Size
}
} else if errors.IsNotFound(err) {
defaultPool = string(provider.LoopProviderType)
} else {
return errors.Trace(err)
}
case StorageKindFilesystem:
f, err := sb.storageInstanceFilesystem(s.StorageTag())
if err == nil {
if f.doc.Info != nil {
siCons.Pool = f.doc.Info.Pool
siCons.Size = f.doc.Info.Size
} else if f.doc.Params != nil {
siCons.Pool = f.doc.Params.Pool
siCons.Size = f.doc.Params.Size
}
} else if errors.IsNotFound(err) {
defaultPool = string(provider.RootfsProviderType)
} else {
return errors.Trace(err)
}
default:
// Unknown storage kind, ignore.
continue
}
if siCons.Pool == "" {
// There's no associated volume or filesystem, so
// take constraints from the application storage
// constraints. This could be wrong, but we've got
// nothing else to go on, and this will match the
// old broken behaviour at least.
//
// If there's no owner, just use the defaults.
siCons.Pool = defaultPool
siCons.Size = 1024
if ownerTag := s.maybeOwner(); ownerTag != nil {
type withStorageConstraints interface {
StorageConstraints() (map[string]StorageConstraints, error)
}
owner, err := st.FindEntity(ownerTag)
if err != nil {
return errors.Trace(err)
}
if owner, ok := owner.(withStorageConstraints); ok {
allCons, err := owner.StorageConstraints()
if err != nil {
return errors.Trace(err)
}
if cons, ok := allCons[s.StorageName()]; ok {
siCons.Pool = cons.Pool
siCons.Size = cons.Size
}
}
}
logger.Warningf(
"no volume or filesystem found, using application storage constraints for %s",
names.ReadableString(s.Tag()),
)
}
ops = append(ops, txn.Op{
C: storageInstancesC,
Id: s.doc.Id,
Assert: txn.DocExists,
Update: bson.D{{"$set", bson.D{
{"constraints", siCons},
}}},
})
}
if len(ops) > 0 {
return errors.Trace(st.db().RunTransaction(ops))
}
return nil
}
// SplitLogCollections moves log entries from the old single log collection
// to the log collection per model.
func SplitLogCollections(pool *StatePool) error {
st := pool.SystemState()
session := st.MongoSession()
db := session.DB(logsDB)
oldLogs := db.C("logs")
// If we haven't seen any particular model, we need to initialise
// the logs collection with the right indices.
seen := set.NewStrings()
iter := oldLogs.Find(nil).Iter()
defer iter.Close()
var doc bson.M
for iter.Next(&doc) {
modelUUID := doc["e"].(string)
newCollName := logCollectionName(modelUUID)
newLogs := db.C(newCollName)
if !seen.Contains(newCollName) {
if err := InitDbLogs(session, modelUUID); err != nil {
return errors.Annotatef(err, "failed to init new logs collection %q", newCollName)
}
seen.Add(newCollName)
}
delete(doc, "e") // old model uuid
if err := newLogs.Insert(doc); err != nil {
// In the case of a restart, we may have already moved
// some of these rows, in which case we'd get a duplicate
// id error (this is OK).
if !mgo.IsDup(err) {
return errors.Annotate(err, "failed to insert log record")
}
}
doc = nil
}
if err := iter.Close(); err != nil {
return errors.Trace(err)
}
// drop the old collection
if err := oldLogs.DropCollection(); err != nil {
// If the namespace is already missing, that's fine.
if isMgoNamespaceNotFound(err) {
return nil
}
return errors.Annotate(err, "failed to drop old logs collection")
}
return nil
}
func isMgoNamespaceNotFound(err error) bool {
// Check for &mgo.QueryError{Code:26, Message:"ns not found"}
if qerr, ok := err.(*mgo.QueryError); ok {
if qerr.Code == 26 {