-
Notifications
You must be signed in to change notification settings - Fork 0
/
allwatcher.go
2264 lines (2032 loc) · 67.1 KB
/
allwatcher.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 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"reflect"
"strings"
"github.com/juju/charm/v8"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/mgo/v2"
"github.com/juju/mgo/v2/bson"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/life"
"github.com/juju/juju/core/model"
"github.com/juju/juju/core/multiwatcher"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/permission"
"github.com/juju/juju/core/status"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/state/watcher"
)
// Yes this is global. We should probably put a logger into the State object,
// and create a child logger from that.
var allWatcherLogger = loggo.GetLogger("juju.state.allwatcher")
// allWatcherBacking implements AllWatcherBacking by fetching entities
// for all models from the State.
type allWatcherBacking struct {
watcher watcher.BaseWatcher
stPool *StatePool
collections []string
collectionByName map[string]allWatcherStateCollection
}
// allWatcherStateCollection holds information about a
// collection watched by an allWatcher and the
// type of value we use to store entity information
// for that collection.
type allWatcherStateCollection struct {
// name stores the name of the collection.
name string
// docType stores the type of document
// that we use for this collection.
docType reflect.Type
// subsidiary is true if the collection is used only
// to modify a primary entity.
subsidiary bool
}
// makeAllWatcherCollectionInfo returns a name indexed map of
// allWatcherStateCollection instances for the collections specified.
func makeAllWatcherCollectionInfo(collNames []string) map[string]allWatcherStateCollection {
seenTypes := make(map[reflect.Type]struct{})
collectionByName := make(map[string]allWatcherStateCollection)
for _, collName := range collNames {
collection := allWatcherStateCollection{name: collName}
switch collName {
case modelsC:
collection.docType = reflect.TypeOf(backingModel{})
case machinesC:
collection.docType = reflect.TypeOf(backingMachine{})
case instanceDataC:
collection.docType = reflect.TypeOf(backingInstanceData{})
collection.subsidiary = true
case unitsC:
collection.docType = reflect.TypeOf(backingUnit{})
case applicationsC:
collection.docType = reflect.TypeOf(backingApplication{})
case charmsC:
collection.docType = reflect.TypeOf(backingCharm{})
case actionsC:
collection.docType = reflect.TypeOf(backingAction{})
case relationsC:
collection.docType = reflect.TypeOf(backingRelation{})
case annotationsC:
collection.docType = reflect.TypeOf(backingAnnotation{})
// TODO: this should be a subsidiary too.
case blocksC:
collection.docType = reflect.TypeOf(backingBlock{})
case statusesC:
collection.docType = reflect.TypeOf(backingStatus{})
collection.subsidiary = true
case constraintsC:
collection.docType = reflect.TypeOf(backingConstraints{})
collection.subsidiary = true
case settingsC:
collection.docType = reflect.TypeOf(backingSettings{})
collection.subsidiary = true
case openedPortsC:
collection.docType = reflect.TypeOf(backingOpenedPorts{})
collection.subsidiary = true
case remoteApplicationsC:
collection.docType = reflect.TypeOf(backingRemoteApplication{})
case applicationOffersC:
collection.docType = reflect.TypeOf(backingApplicationOffer{})
case generationsC:
collection.docType = reflect.TypeOf(backingGeneration{})
case permissionsC:
// Permissions are attached to the Model that they are for.
collection.docType = reflect.TypeOf(backingPermission{})
collection.subsidiary = true
case podSpecsC:
collection.docType = reflect.TypeOf(backingPodSpec{})
collection.subsidiary = true
default:
allWatcherLogger.Criticalf("programming error: unknown collection %q", collName)
}
docType := collection.docType
if _, ok := seenTypes[docType]; ok {
allWatcherLogger.Criticalf("programming error: duplicate collection type %s", docType)
} else {
seenTypes[docType] = struct{}{}
}
if _, ok := collectionByName[collName]; ok {
allWatcherLogger.Criticalf("programming error: duplicate collection name %q", collName)
} else {
collectionByName[collName] = collection
}
}
return collectionByName
}
type backingModel modelDoc
func (e *backingModel) isNotFoundAndModelDead(err error) bool {
// Return true if the error is not found and the model is dead.
// This will be the case if the model has been marked dead, pending cleanup.
return errors.IsNotFound(err) && e.Life == Dead
}
func (e *backingModel) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`model "%s" updated`, ctx.id)
// Update the context with the model type.
ctx.modelType_ = e.Type
info := &multiwatcher.ModelInfo{
ModelUUID: e.UUID,
Type: model.ModelType(e.Type),
Name: e.Name,
Life: life.Value(e.Life.String()),
Owner: e.Owner,
ControllerUUID: e.ControllerUUID,
IsController: ctx.state.IsController(),
Cloud: e.Cloud,
CloudRegion: e.CloudRegion,
CloudCredential: e.CloudCredential,
SLA: multiwatcher.ModelSLAInfo{
Level: e.SLA.Level.String(),
Owner: e.SLA.Owner,
},
}
oldInfo := ctx.store.Get(info.EntityID())
if oldInfo == nil {
settings, err := ctx.getSettings(modelGlobalKey)
if e.isNotFoundAndModelDead(err) {
// Since we know this isn't in the store, stop looking for new
// things.
return nil
}
if err != nil {
return errors.Trace(err)
}
cfg, err := config.New(config.NoDefaults, settings)
if err != nil {
return errors.Trace(err)
}
info.Config = cfg.AllAttrs()
// Annotations are optional, so may not be there.
info.Annotations = ctx.getAnnotations(modelGlobalKey)
c, err := ctx.readConstraints(modelGlobalKey)
if e.isNotFoundAndModelDead(err) {
// Since we know this isn't in the store, stop looking for new
// things.
return nil
}
if err != nil {
return errors.Trace(err)
}
info.Constraints = c
info.Status, err = ctx.getStatus(modelGlobalKey, "model")
if e.isNotFoundAndModelDead(err) {
// Since we know this isn't in the store, stop looking for new
// things.
return nil
}
if err != nil {
return errors.Trace(err)
}
permissions, err := ctx.permissionsForModel(e.UUID)
if err != nil {
return errors.Trace(err)
}
info.UserPermissions = permissions
} else {
oldInfo := oldInfo.(*multiwatcher.ModelInfo)
info.Annotations = oldInfo.Annotations
info.Config = oldInfo.Config
info.Constraints = oldInfo.Constraints
info.Status = oldInfo.Status
info.UserPermissions = oldInfo.UserPermissions
}
ctx.store.Update(info)
return nil
}
func (e *backingModel) removed(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`model "%s" removed`, ctx.id)
ctx.removeFromStore(multiwatcher.ModelKind)
return nil
}
func (e *backingModel) mongoID() string {
return e.UUID
}
type backingPermission permissionDoc
func (e *backingPermission) modelAndUser(id string) (string, string, bool) {
parts := strings.Split(id, "#")
if len(parts) < 4 {
// Not valid for as far as we care about.
return "", "", false
}
// At this stage, we are only dealing with model user permissions.
if parts[0] != modelGlobalKey || parts[2] != userGlobalKeyPrefix {
return "", "", false
}
return parts[1], parts[3], true
}
func (e *backingPermission) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`permission "%s" updated`, ctx.id)
modelUUID, user, ok := e.modelAndUser(ctx.id)
if !ok {
// Not valid for as far as we care about.
return nil
}
info := e.getModelInfo(ctx, modelUUID)
if info == nil {
return nil
}
// Set the access for the user in the permission map of the model.
info.UserPermissions[user] = permission.Access(e.Access)
ctx.store.Update(info)
return nil
}
func (e *backingPermission) removed(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`permission "%s" removed`, ctx.id)
modelUUID, user, ok := e.modelAndUser(ctx.id)
if !ok {
// Not valid for as far as we care about.
return nil
}
info := e.getModelInfo(ctx, modelUUID)
if info == nil {
return nil
}
delete(info.UserPermissions, user)
ctx.store.Update(info)
return nil
}
func (e *backingPermission) getModelInfo(ctx *allWatcherContext, modelUUID string) *multiwatcher.ModelInfo {
// NOTE: we can't use the modelUUID from the ctx here because it is the
// modelUUID of the system state.
storeKey := &multiwatcher.ModelInfo{
ModelUUID: modelUUID,
}
info0 := ctx.store.Get(storeKey.EntityID())
switch info := info0.(type) {
case *multiwatcher.ModelInfo:
return info
}
// In all other cases, which really should be never, return nil.
return nil
}
func (e *backingPermission) mongoID() string {
allWatcherLogger.Criticalf("programming error: attempting to get mongoID from permissions document")
return ""
}
type backingMachine machineDoc
func (m *backingMachine) updateAgentVersion(info *multiwatcher.MachineInfo) {
if m.Tools != nil {
info.AgentStatus.Version = m.Tools.Version.Number.String()
}
}
func (m *backingMachine) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`machine "%s:%s" updated`, ctx.modelUUID, ctx.id)
wantsVote := false
hasVote := false
if ctx.state.IsController() {
// We can handle an extra query here as long as it is only for controller
// machines. Could potentially optimize further if necessary for initial load.
node, err := ctx.state.ControllerNode(m.Id)
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
wantsVote = err == nil && node.WantsVote()
hasVote = err == nil && node.HasVote()
}
modelID, _, _ := ctx.entityIDForGlobalKey(modelGlobalKey)
modelEntity := ctx.store.Get(modelID)
var providerType string
if modelEntity != nil {
modelInfo := modelEntity.(*multiwatcher.ModelInfo)
providerType, _ = modelInfo.Config["type"].(string)
}
isManual := isManualMachine(m.Id, m.Nonce, providerType)
info := &multiwatcher.MachineInfo{
ModelUUID: m.ModelUUID,
ID: m.Id,
Life: life.Value(m.Life.String()),
Series: m.Series,
ContainerType: m.ContainerType,
IsManual: isManual,
Jobs: paramsJobsFromJobs(m.Jobs),
SupportedContainers: m.SupportedContainers,
SupportedContainersKnown: m.SupportedContainersKnown,
HasVote: hasVote,
WantsVote: wantsVote,
PreferredPublicAddress: m.PreferredPublicAddress.networkAddress(),
PreferredPrivateAddress: m.PreferredPrivateAddress.networkAddress(),
Hostname: m.Hostname,
}
addresses := network.MergedAddresses(networkAddresses(m.MachineAddresses), networkAddresses(m.Addresses))
for _, addr := range addresses {
mAddr := network.ProviderAddress{
MachineAddress: addr.MachineAddress,
}
spaceID := addr.SpaceID
if spaceID != network.AlphaSpaceId && spaceID != "" {
// TODO: cache spaces
space, err := ctx.state.Space(spaceID)
if err != nil {
return errors.Annotatef(err, "retrieving space for ID %q", spaceID)
}
mAddr.SpaceName = network.SpaceName(space.Name())
mAddr.ProviderSpaceID = space.ProviderId()
}
info.Addresses = append(info.Addresses, mAddr)
}
oldInfo := ctx.store.Get(info.EntityID())
if oldInfo == nil {
key := machineGlobalKey(m.Id)
agentStatus, err := ctx.getStatus(key, "machine agent")
if err != nil {
return errors.Annotatef(err, "reading machine agent for key %s", key)
}
info.AgentStatus = agentStatus
key = machineGlobalInstanceKey(m.Id)
instanceStatus, err := ctx.getStatus(key, "machine instance")
if err != nil {
return errors.Annotatef(err, "reading machine instance for key %s", key)
}
info.InstanceStatus = instanceStatus
// Annotations are optional, so may not be there.
info.Annotations = ctx.getAnnotations(key)
} else {
// The entry already exists, so preserve the current status and
// instance data. These will be updated as necessary as the status and instance data
// updates come through.
oldInfo := oldInfo.(*multiwatcher.MachineInfo)
info.AgentStatus = oldInfo.AgentStatus
info.Annotations = oldInfo.Annotations
info.InstanceStatus = oldInfo.InstanceStatus
info.InstanceID = oldInfo.InstanceID
info.HardwareCharacteristics = oldInfo.HardwareCharacteristics
}
m.updateAgentVersion(info)
// If the machine is been provisioned, fetch the instance id as required,
// and set instance id and hardware characteristics.
instanceData, err := ctx.getInstanceData(m.Id)
if err == nil {
if m.Nonce != "" && info.InstanceID == "" {
info.InstanceID = string(instanceData.InstanceId)
info.HardwareCharacteristics = hardwareCharacteristics(instanceData)
}
// InstanceMutater needs the liveliness of the instanceData.CharmProfiles
// as this changes with charm-upgrades
info.CharmProfiles = instanceData.CharmProfiles
} else if !errors.IsNotFound(err) {
return err
}
ctx.store.Update(info)
return nil
}
func (m *backingMachine) removed(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`machine "%s:%s" removed`, ctx.modelUUID, ctx.id)
ctx.removeFromStore(multiwatcher.MachineKind)
return nil
}
func (m *backingMachine) mongoID() string {
return m.Id
}
type backingInstanceData instanceData
func (i *backingInstanceData) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`instance data "%s:%s" updated`, ctx.modelUUID, ctx.id)
parentID, _, ok := ctx.entityIDForGlobalKey(machineGlobalKey(ctx.id))
if !ok {
return nil
}
info0 := ctx.store.Get(parentID)
switch info := info0.(type) {
case nil:
// The parent info doesn't exist. Ignore the status until it does.
return nil
case *multiwatcher.MachineInfo:
newInfo := *info
var instanceData *instanceData = (*instanceData)(i)
newInfo.HardwareCharacteristics = hardwareCharacteristics(*instanceData)
newInfo.CharmProfiles = instanceData.CharmProfiles
info0 = &newInfo
default:
return errors.Errorf("instanceData for unexpected entity with id %q; type %T", ctx.id, info)
}
ctx.store.Update(info0)
return nil
}
func (i *backingInstanceData) removed(ctx *allWatcherContext) error {
// If the instanceData is removed, the machine will follow not long
// after so do nothing.
return nil
}
func (i *backingInstanceData) mongoID() string {
// This is a subsidiary collection, we shouldn't be calling mongoID.
return i.MachineId
}
type backingUnit unitDoc
func (u *backingUnit) unitAndAgentStatus(ctx *allWatcherContext, info *multiwatcher.UnitInfo) error {
unitStatusResult, err := ctx.getStatus(unitGlobalKey(u.Name), "unit")
if err != nil {
return errors.Trace(err)
}
agentStatusResult, err := ctx.getStatus(unitAgentGlobalKey(u.Name), "unit")
if err != nil {
return errors.Trace(err)
}
// NOTE: c.f. *Unit.Status(), we need to deal with the error state.
if agentStatusResult.Current == status.Error {
since := agentStatusResult.Since
unitStatusResult = agentStatusResult
agentStatusResult = multiwatcher.StatusInfo{
Current: status.Idle,
Data: normaliseStatusData(nil),
Since: since,
}
}
// Unit and workload status.
info.WorkloadStatus = unitStatusResult
info.AgentStatus = agentStatusResult
return nil
}
func (u *backingUnit) updateAgentVersion(info *multiwatcher.UnitInfo) {
if u.Tools != nil {
info.AgentStatus.Version = u.Tools.Version.Number.String()
}
}
func (u *backingUnit) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`unit "%s:%s" updated`, ctx.modelUUID, ctx.id)
info := &multiwatcher.UnitInfo{
ModelUUID: u.ModelUUID,
Name: u.Name,
Application: u.Application,
Series: u.Series,
Life: life.Value(u.Life.String()),
MachineID: u.MachineId,
Principal: u.Principal,
Subordinate: u.Principal != "",
}
if u.CharmURL != nil {
info.CharmURL = u.CharmURL.String()
}
// Construct a unit for the purpose of retrieving other fields as necessary.
modelType, err := ctx.modelType()
if err != nil {
return errors.Annotatef(err, "get model type for %q", ctx.modelUUID)
}
var unitDoc unitDoc = unitDoc(*u)
unit := newUnit(ctx.state, modelType, &unitDoc)
oldInfo := ctx.store.Get(info.EntityID())
if oldInfo == nil {
allWatcherLogger.Debugf("new unit %q added to backing state", u.Name)
// Annotations are optional, so may not be there.
info.Annotations = ctx.getAnnotations(unitGlobalKey(u.Name))
// We're adding the entry for the first time,
// so fetch the associated unit status and opened ports.
err := u.unitAndAgentStatus(ctx, info)
if err != nil {
return errors.Annotatef(err, "retrieve unit and agent status for %q", u.Name)
}
unitPortRangesByEndpoint, err := ctx.getUnitPortRangesByEndpoint(unit)
if err != nil {
return errors.Trace(err)
}
info.OpenPortRangesByEndpoint = unitPortRangesByEndpoint.Clone()
if modelType == ModelTypeCAAS {
containerStatus, err := ctx.getStatus(globalCloudContainerKey(u.Name), "cloud container")
if err == nil {
info.ContainerStatus = containerStatus
}
}
} else {
// The entry already exists, so preserve the current status and ports.
oldInfo := oldInfo.(*multiwatcher.UnitInfo)
info.Annotations = oldInfo.Annotations
// Unit and workload status.
info.AgentStatus = oldInfo.AgentStatus
info.WorkloadStatus = oldInfo.WorkloadStatus
info.ContainerStatus = oldInfo.ContainerStatus
info.OpenPortRangesByEndpoint = oldInfo.OpenPortRangesByEndpoint
}
u.updateAgentVersion(info)
// This is horrible as we are loading the machine twice for every unit.
// Can't optimize this yet.
// TODO: deprecate this ASAP and remove ASAP. It is only there for backwards
// compatibility to 1.18.
publicAddress, privateAddress, err := ctx.getUnitAddresses(unit)
if err != nil {
return errors.Annotatef(err, "get addresses for %q", u.Name)
}
info.PublicAddress = publicAddress
info.PrivateAddress = privateAddress
ctx.store.Update(info)
return nil
}
// getUnitAddresses returns the public and private addresses on a given unit.
// As of 1.18, the addresses are stored on the assigned machine but we retain
// this approach for backwards compatibility.
func (ctx *allWatcherContext) getUnitAddresses(u *Unit) (string, string, error) {
// If we are dealing with a CAAS unit, use the unit methods, they
// are complicated and not yet mirrored in the allwatcher. Also there
// are entities in CAAS models that should probably be exposed up to the
// model cache, but haven't yet.
modelType, err := ctx.modelType()
if err != nil {
return "", "", errors.Annotatef(err, "get model type for %q", ctx.modelUUID)
}
if modelType == ModelTypeCAAS {
publicAddress, err := u.PublicAddress()
if err != nil {
allWatcherLogger.Tracef("getting a public address for unit %q failed: %q", u.Name(), err)
}
privateAddress, err := u.PrivateAddress()
if err != nil {
allWatcherLogger.Tracef("getting a private address for unit %q failed: %q", u.Name(), err)
}
return publicAddress.Value, privateAddress.Value, nil
}
machineID, _ := u.AssignedMachineId()
if machineID == "" {
return "", "", nil
}
// Get the machine out of the store and use the preferred public and
// preferred private addresses out of that.
machineInfo := ctx.getMachineInfo(machineID)
if machineInfo == nil {
// We know that the machines are processed before the units, so they
// will always be there when we are looking. Except for the case where
// we are in the process of deleting the machine or units as they are
// being destroyed. If this is the case, we don't really care about
// the addresses, so returning empty values is fine.
return "", "", nil
}
return machineInfo.PreferredPublicAddress.Value, machineInfo.PreferredPrivateAddress.Value, nil
}
func (u *backingUnit) removed(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`unit "%s:%s" removed`, ctx.modelUUID, ctx.id)
ctx.removeFromStore(multiwatcher.UnitKind)
return nil
}
func (u *backingUnit) mongoID() string {
return u.Name
}
type backingApplication applicationDoc
func (app *backingApplication) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`application "%s:%s" updated`, ctx.modelUUID, ctx.id)
if app.CharmURL == nil {
return errors.Errorf("charm url is nil")
}
info := &multiwatcher.ApplicationInfo{
ModelUUID: app.ModelUUID,
Name: app.Name,
Exposed: app.Exposed,
CharmURL: app.CharmURL.String(),
Life: life.Value(app.Life.String()),
MinUnits: app.MinUnits,
Subordinate: app.Subordinate,
}
oldInfo := ctx.store.Get(info.EntityID())
needConfig := false
if oldInfo == nil {
allWatcherLogger.Debugf("new application %q added to backing state", app.Name)
key := applicationGlobalKey(app.Name)
// Annotations are optional, so may not be there.
info.Annotations = ctx.getAnnotations(key)
// We're adding the entry for the first time,
// so fetch the associated child documents.
c, err := ctx.readConstraints(key)
if err != nil {
return errors.Trace(err)
}
info.Constraints = c
needConfig = true
applicationStatus, err := ctx.getStatus(key, "application")
if err != nil {
return errors.Annotatef(err, "reading application status for key %s", key)
}
info.Status = applicationStatus
// OperatorStatus is only available for CAAS applications.
// So if we don't find it, don't worry.
modelType, err := ctx.modelType()
if err != nil {
return errors.Annotatef(err, "get model type for %q", ctx.modelUUID)
}
if modelType == ModelTypeCAAS {
// Look for the PodSpec for this application.
var doc backingPodSpec
if err := readPodInfo(ctx.state.db(), app.Name, &doc); err != nil {
if errors.IsNotFound(err) {
// This is expected in some situations, there just hasn't
// been a call to set the pod spec.
} else {
return errors.Annotatef(err, "get podSpec for %s", app.Name)
}
} else {
info.PodSpec = doc.asPodSpec()
}
key = applicationGlobalOperatorKey(app.Name)
operatorStatus, err := ctx.getStatus(key, "application operator")
if err == nil {
info.OperatorStatus = operatorStatus
}
}
} else {
// The entry already exists, so preserve the current status.
appInfo := oldInfo.(*multiwatcher.ApplicationInfo)
info.Annotations = appInfo.Annotations
info.Constraints = appInfo.Constraints
info.WorkloadVersion = appInfo.WorkloadVersion
if info.CharmURL == appInfo.CharmURL {
// The charm URL remains the same - we can continue to
// use the same config settings.
info.Config = appInfo.Config
} else {
// The charm URL has changed - we need to fetch the
// settings from the new charm's settings doc.
needConfig = true
}
info.Status = appInfo.Status
info.OperatorStatus = appInfo.OperatorStatus
info.PodSpec = appInfo.PodSpec
}
if needConfig {
config, err := ctx.getSettings(applicationCharmConfigKey(app.Name, app.CharmURL))
if err != nil {
return errors.Annotatef(err, "application %q", app.Name)
}
info.Config = config
}
ctx.store.Update(info)
return nil
}
func (app *backingApplication) removed(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`application "%s:%s" removed`, ctx.modelUUID, ctx.id)
ctx.removeFromStore(multiwatcher.ApplicationKind)
return nil
}
func (app *backingApplication) mongoID() string {
return app.Name
}
type backingPodSpec containerSpecDoc
func (ps *backingPodSpec) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`podspec "%s:%s" updated`, ctx.modelUUID, ctx.id)
// The id of the podspec is the application global key.
parentID, _, ok := ctx.entityIDForGlobalKey(ctx.id)
if !ok {
return nil
}
info0 := ctx.store.Get(parentID)
switch info := info0.(type) {
case nil:
// The parent info doesn't exist. Ignore until it does.
return nil
case *multiwatcher.ApplicationInfo:
newInfo := *info
newInfo.PodSpec = ps.asPodSpec()
info0 = &newInfo
default:
allWatcherLogger.Warningf("unexpected podspec type: %T", info)
return nil
}
ctx.store.Update(info0)
return nil
}
func (ps *backingPodSpec) asPodSpec() *multiwatcher.PodSpec {
podSpec := &multiwatcher.PodSpec{
Spec: ps.Spec,
Counter: ps.UpgradeCounter,
}
if len(podSpec.Spec) == 0 && len(ps.RawSpec) > 0 {
podSpec.Spec = ps.RawSpec
podSpec.Raw = true
}
return podSpec
}
func (ps *backingPodSpec) removed(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`podspec "%s:%s" removed`, ctx.modelUUID, ctx.id)
// The podSpec is only removed when the application is removed, so we don't care.
return nil
}
func (ps *backingPodSpec) mongoID() string {
allWatcherLogger.Criticalf("programming error: attempting to get mongoID from podspec document")
return ""
}
type backingCharm charmDoc
func (ch *backingCharm) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`charm "%s:%s" updated`, ctx.modelUUID, ctx.id)
info := &multiwatcher.CharmInfo{
ModelUUID: ch.ModelUUID,
CharmURL: ch.URL.String(),
CharmVersion: ch.CharmVersion,
Life: life.Value(ch.Life.String()),
}
if ch.LXDProfile != nil && !ch.LXDProfile.Empty() {
info.LXDProfile = toMultiwatcherProfile(ch.LXDProfile)
}
if ch.Config != nil {
if ds := ch.Config.DefaultSettings(); len(ds) > 0 {
info.DefaultConfig = ds
}
}
ctx.store.Update(info)
return nil
}
func (ch *backingCharm) removed(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`charm "%s:%s" removed`, ctx.modelUUID, ctx.id)
ctx.removeFromStore(multiwatcher.CharmKind)
return nil
}
func (ch *backingCharm) mongoID() string {
_, id, ok := splitDocID(ch.DocID)
if !ok {
allWatcherLogger.Criticalf("charm ID not valid: %v", ch.DocID)
}
return id
}
func toMultiwatcherProfile(profile *LXDProfile) *multiwatcher.Profile {
unescapedProfile := unescapeLXDProfile(profile)
return &multiwatcher.Profile{
Config: unescapedProfile.Config,
Description: unescapedProfile.Description,
Devices: unescapedProfile.Devices,
}
}
type backingRemoteApplication remoteApplicationDoc
func (app *backingRemoteApplication) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`remote application "%s:%s" updated`, ctx.modelUUID, ctx.id)
if app.Name == "" {
return errors.Errorf("saas application name is not set")
}
if app.IsConsumerProxy {
// Since this is a consumer proxy, we update the offer
// info in this (the offering) model.
return app.updateOfferInfo(ctx)
}
info := &multiwatcher.RemoteApplicationUpdate{
ModelUUID: ctx.modelUUID, // ModelUUID not part of the remoteApplicationDoc
Name: app.Name,
OfferUUID: app.OfferUUID,
OfferURL: app.URL,
Life: life.Value(app.Life.String()),
}
oldInfo := ctx.store.Get(info.EntityID())
if oldInfo == nil {
allWatcherLogger.Debugf("new remote application %q added to backing state", app.Name)
// Fetch the status.
key := remoteApplicationGlobalKey(app.Name)
appStatus, err := ctx.getStatus(key, "saas application")
if err != nil {
return errors.Annotatef(err, "reading remote application status for key %s", key)
}
info.Status = appStatus
allWatcherLogger.Debugf("saas application status %#v", info.Status)
} else {
allWatcherLogger.Debugf("use status from existing app")
switch t := oldInfo.(type) {
case *multiwatcher.RemoteApplicationUpdate:
info.Status = t.Status
default:
allWatcherLogger.Debugf("unexpected type %t", t)
}
}
ctx.store.Update(info)
return nil
}
func (app *backingRemoteApplication) updateOfferInfo(ctx *allWatcherContext) error {
// Remote Applications reference an offer using the offer UUID.
// Offers in the store use offer name as the id key, so we need
// to look through the store entities to find any matching offer.
var offerInfo *multiwatcher.ApplicationOfferInfo
entities := ctx.store.All()
for _, e := range entities {
var ok bool
if offerInfo, ok = e.(*multiwatcher.ApplicationOfferInfo); ok {
if offerInfo.OfferUUID != app.OfferUUID {
offerInfo = nil
continue
}
break
}
}
// If we have an existing remote application,
// adjust any offer info also.
if offerInfo == nil {
return nil
}
// TODO: be smarter about reading status.
remoteConnection, err := ctx.state.RemoteConnectionStatus(offerInfo.OfferUUID)
if err != nil {
return errors.Trace(err)
}
offerInfo.TotalConnectedCount = remoteConnection.TotalConnectionCount()
offerInfo.ActiveConnectedCount = remoteConnection.ActiveConnectionCount()
ctx.store.Update(offerInfo)
return nil
}
func (app *backingRemoteApplication) removed(ctx *allWatcherContext) (err error) {
allWatcherLogger.Tracef(`remote application "%s:%s" removed`, ctx.modelUUID, ctx.id)
// TODO: see if we need the check of consumer proxy like in the change
err = app.updateOfferInfo(ctx)
if err != nil {
// We log the error but don't prevent the remote app removal.
allWatcherLogger.Errorf("updating application offer info: %v", err)
}
ctx.removeFromStore(multiwatcher.RemoteApplicationKind)
return err
}
func (app *backingRemoteApplication) mongoID() string {
return app.Name
}
type backingApplicationOffer applicationOfferDoc
func (b *backingApplicationOffer) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`application offer "%s:%s" updated`, ctx.modelUUID, ctx.id)
info := &multiwatcher.ApplicationOfferInfo{
ModelUUID: ctx.modelUUID, // ModelUUID not on applicationOfferDoc
OfferName: b.OfferName,
OfferUUID: b.OfferUUID,
ApplicationName: b.ApplicationName,
}
// UGH, this abstraction means we are likely doing needless queries.
offers := NewApplicationOffers(ctx.state)
offer, err := offers.ApplicationOfferForUUID(info.OfferUUID)
if err != nil {
return errors.Trace(err)
}
localApp, err := ctx.state.Application(offer.ApplicationName)
if err != nil {
return errors.Trace(err)
}
curl, _ := localApp.CharmURL()
info.ApplicationName = offer.ApplicationName
info.CharmName = curl.Name
remoteConnection, err := ctx.state.RemoteConnectionStatus(info.OfferUUID)
if err != nil {
return errors.Trace(err)
}
info.TotalConnectedCount = remoteConnection.TotalConnectionCount()
info.ActiveConnectedCount = remoteConnection.ActiveConnectionCount()
ctx.store.Update(info)
return nil
}
func (b *backingApplicationOffer) removed(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`application offer "%s:%s" removed`, ctx.modelUUID, ctx.id)
ctx.removeFromStore(multiwatcher.ApplicationOfferKind)
return nil
}
func (b *backingApplicationOffer) mongoID() string {
return b.OfferName
}
type backingAction actionDoc
func (a *backingAction) mongoID() string {
_, id, ok := splitDocID(a.DocId)
if !ok {
allWatcherLogger.Criticalf("action ID not valid: %v", a.DocId)
}
return id
}
func (a *backingAction) removed(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`action "%s:%s" removed`, ctx.modelUUID, ctx.id)
ctx.removeFromStore(multiwatcher.ActionKind)
return nil
}
func (a *backingAction) updated(ctx *allWatcherContext) error {
allWatcherLogger.Tracef(`action "%s:%s" updated`, ctx.modelUUID, ctx.id)
info := &multiwatcher.ActionInfo{
ModelUUID: a.ModelUUID,
ID: ctx.id, // local ID isn't available on the action doc
Receiver: a.Receiver,
Name: a.Name,
Parameters: a.Parameters,