/
migration_import.go
1840 lines (1674 loc) · 51.6 KB
/
migration_import.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 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"encoding/hex"
"fmt"
"reflect"
"time"
"github.com/juju/description"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/version"
"gopkg.in/juju/charm.v6-unstable"
"gopkg.in/juju/names.v2"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/cloud"
"github.com/juju/juju/constraints"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/instance"
"github.com/juju/juju/network"
"github.com/juju/juju/payload"
"github.com/juju/juju/permission"
"github.com/juju/juju/state/cloudimagemetadata"
"github.com/juju/juju/status"
"github.com/juju/juju/storage"
"github.com/juju/juju/storage/poolmanager"
"github.com/juju/juju/storage/provider"
"github.com/juju/juju/tools"
)
// When we import a new model, we need to give the leaders some time to
// settle. We don't want to have leader switches just because we migrated an
// environment, so this time needs to be long enough to make sure we cover
// the time taken to migration a reasonable sized environment. We don't yet
// know how long this is going to be, but we need something.
var initialLeaderClaimTime = time.Minute
// Import the database agnostic model representation into the database.
func (st *State) Import(model description.Model) (_ *Model, _ *State, err error) {
logger := loggo.GetLogger("juju.state.import-model")
logger.Debugf("import starting for model %s", model.Tag().Id())
// At this stage, attempting to import a model with the same
// UUID as an existing model will error.
tag := model.Tag()
_, err = st.GetModel(tag)
if err == nil {
// We have an existing matching model.
return nil, nil, errors.AlreadyExistsf("model with UUID %s", tag.Id())
} else if !errors.IsNotFound(err) {
return nil, nil, errors.Trace(err)
}
if len(model.RemoteApplications()) != 0 {
// Cross-model relations are currently limited to models on
// the same controller, while migration is for getting the
// model to a new controller.
return nil, nil, errors.New("can't import models with remote applications")
}
// Create the model.
cfg, err := config.New(config.NoDefaults, model.Config())
if err != nil {
return nil, nil, errors.Trace(err)
}
args := ModelArgs{
CloudName: model.Cloud(),
CloudRegion: model.CloudRegion(),
Config: cfg,
Owner: model.Owner(),
MigrationMode: MigrationModeImporting,
// NOTE(axw) we create the model without any storage
// pools. We'll need to import the storage pools from
// the model description before adding any volumes,
// filesystems or storage instances.
StorageProviderRegistry: storage.StaticProviderRegistry{},
}
if creds := model.CloudCredential(); creds != nil {
// Need to add credential or make sure an existing credential
// matches.
// TODO: there really should be a way to create a cloud credential
// tag in the names package from the cloud, owner and name.
credID := fmt.Sprintf("%s/%s/%s", creds.Cloud(), creds.Owner(), creds.Name())
if !names.IsValidCloudCredential(credID) {
return nil, nil, errors.Errorf("model credentails id not valid: %q", credID)
}
credTag := names.NewCloudCredentialTag(credID)
existingCreds, err := st.CloudCredential(credTag)
if errors.IsNotFound(err) {
credential := cloud.NewCredential(
cloud.AuthType(creds.AuthType()),
creds.Attributes())
if err := st.UpdateCloudCredential(credTag, credential); err != nil {
return nil, nil, errors.Trace(err)
}
} else if err != nil {
return nil, nil, errors.Trace(err)
} else {
// ensure existing creds match
if string(existingCreds.AuthType()) != creds.AuthType() {
return nil, nil, errors.Errorf("credential auth type mismatch: %q != %q", existingCreds.AuthType(), creds.AuthType())
}
if !reflect.DeepEqual(existingCreds.Attributes(), creds.Attributes()) {
return nil, nil, errors.Errorf("credential attribute mismatch: %v != %v", existingCreds.Attributes(), creds.Attributes())
}
if existingCreds.Revoked {
return nil, nil, errors.Errorf("credential %q is revoked", credID)
}
}
args.CloudCredential = credTag
}
dbModel, newSt, err := st.NewModel(args)
if err != nil {
return nil, nil, errors.Trace(err)
}
logger.Debugf("model created %s/%s", dbModel.Owner().Id(), dbModel.Name())
defer func() {
if err != nil {
newSt.Close()
}
}()
// We don't actually care what the old model status was, because we are
// going to set it to busy, with a message of migrating.
if err := dbModel.SetStatus(status.StatusInfo{
Status: status.Busy,
Message: "importing",
}); err != nil {
return nil, nil, errors.Trace(err)
}
// I would have loved to use import, but that is a reserved word.
restore := importer{
st: newSt,
dbModel: dbModel,
model: model,
logger: logger,
}
if err := restore.sequences(); err != nil {
return nil, nil, errors.Annotate(err, "sequences")
}
// We need to import the sequences first as we may add blocks
// in the modelExtras which will touch the block sequence.
if err := restore.modelExtras(); err != nil {
return nil, nil, errors.Annotate(err, "base model aspects")
}
if err := newSt.SetModelConstraints(restore.constraints(model.Constraints())); err != nil {
return nil, nil, errors.Annotate(err, "model constraints")
}
if err := restore.sshHostKeys(); err != nil {
return nil, nil, errors.Annotate(err, "sshHostKeys")
}
if err := restore.cloudimagemetadata(); err != nil {
return nil, nil, errors.Annotate(err, "cloudimagemetadata")
}
if err := restore.actions(); err != nil {
return nil, nil, errors.Annotate(err, "actions")
}
if err := restore.modelUsers(); err != nil {
return nil, nil, errors.Annotate(err, "modelUsers")
}
if err := restore.machines(); err != nil {
return nil, nil, errors.Annotate(err, "machines")
}
if err := restore.applications(); err != nil {
return nil, nil, errors.Annotate(err, "applications")
}
if err := restore.relations(); err != nil {
return nil, nil, errors.Annotate(err, "relations")
}
if err := restore.spaces(); err != nil {
return nil, nil, errors.Annotate(err, "spaces")
}
if err := restore.linklayerdevices(); err != nil {
return nil, nil, errors.Annotate(err, "linklayerdevices")
}
if err := restore.subnets(); err != nil {
return nil, nil, errors.Annotate(err, "subnets")
}
if err := restore.ipaddresses(); err != nil {
return nil, nil, errors.Annotate(err, "ipaddresses")
}
if err := restore.storage(); err != nil {
return nil, nil, errors.Annotate(err, "storage")
}
// NOTE: at the end of the import make sure that the mode of the model
// is set to "imported" not "active" (or whatever we call it). This way
// we don't start model workers for it before the migration process
// is complete.
// Update the sequences to match that the source.
if err := dbModel.SetSLA(
model.SLA().Level(),
model.SLA().Owner(),
[]byte(model.SLA().Credentials()),
); err != nil {
return nil, nil, errors.Trace(err)
}
if MeterStatusFromString(model.MeterStatus().Code()).String() != MeterNotAvailable.String() {
if err := dbModel.SetMeterStatus(model.MeterStatus().Code(), model.MeterStatus().Info()); err != nil {
return nil, nil, errors.Trace(err)
}
}
logger.Debugf("import success")
return dbModel, newSt, nil
}
type importer struct {
st *State
dbModel *Model
model description.Model
logger loggo.Logger
// applicationUnits is populated at the end of loading the applications, and is a
// map of application name to units of that application.
applicationUnits map[string][]*Unit
}
func (i *importer) modelExtras() error {
if latest := i.model.LatestToolsVersion(); latest != version.Zero {
if err := i.dbModel.UpdateLatestToolsVersion(latest); err != nil {
return errors.Trace(err)
}
}
if annotations := i.model.Annotations(); len(annotations) > 0 {
if err := i.st.SetAnnotations(i.dbModel, annotations); err != nil {
return errors.Trace(err)
}
}
blockType := map[string]BlockType{
"destroy-model": DestroyBlock,
"remove-object": RemoveBlock,
"all-changes": ChangeBlock,
}
for blockName, message := range i.model.Blocks() {
block, ok := blockType[blockName]
if !ok {
return errors.Errorf("unknown block type: %q", blockName)
}
i.st.SwitchBlockOn(block, message)
}
if err := i.importStatusHistory(modelGlobalKey, i.model.StatusHistory()); err != nil {
return errors.Trace(err)
}
return nil
}
func (i *importer) sequences() error {
sequenceValues := i.model.Sequences()
docs := make([]interface{}, 0, len(sequenceValues))
for key, value := range sequenceValues {
// The sequences which track charm revisions aren't imported
// here because they get set when charm binaries are imported
// later. Importing them here means the wrong values get used.
if !isCharmRevSeqName(key) {
docs = append(docs, sequenceDoc{
DocID: key,
Name: key,
Counter: value,
})
}
}
// In reality, we will almost always have sequences to migrate.
// However, in tests, sometimes we don't.
if len(docs) == 0 {
return nil
}
sequences, closer := i.st.db().GetCollection(sequenceC)
defer closer()
if err := sequences.Writeable().Insert(docs...); err != nil {
return errors.Trace(err)
}
return nil
}
func (i *importer) modelUsers() error {
i.logger.Debugf("importing users")
// The user that was auto-added when we created the model will have
// the wrong DateCreated, so we remove it, and add in all the users we
// know about. It is also possible that the owner of the model no
// longer has access to the model due to changes over time.
if err := i.st.RemoveUserAccess(i.dbModel.Owner(), i.dbModel.ModelTag()); err != nil {
return errors.Trace(err)
}
users := i.model.Users()
modelUUID := i.dbModel.UUID()
var ops []txn.Op
for _, user := range users {
ops = append(ops, createModelUserOps(
modelUUID,
user.Name(),
user.CreatedBy(),
user.DisplayName(),
user.DateCreated(),
permission.Access(user.Access()))...,
)
}
if err := i.st.runTransaction(ops); err != nil {
return errors.Trace(err)
}
// Now set their last connection times.
for _, user := range users {
i.logger.Debugf("user %s", user.Name())
lastConnection := user.LastConnection()
if lastConnection.IsZero() {
continue
}
err := i.st.updateLastModelConnection(user.Name(), lastConnection)
if err != nil {
return errors.Trace(err)
}
}
return nil
}
func (i *importer) machines() error {
i.logger.Debugf("importing machines")
for _, m := range i.model.Machines() {
if err := i.machine(m); err != nil {
i.logger.Errorf("error importing machine: %s", err)
return errors.Annotate(err, m.Id())
}
}
i.logger.Debugf("importing machines succeeded")
return nil
}
func (i *importer) machine(m description.Machine) error {
// Import this machine, then import its containers.
i.logger.Debugf("importing machine %s", m.Id())
// 1. construct a machineDoc
mdoc, err := i.makeMachineDoc(m)
if err != nil {
return errors.Annotatef(err, "machine %s", m.Id())
}
// 2. construct enough MachineTemplate to pass into 'insertNewMachineOps'
// - adds constraints doc
// - adds status doc
// - adds machine block devices doc
mStatus := m.Status()
if mStatus == nil {
return errors.NotValidf("missing status")
}
machineStatusDoc := statusDoc{
ModelUUID: i.st.ModelUUID(),
Status: status.Status(mStatus.Value()),
StatusInfo: mStatus.Message(),
StatusData: mStatus.Data(),
Updated: mStatus.Updated().UnixNano(),
}
// A machine isn't valid if it doesn't have an instance.
instance := m.Instance()
instStatus := instance.Status()
instanceStatusDoc := statusDoc{
ModelUUID: i.st.ModelUUID(),
Status: status.Status(instStatus.Value()),
StatusInfo: instStatus.Message(),
StatusData: instStatus.Data(),
Updated: instStatus.Updated().UnixNano(),
}
cons := i.constraints(m.Constraints())
prereqOps, machineOp := i.st.baseNewMachineOps(
mdoc,
machineStatusDoc,
instanceStatusDoc,
cons,
)
// 3. create op for adding in instance data
prereqOps = append(prereqOps, i.machineInstanceOp(mdoc, instance))
if parentId := ParentId(mdoc.Id); parentId != "" {
prereqOps = append(prereqOps,
// Update containers record for host machine.
i.st.addChildToContainerRefOp(parentId, mdoc.Id),
)
}
// insertNewContainerRefOp adds an empty doc into the containerRefsC
// collection for the machine being added.
prereqOps = append(prereqOps, i.st.insertNewContainerRefOp(mdoc.Id))
// 4. gather prereqs and machine op, run ops.
ops := append(prereqOps, machineOp)
// 5. add any ops that we may need to add the opened ports information.
ops = append(ops, i.machinePortsOps(m)...)
if err := i.st.runTransaction(ops); err != nil {
return errors.Trace(err)
}
machine := newMachine(i.st, mdoc)
if annotations := m.Annotations(); len(annotations) > 0 {
if err := i.st.SetAnnotations(machine, annotations); err != nil {
return errors.Trace(err)
}
}
if err := i.importStatusHistory(machine.globalKey(), m.StatusHistory()); err != nil {
return errors.Trace(err)
}
if err := i.importStatusHistory(machine.globalInstanceKey(), instance.StatusHistory()); err != nil {
return errors.Trace(err)
}
if err := i.importMachineBlockDevices(machine, m); err != nil {
return errors.Trace(err)
}
// Now that this machine exists in the database, process each of the
// containers in this machine.
for _, container := range m.Containers() {
if err := i.machine(container); err != nil {
return errors.Annotate(err, container.Id())
}
}
return nil
}
func (i *importer) importMachineBlockDevices(machine *Machine, m description.Machine) error {
var devices []BlockDeviceInfo
for _, device := range m.BlockDevices() {
devices = append(devices, BlockDeviceInfo{
DeviceName: device.Name(),
DeviceLinks: device.Links(),
Label: device.Label(),
UUID: device.UUID(),
HardwareId: device.HardwareID(),
WWN: device.WWN(),
BusAddress: device.BusAddress(),
Size: device.Size(),
FilesystemType: device.FilesystemType(),
InUse: device.InUse(),
MountPoint: device.MountPoint(),
})
}
if err := machine.SetMachineBlockDevices(devices...); err != nil {
return errors.Trace(err)
}
return nil
}
func (i *importer) machinePortsOps(m description.Machine) []txn.Op {
var result []txn.Op
machineID := m.Id()
for _, ports := range m.OpenedPorts() {
subnetID := ports.SubnetID()
doc := &portsDoc{
MachineID: machineID,
SubnetID: subnetID,
}
for _, opened := range ports.OpenPorts() {
doc.Ports = append(doc.Ports, PortRange{
UnitName: opened.UnitName(),
FromPort: opened.FromPort(),
ToPort: opened.ToPort(),
Protocol: opened.Protocol(),
})
}
result = append(result, txn.Op{
C: openedPortsC,
Id: portsGlobalKey(machineID, subnetID),
Assert: txn.DocMissing,
Insert: doc,
})
}
return result
}
func (i *importer) machineInstanceOp(mdoc *machineDoc, inst description.CloudInstance) txn.Op {
doc := &instanceData{
DocID: mdoc.DocID,
MachineId: mdoc.Id,
InstanceId: instance.Id(inst.InstanceId()),
ModelUUID: mdoc.ModelUUID,
}
if arch := inst.Architecture(); arch != "" {
doc.Arch = &arch
}
if mem := inst.Memory(); mem != 0 {
doc.Mem = &mem
}
if rootDisk := inst.RootDisk(); rootDisk != 0 {
doc.RootDisk = &rootDisk
}
if cores := inst.CpuCores(); cores != 0 {
doc.CpuCores = &cores
}
if power := inst.CpuPower(); power != 0 {
doc.CpuPower = &power
}
if tags := inst.Tags(); len(tags) > 0 {
doc.Tags = &tags
}
if az := inst.AvailabilityZone(); az != "" {
doc.AvailZone = &az
}
return txn.Op{
C: instanceDataC,
Id: mdoc.DocID,
Assert: txn.DocMissing,
Insert: doc,
}
}
func (i *importer) makeMachineDoc(m description.Machine) (*machineDoc, error) {
id := m.Id()
supported, supportedSet := m.SupportedContainers()
supportedContainers := make([]instance.ContainerType, len(supported))
for j, c := range supported {
supportedContainers[j] = instance.ContainerType(c)
}
jobs, err := i.makeMachineJobs(m.Jobs())
if err != nil {
return nil, errors.Trace(err)
}
machineTag := m.Tag()
return &machineDoc{
DocID: i.st.docID(id),
Id: id,
ModelUUID: i.st.ModelUUID(),
Nonce: m.Nonce(),
Series: m.Series(),
ContainerType: m.ContainerType(),
Principals: nil, // Set during unit import.
Life: Alive,
Tools: i.makeTools(m.Tools()),
Jobs: jobs,
NoVote: true, // State servers can't be migrated yet.
HasVote: false, // State servers can't be migrated yet.
PasswordHash: m.PasswordHash(),
Clean: !i.machineHasUnits(machineTag),
Volumes: i.machineVolumes(machineTag),
Filesystems: i.machineFilesystems(machineTag),
Addresses: i.makeAddresses(m.ProviderAddresses()),
MachineAddresses: i.makeAddresses(m.MachineAddresses()),
PreferredPrivateAddress: i.makeAddress(m.PreferredPrivateAddress()),
PreferredPublicAddress: i.makeAddress(m.PreferredPublicAddress()),
SupportedContainersKnown: supportedSet,
SupportedContainers: supportedContainers,
Placement: m.Placement(),
}, nil
}
func (i *importer) machineHasUnits(tag names.MachineTag) bool {
for _, app := range i.model.Applications() {
for _, unit := range app.Units() {
if unit.Machine() == tag {
return true
}
}
}
return false
}
func (i *importer) machineVolumes(tag names.MachineTag) []string {
var result []string
for _, volume := range i.model.Volumes() {
for _, attachment := range volume.Attachments() {
if attachment.Machine() == tag {
result = append(result, volume.Tag().Id())
}
}
}
return result
}
func (i *importer) machineFilesystems(tag names.MachineTag) []string {
var result []string
for _, filesystem := range i.model.Filesystems() {
for _, attachment := range filesystem.Attachments() {
if attachment.Machine() == tag {
result = append(result, filesystem.Tag().Id())
}
}
}
return result
}
func (i *importer) makeMachineJobs(jobs []string) ([]MachineJob, error) {
// At time of writing, there are three valid jobs. If any jobs gets
// deprecated or changed in the future, older models that specify those
// jobs need to be handled here.
result := make([]MachineJob, 0, len(jobs))
for _, job := range jobs {
switch job {
case "host-units":
result = append(result, JobHostUnits)
case "api-server":
result = append(result, JobManageModel)
default:
return nil, errors.Errorf("unknown machine job: %q", job)
}
}
return result, nil
}
func (i *importer) makeTools(t description.AgentTools) *tools.Tools {
if t == nil {
return nil
}
return &tools.Tools{
Version: t.Version(),
URL: t.URL(),
SHA256: t.SHA256(),
Size: t.Size(),
}
}
func (i *importer) makeAddress(addr description.Address) address {
if addr == nil {
return address{}
}
return address{
Value: addr.Value(),
AddressType: addr.Type(),
Scope: addr.Scope(),
Origin: addr.Origin(),
}
}
func (i *importer) makeAddresses(addrs []description.Address) []address {
result := make([]address, len(addrs))
for j, addr := range addrs {
result[j] = i.makeAddress(addr)
}
return result
}
func (i *importer) applications() error {
i.logger.Debugf("importing applications")
// Ensure we import principal applications first, so that
// subordinate units can refer to the principal ones.
var principals, subordinates []description.Application
for _, app := range i.model.Applications() {
if app.Subordinate() {
subordinates = append(subordinates, app)
} else {
principals = append(principals, app)
}
}
for _, s := range append(principals, subordinates...) {
if err := i.application(s); err != nil {
i.logger.Errorf("error importing application %s: %s", s.Name(), err)
return errors.Annotate(err, s.Name())
}
}
if err := i.loadUnits(); err != nil {
return errors.Annotate(err, "loading new units from db")
}
i.logger.Debugf("importing applications succeeded")
return nil
}
func (i *importer) loadUnits() error {
unitsCollection, closer := i.st.db().GetCollection(unitsC)
defer closer()
docs := []unitDoc{}
err := unitsCollection.Find(nil).All(&docs)
if err != nil {
return errors.Annotate(err, "cannot get all units")
}
result := make(map[string][]*Unit)
for _, doc := range docs {
units := result[doc.Application]
result[doc.Application] = append(units, newUnit(i.st, &doc))
}
i.applicationUnits = result
return nil
}
// makeStatusDoc assumes status is non-nil.
func (i *importer) makeStatusDoc(statusVal description.Status) statusDoc {
return statusDoc{
Status: status.Status(statusVal.Value()),
StatusInfo: statusVal.Message(),
StatusData: statusVal.Data(),
Updated: statusVal.Updated().UnixNano(),
}
}
func (i *importer) application(a description.Application) error {
// Import this application, then its units.
i.logger.Debugf("importing application %s", a.Name())
// 1. construct an applicationDoc
appDoc, err := i.makeApplicationDoc(a)
if err != nil {
return errors.Trace(err)
}
app := newApplication(i.st, appDoc)
// 2. construct a statusDoc
status := a.Status()
if status == nil {
return errors.NotValidf("missing status")
}
statusDoc := i.makeStatusDoc(status)
// TODO: update never set malarky... maybe...
// When creating the settings, we ignore nils. In other circumstances, nil
// means to delete the value (reset to default), so creating with nil should
// mean to use the default, i.e. don't set the value.
// There may have existed some applications with settings that contained
// nil values, see lp#1667199. When importing, we want these stripped.
removeNils(a.Settings())
ops, err := addApplicationOps(i.st, app, addApplicationOpsArgs{
applicationDoc: appDoc,
statusDoc: statusDoc,
constraints: i.constraints(a.Constraints()),
storage: i.storageConstraints(a.StorageConstraints()),
settings: a.Settings(),
leadershipSettings: a.LeadershipSettings(),
})
if err != nil {
return errors.Trace(err)
}
ops = append(ops, txn.Op{
C: endpointBindingsC,
Id: app.globalKey(),
Assert: txn.DocMissing,
Insert: endpointBindingsDoc{
Bindings: bindingsMap(a.EndpointBindings()),
},
})
ops = append(ops, i.appResourceOps(a)...)
if err := i.st.runTransaction(ops); err != nil {
return errors.Trace(err)
}
if annotations := a.Annotations(); len(annotations) > 0 {
if err := i.st.SetAnnotations(app, annotations); err != nil {
return errors.Trace(err)
}
}
if err := i.importStatusHistory(app.globalKey(), a.StatusHistory()); err != nil {
return errors.Trace(err)
}
for _, unit := range a.Units() {
if err := i.unit(a, unit); err != nil {
return errors.Trace(err)
}
}
if a.Leader() != "" {
if err := i.st.LeadershipClaimer().ClaimLeadership(
a.Name(),
a.Leader(),
initialLeaderClaimTime); err != nil {
return errors.Trace(err)
}
}
return nil
}
func (i *importer) appResourceOps(app description.Application) []txn.Op {
// Add a placeholder record for each resource that is a placeholder.
// Resources define placeholders as resources where the timestamp is Zero.
var result []txn.Op
appName := app.Name()
var makeResourceDoc = func(id, name string, rev description.ResourceRevision) resourceDoc {
fingerprint, _ := hex.DecodeString(rev.FingerprintHex())
return resourceDoc{
ID: id,
ApplicationID: appName,
Name: name,
Type: rev.Type(),
Path: rev.Path(),
Description: rev.Description(),
Origin: rev.Origin(),
Revision: rev.Revision(),
Fingerprint: fingerprint,
Size: rev.Size(),
Username: rev.Username(),
}
}
for _, r := range app.Resources() {
// I cannot for the life of me find the function where the underlying
// resource id is defined to be the appname/resname but that is what
// ends up in the DB.
resName := r.Name()
resID := appName + "/" + resName
// Check both the app and charmstore
if appRev := r.ApplicationRevision(); appRev.Timestamp().IsZero() {
result = append(result, txn.Op{
C: resourcesC,
Id: applicationResourceID(resID),
Assert: txn.DocMissing,
Insert: makeResourceDoc(resID, resName, appRev),
})
}
if storeRev := r.CharmStoreRevision(); storeRev.Timestamp().IsZero() {
doc := makeResourceDoc(resID, resName, storeRev)
// Now the resource code is particularly stupid and instead of using
// the ID, or encoding the type somewhere, it uses the fact that the
// LastPolled time to indicate it is the charm store version.
doc.LastPolled = time.Now()
result = append(result, txn.Op{
C: resourcesC,
Id: charmStoreResourceID(resID),
Assert: txn.DocMissing,
Insert: doc,
})
}
}
return result
}
func (i *importer) storageConstraints(cons map[string]description.StorageConstraint) map[string]StorageConstraints {
if len(cons) == 0 {
return nil
}
result := make(map[string]StorageConstraints)
for key, value := range cons {
result[key] = StorageConstraints{
Pool: value.Pool(),
Size: value.Size(),
Count: value.Count(),
}
}
return result
}
func (i *importer) unit(s description.Application, u description.Unit) error {
i.logger.Debugf("importing unit %s", u.Name())
// 1. construct a unitDoc
udoc, err := i.makeUnitDoc(s, u)
if err != nil {
return errors.Trace(err)
}
// 2. construct a statusDoc for the workload status and agent status
agentStatus := u.AgentStatus()
if agentStatus == nil {
return errors.NotValidf("missing agent status")
}
agentStatusDoc := i.makeStatusDoc(agentStatus)
workloadStatus := u.WorkloadStatus()
if workloadStatus == nil {
return errors.NotValidf("missing workload status")
}
workloadStatusDoc := i.makeStatusDoc(workloadStatus)
workloadVersion := u.WorkloadVersion()
versionStatus := status.Active
if workloadVersion == "" {
versionStatus = status.Unknown
}
workloadVersionDoc := statusDoc{
Status: versionStatus,
StatusInfo: workloadVersion,
}
ops, err := addUnitOps(i.st, addUnitOpsArgs{
unitDoc: udoc,
agentStatusDoc: agentStatusDoc,
workloadStatusDoc: workloadStatusDoc,
workloadVersionDoc: workloadVersionDoc,
meterStatusDoc: &meterStatusDoc{
Code: u.MeterStatusCode(),
Info: u.MeterStatusInfo(),
},
})
if err != nil {
return errors.Trace(err)
}
// If the unit is a principal, add it to its machine.
if u.Principal().Id() == "" {
ops = append(ops, txn.Op{
C: machinesC,
Id: u.Machine().Id(),
Assert: txn.DocExists,
Update: bson.M{"$addToSet": bson.M{"principals": u.Name()}},
})
}
// We should only have constraints for principal agents.
// We don't encode that business logic here, if there are constraints
// in the imported model, we put them in the database.
if cons := u.Constraints(); cons != nil {
agentGlobalKey := unitAgentGlobalKey(u.Name())
ops = append(ops, createConstraintsOp(i.st, agentGlobalKey, i.constraints(cons)))
}
if err := i.st.runTransaction(ops); err != nil {
i.logger.Debugf("failed ops: %#v", ops)
return errors.Trace(err)
}
unit := newUnit(i.st, udoc)
if annotations := u.Annotations(); len(annotations) > 0 {
if err := i.st.SetAnnotations(unit, annotations); err != nil {
return errors.Trace(err)
}
}
if err := i.importStatusHistory(unit.globalKey(), u.WorkloadStatusHistory()); err != nil {
return errors.Trace(err)
}
if err := i.importStatusHistory(unit.globalAgentKey(), u.AgentStatusHistory()); err != nil {
return errors.Trace(err)
}
if err := i.importStatusHistory(unit.globalWorkloadVersionKey(), u.WorkloadVersionHistory()); err != nil {
return errors.Trace(err)
}
if err := i.importUnitPayloads(unit, u.Payloads()); err != nil {
return errors.Trace(err)
}
return nil
}
func (i *importer) importUnitPayloads(unit *Unit, payloads []description.Payload) error {
up, err := i.st.UnitPayloads(unit)
if err != nil {
return errors.Trace(err)
}
for _, p := range payloads {
if err := up.Track(payload.Payload{
PayloadClass: charm.PayloadClass{
Name: p.Name(),
Type: p.Type(),
},
ID: p.RawID(),
Status: p.State(),
Labels: p.Labels(),
}); err != nil {
return errors.Trace(err)
}
}
return nil
}
func (i *importer) makeApplicationDoc(s description.Application) (*applicationDoc, error) {
charmURL, err := charm.ParseURL(s.CharmURL())
if err != nil {
return nil, errors.Trace(err)
}
return &applicationDoc{
Name: s.Name(),
Series: s.Series(),
Subordinate: s.Subordinate(),
CharmURL: charmURL,
Channel: s.Channel(),
CharmModifiedVersion: s.CharmModifiedVersion(),
ForceCharm: s.ForceCharm(),
Life: Alive,
UnitCount: len(s.Units()),
RelationCount: i.relationCount(s.Name()),
Exposed: s.Exposed(),
MinUnits: s.MinUnits(),
MetricCredentials: s.MetricsCredentials(),
}, nil
}