-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.go
1264 lines (1152 loc) · 37.7 KB
/
watcher.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 apiserver
import (
"github.com/juju/errors"
"github.com/kr/pretty"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/common/crossmodel"
"github.com/juju/juju/apiserver/common/storagecommon"
apiservererrors "github.com/juju/juju/apiserver/errors"
"github.com/juju/juju/apiserver/facade"
"github.com/juju/juju/apiserver/facades/controller/crossmodelrelations"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/controller"
"github.com/juju/juju/core/cache"
"github.com/juju/juju/core/migration"
"github.com/juju/juju/core/multiwatcher"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/status"
corewatcher "github.com/juju/juju/core/watcher"
"github.com/juju/juju/state"
)
// NewAllWatcher returns a new API server endpoint for interacting
// with a watcher created by the WatchAll and WatchAllModels API calls.
func NewAllWatcher(context facade.Context) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
if !auth.AuthClient() {
// Note that we don't need to check specific permissions
// here, as the AllWatcher can only do anything if the
// watcher resource has already been created, so we can
// rely on the permission check there to ensure that
// this facade can't do anything it shouldn't be allowed
// to.
//
// This is useful because the AllWatcher is reused for
// both the WatchAll (requires model access rights) and
// the WatchAllModels (requring controller superuser
// rights) API calls.
return nil, apiservererrors.ErrPerm
}
watcher, ok := resources.Get(id).(multiwatcher.Watcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher
}
return &SrvAllWatcher{
watcherCommon: newWatcherCommon(context),
watcher: watcher,
}, nil
}
type watcherCommon struct {
id string
resources facade.Resources
dispose func()
controller *cache.Controller
}
func newWatcherCommon(context facade.Context) watcherCommon {
return watcherCommon{
context.ID(),
context.Resources(),
context.Dispose,
context.Controller(),
}
}
// Stop stops the watcher.
func (w *watcherCommon) Stop() error {
w.dispose()
return w.resources.Stop(w.id)
}
// SrvAllWatcher defines the API methods on a state.Multiwatcher.
// which watches any changes to the state. Each client has its own
// current set of watchers, stored in resources. It is used by both
// the AllWatcher and AllModelWatcher facades.
type SrvAllWatcher struct {
watcherCommon
watcher multiwatcher.Watcher
}
// Next will return the current state of everything on the first call
// and subsequent calls will
func (aw *SrvAllWatcher) Next() (params.AllWatcherNextResults, error) {
deltas, err := aw.watcher.Next()
return params.AllWatcherNextResults{
Deltas: aw.translate(deltas),
}, err
}
func (aw *SrvAllWatcher) translate(deltas []multiwatcher.Delta) []params.Delta {
response := make([]params.Delta, 0, len(deltas))
for _, delta := range deltas {
id := delta.Entity.EntityID()
var converted params.EntityInfo
switch id.Kind {
case multiwatcher.ModelKind:
converted = aw.translateModel(delta.Entity)
case multiwatcher.ApplicationKind:
converted = aw.translateApplication(delta.Entity)
case multiwatcher.RemoteApplicationKind:
converted = aw.translateRemoteApplication(delta.Entity)
case multiwatcher.MachineKind:
converted = aw.translateMachine(delta.Entity)
case multiwatcher.UnitKind:
converted = aw.translateUnit(delta.Entity)
case multiwatcher.CharmKind:
converted = aw.translateCharm(delta.Entity)
case multiwatcher.RelationKind:
converted = aw.translateRelation(delta.Entity)
case multiwatcher.BranchKind:
converted = aw.translateBranch(delta.Entity)
case multiwatcher.AnnotationKind: // THIS SEEMS WEIRD
// FIXME: annotations should be part of the underlying entity.
converted = aw.translateAnnotation(delta.Entity)
case multiwatcher.BlockKind:
converted = aw.translateBlock(delta.Entity)
case multiwatcher.ActionKind:
converted = aw.translateAction(delta.Entity)
case multiwatcher.ApplicationOfferKind:
converted = aw.translateApplicationOffer(delta.Entity)
default:
// converted stays nil
}
// It is possible that there are some multiwatcher elements that are
// internal, and not exposed outside the controller.
// Also this is a key place to start versioning the all watchers.
if converted != nil {
response = append(response, params.Delta{
Removed: delta.Removed,
Entity: converted})
}
}
return response
}
func (aw *SrvAllWatcher) translateModel(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.ModelInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.ModelUpdate{
ModelUUID: orig.ModelUUID,
Name: orig.Name,
Life: orig.Life,
Owner: orig.Owner,
ControllerUUID: orig.ControllerUUID,
IsController: orig.IsController,
Config: orig.Config,
Status: aw.translateStatus(orig.Status),
Constraints: orig.Constraints,
SLA: params.ModelSLAInfo{
Level: orig.SLA.Level,
Owner: orig.SLA.Owner,
},
}
}
func (aw *SrvAllWatcher) translateStatus(info multiwatcher.StatusInfo) params.StatusInfo {
return params.StatusInfo{
Err: info.Err, // CHECK THIS
Current: info.Current,
Message: info.Message,
Since: info.Since,
Version: info.Version,
Data: info.Data,
}
}
func (aw *SrvAllWatcher) translateApplication(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.ApplicationInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
// If the application status is unset, then set it to unknown. It is
// expected that downstream clients (model cache, pylibjuju, jslibjuju)
// correctly interpret the unknown status from the unit status. If the unit
// status is not found, then fall back to unknown.
// If a charm author has set the application status, then show that instead.
applicationStatus := multiwatcher.StatusInfo{Current: status.Unset}
if orig.Status.Current != status.Unset {
applicationStatus = orig.Status
}
return ¶ms.ApplicationInfo{
ModelUUID: orig.ModelUUID,
Name: orig.Name,
Exposed: orig.Exposed,
CharmURL: orig.CharmURL,
OwnerTag: orig.OwnerTag,
Life: orig.Life,
MinUnits: orig.MinUnits,
Constraints: orig.Constraints,
Config: orig.Config,
Subordinate: orig.Subordinate,
Status: aw.translateStatus(applicationStatus),
WorkloadVersion: orig.WorkloadVersion,
}
}
func (aw *SrvAllWatcher) translateMachine(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.MachineInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.MachineInfo{
ModelUUID: orig.ModelUUID,
Id: orig.ID,
InstanceId: orig.InstanceID,
AgentStatus: aw.translateStatus(orig.AgentStatus),
InstanceStatus: aw.translateStatus(orig.InstanceStatus),
Life: orig.Life,
Config: orig.Config,
Series: orig.Series,
ContainerType: orig.ContainerType,
IsManual: orig.IsManual,
SupportedContainers: orig.SupportedContainers,
SupportedContainersKnown: orig.SupportedContainersKnown,
HardwareCharacteristics: orig.HardwareCharacteristics,
CharmProfiles: orig.CharmProfiles,
Jobs: orig.Jobs,
Addresses: aw.translateAddresses(orig.Addresses),
HasVote: orig.HasVote,
WantsVote: orig.WantsVote,
Hostname: orig.Hostname,
}
}
func (aw *SrvAllWatcher) translateAddresses(addresses []network.ProviderAddress) []params.Address {
if addresses == nil {
return nil
}
result := make([]params.Address, 0, len(addresses))
for _, address := range addresses {
result = append(result, params.Address{
Value: address.Value,
Type: string(address.Type),
Scope: string(address.Scope),
SpaceName: string(address.SpaceName),
ProviderSpaceID: string(address.ProviderSpaceID),
})
}
return result
}
func (aw *SrvAllWatcher) translateCharm(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.CharmInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.CharmInfo{
ModelUUID: orig.ModelUUID,
CharmURL: orig.CharmURL,
CharmVersion: orig.CharmVersion,
Life: orig.Life,
LXDProfile: aw.translateProfile(orig.LXDProfile),
DefaultConfig: orig.DefaultConfig,
}
}
func (aw *SrvAllWatcher) translateProfile(profile *multiwatcher.Profile) *params.Profile {
if profile == nil {
return nil
}
return ¶ms.Profile{
Config: profile.Config,
Description: profile.Description,
Devices: profile.Devices,
}
}
func (aw *SrvAllWatcher) translateRemoteApplication(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.RemoteApplicationUpdate)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.RemoteApplicationUpdate{
ModelUUID: orig.ModelUUID,
Name: orig.Name,
OfferUUID: orig.OfferUUID,
OfferURL: orig.OfferURL,
Life: orig.Life,
Status: aw.translateStatus(orig.Status),
}
}
func (aw *SrvAllWatcher) translateApplicationOffer(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.ApplicationOfferInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.ApplicationOfferInfo{
ModelUUID: orig.ModelUUID,
OfferName: orig.OfferName,
OfferUUID: orig.OfferUUID,
ApplicationName: orig.ApplicationName,
CharmName: orig.CharmName,
TotalConnectedCount: orig.TotalConnectedCount,
ActiveConnectedCount: orig.ActiveConnectedCount,
}
}
func (aw *SrvAllWatcher) translateUnit(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.UnitInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
translatedPortRanges := aw.translatePortRanges(orig.OpenPortRangesByEndpoint)
return ¶ms.UnitInfo{
ModelUUID: orig.ModelUUID,
Name: orig.Name,
Application: orig.Application,
Series: orig.Series,
CharmURL: orig.CharmURL,
Life: orig.Life,
PublicAddress: orig.PublicAddress,
PrivateAddress: orig.PrivateAddress,
MachineId: orig.MachineID,
Ports: aw.mapRangesIntoPorts(translatedPortRanges),
PortRanges: translatedPortRanges,
Principal: orig.Principal,
Subordinate: orig.Subordinate,
WorkloadStatus: aw.translateStatus(orig.WorkloadStatus),
AgentStatus: aw.translateStatus(orig.AgentStatus),
}
}
func (aw *SrvAllWatcher) mapRangesIntoPorts(portRanges []params.PortRange) []params.Port {
if portRanges == nil {
return nil
}
result := make([]params.Port, 0, len(portRanges))
for _, pr := range portRanges {
for portNum := pr.FromPort; portNum <= pr.ToPort; portNum++ {
result = append(result, params.Port{
Protocol: pr.Protocol,
Number: portNum,
})
}
}
return result
}
// translatePortRanges flattens a set of port ranges grouped by endpoint into
// a list of unique port ranges. This method ignores subnet IDs and is provided
// for backwards compatibility with pre 2.9 clients that assume that open-ports
// applies to all subnets.
func (aw *SrvAllWatcher) translatePortRanges(portsByEndpoint network.GroupedPortRanges) []params.PortRange {
if portsByEndpoint == nil {
return nil
}
uniquePortRanges := portsByEndpoint.UniquePortRanges()
network.SortPortRanges(uniquePortRanges)
result := make([]params.PortRange, len(uniquePortRanges))
for i, pr := range uniquePortRanges {
result[i] = params.FromNetworkPortRange(pr)
}
return result
}
func (aw *SrvAllWatcher) translateAction(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.ActionInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.ActionInfo{
ModelUUID: orig.ModelUUID,
Id: orig.ID,
Receiver: orig.Receiver,
Name: orig.Name,
Parameters: orig.Parameters,
Status: orig.Status,
Message: orig.Message,
Results: orig.Results,
Enqueued: orig.Enqueued,
Started: orig.Started,
Completed: orig.Completed,
}
}
func (aw *SrvAllWatcher) translateRelation(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.RelationInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.RelationInfo{
ModelUUID: orig.ModelUUID,
Key: orig.Key,
Id: orig.ID,
Endpoints: aw.translateEndpoints(orig.Endpoints),
}
}
func (aw *SrvAllWatcher) translateEndpoints(eps []multiwatcher.Endpoint) []params.Endpoint {
if eps == nil {
return nil
}
result := make([]params.Endpoint, 0, len(eps))
for _, ep := range eps {
result = append(result, params.Endpoint{
ApplicationName: ep.ApplicationName,
Relation: params.CharmRelation{
Name: ep.Relation.Name,
Role: ep.Relation.Role,
Interface: ep.Relation.Interface,
Optional: ep.Relation.Optional,
Limit: ep.Relation.Limit,
Scope: ep.Relation.Scope,
},
})
}
return result
}
func (aw *SrvAllWatcher) translateAnnotation(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.AnnotationInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.AnnotationInfo{
ModelUUID: orig.ModelUUID,
Tag: orig.Tag,
Annotations: orig.Annotations,
}
}
func (aw *SrvAllWatcher) translateBlock(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.BlockInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.BlockInfo{
ModelUUID: orig.ModelUUID,
Id: orig.ID,
Type: orig.Type,
Message: orig.Message,
Tag: orig.Tag,
}
}
func (aw *SrvAllWatcher) translateBranch(info multiwatcher.EntityInfo) params.EntityInfo {
orig, ok := info.(*multiwatcher.BranchInfo)
if !ok {
logger.Criticalf("consistency error: %s", pretty.Sprint(info))
return nil
}
return ¶ms.BranchInfo{
ModelUUID: orig.ModelUUID,
Id: orig.ID,
Name: orig.Name,
AssignedUnits: orig.AssignedUnits,
Config: aw.translateBranchConfig(orig.Config),
Created: orig.Created,
CreatedBy: orig.CreatedBy,
Completed: orig.Completed,
CompletedBy: orig.CompletedBy,
GenerationId: orig.GenerationID,
}
}
func (aw *SrvAllWatcher) translateBranchConfig(config map[string][]multiwatcher.ItemChange) map[string][]params.ItemChange {
if config == nil {
return nil
}
result := make(map[string][]params.ItemChange)
for key, value := range config {
if value == nil {
result[key] = nil
} else {
changes := make([]params.ItemChange, 0, len(value))
for _, change := range value {
changes = append(changes, params.ItemChange{
Type: change.Type,
Key: change.Key,
OldValue: change.OldValue,
NewValue: change.NewValue,
})
}
result[key] = changes
}
}
return result
}
func isAgent(auth facade.Authorizer) bool {
return auth.AuthMachineAgent() || auth.AuthUnitAgent() || auth.AuthApplicationAgent() || auth.AuthModelAgent()
}
func isAgentOrUser(auth facade.Authorizer) bool {
return isAgent(auth) || auth.AuthClient()
}
func newNotifyWatcher(context facade.Context) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
// TODO(wallyworld) - enhance this watcher to support
// anonymous api calls with macaroons.
if auth.GetAuthTag() != nil && !isAgentOrUser(auth) {
return nil, apiservererrors.ErrPerm
}
watcher, ok := resources.Get(id).(cache.NotifyWatcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher
}
return &srvNotifyWatcher{
watcherCommon: newWatcherCommon(context),
watcher: watcher,
}, nil
}
// srvNotifyWatcher defines the API access to methods on a NotifyWatcher.
// Each client has its own current set of watchers, stored in resources.
type srvNotifyWatcher struct {
watcherCommon
watcher cache.NotifyWatcher
}
// state watchers have an Err method, but cache watchers do not.
type hasErr interface {
Err() error
}
// Next returns when a change has occurred to the
// entity being watched since the most recent call to Next
// or the Watch call that created the NotifyWatcher.
func (w *srvNotifyWatcher) Next() error {
if _, ok := <-w.watcher.Changes(); ok {
return nil
}
var err error
if e, ok := w.watcher.(hasErr); ok {
err = e.Err()
}
if err == nil {
err = apiservererrors.ErrStoppedWatcher
}
return err
}
// srvStringsWatcher defines the API for methods on a state.StringsWatcher.
// Each client has its own current set of watchers, stored in resources.
// srvStringsWatcher notifies about changes for all entities of a given kind,
// sending the changes as a list of strings.
type srvStringsWatcher struct {
watcherCommon
watcher cache.StringsWatcher
}
func newStringsWatcher(context facade.Context) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
// TODO(wallyworld) - enhance this watcher to support
// anonymous api calls with macaroons.
if auth.GetAuthTag() != nil && !isAgentOrUser(auth) {
return nil, apiservererrors.ErrPerm
}
watcher, ok := resources.Get(id).(cache.StringsWatcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher
}
return &srvStringsWatcher{
watcherCommon: newWatcherCommon(context),
watcher: watcher,
}, nil
}
// Next returns when a change has occurred to an entity of the
// collection being watched since the most recent call to Next
// or the Watch call that created the srvStringsWatcher.
func (w *srvStringsWatcher) Next() (params.StringsWatchResult, error) {
if changes, ok := <-w.watcher.Changes(); ok {
return params.StringsWatchResult{
Changes: changes,
}, nil
}
var err error
if e, ok := w.watcher.(hasErr); ok {
err = e.Err()
}
if err == nil {
err = apiservererrors.ErrStoppedWatcher
}
return params.StringsWatchResult{}, err
}
// srvRelationUnitsWatcher defines the API wrapping a state.RelationUnitsWatcher.
// It notifies about units entering and leaving the scope of a RelationUnit,
// and changes to the settings of those units known to have entered.
type srvRelationUnitsWatcher struct {
watcherCommon
watcher common.RelationUnitsWatcher
}
func newRelationUnitsWatcher(context facade.Context) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
// TODO(wallyworld) - enhance this watcher to support
// anonymous api calls with macaroons.
if auth.GetAuthTag() != nil && !isAgent(auth) {
return nil, apiservererrors.ErrPerm
}
watcher, ok := resources.Get(id).(common.RelationUnitsWatcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher
}
return &srvRelationUnitsWatcher{
watcherCommon: newWatcherCommon(context),
watcher: watcher,
}, nil
}
// Next returns when a change has occurred to an entity of the
// collection being watched since the most recent call to Next
// or the Watch call that created the srvRelationUnitsWatcher.
func (w *srvRelationUnitsWatcher) Next() (params.RelationUnitsWatchResult, error) {
if changes, ok := <-w.watcher.Changes(); ok {
return params.RelationUnitsWatchResult{
Changes: changes,
}, nil
}
err := w.watcher.Err()
if err == nil {
err = apiservererrors.ErrStoppedWatcher
}
return params.RelationUnitsWatchResult{}, err
}
// srvRemoteRelationWatcher defines the API wrapping a
// state.RelationUnitsWatcher but serving the events it emits as
// fully-expanded params.RemoteRelationChangeEvents so they can be
// used across model/controller boundaries.
type srvRemoteRelationWatcher struct {
watcherCommon
backend crossmodel.Backend
watcher *crossmodel.WrappedUnitsWatcher
}
func newRemoteRelationWatcher(context facade.Context) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
// TODO(wallyworld) - enhance this watcher to support
// anonymous api calls with macaroons.
if auth.GetAuthTag() != nil && !isAgent(auth) {
return nil, apiservererrors.ErrPerm
}
watcher, ok := resources.Get(id).(*crossmodel.WrappedUnitsWatcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher
}
return &srvRemoteRelationWatcher{
watcherCommon: newWatcherCommon(context),
backend: crossmodel.GetBackend(context.State()),
watcher: watcher,
}, nil
}
func (w *srvRemoteRelationWatcher) Next() (params.RemoteRelationWatchResult, error) {
if change, ok := <-w.watcher.Changes(); ok {
// Expand the change into a cross-model event.
expanded, err := crossmodel.ExpandChange(
w.backend,
w.watcher.RelationToken,
w.watcher.ApplicationToken,
change,
)
if err != nil {
return params.RemoteRelationWatchResult{
Error: apiservererrors.ServerError(err),
}, nil
}
return params.RemoteRelationWatchResult{
Changes: expanded,
}, nil
}
err := w.watcher.Err()
if err == nil {
err = apiservererrors.ErrStoppedWatcher
}
return params.RemoteRelationWatchResult{}, err
}
// srvRelationStatusWatcher defines the API wrapping a state.RelationStatusWatcher.
type srvRelationStatusWatcher struct {
watcherCommon
st *state.State
watcher state.StringsWatcher
}
func newRelationStatusWatcher(context facade.Context) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
// TODO(wallyworld) - enhance this watcher to support
// anonymous api calls with macaroons.
if auth.GetAuthTag() != nil && !isAgent(auth) {
return nil, apiservererrors.ErrPerm
}
watcher, ok := resources.Get(id).(state.StringsWatcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher
}
return &srvRelationStatusWatcher{
watcherCommon: newWatcherCommon(context),
st: context.State(),
watcher: watcher,
}, nil
}
// Next returns when a change has occurred to an entity of the
// collection being watched since the most recent call to Next
// or the Watch call that created the srvRelationStatusWatcher.
func (w *srvRelationStatusWatcher) Next() (params.RelationLifeSuspendedStatusWatchResult, error) {
if changes, ok := <-w.watcher.Changes(); ok {
changesParams := make([]params.RelationLifeSuspendedStatusChange, len(changes))
for i, key := range changes {
change, err := crossmodel.GetRelationLifeSuspendedStatusChange(crossmodel.GetBackend(w.st), key)
if err != nil {
return params.RelationLifeSuspendedStatusWatchResult{
Error: apiservererrors.ServerError(err),
}, nil
}
changesParams[i] = *change
}
return params.RelationLifeSuspendedStatusWatchResult{
Changes: changesParams,
}, nil
}
err := w.watcher.Err()
if err == nil {
err = apiservererrors.ErrStoppedWatcher
}
return params.RelationLifeSuspendedStatusWatchResult{}, err
}
// srvOfferStatusWatcher defines the API wrapping a crossmodelrelations.OfferStatusWatcher.
type srvOfferStatusWatcher struct {
watcherCommon
st *state.State
model *cache.Model
watcher crossmodelrelations.OfferWatcher
}
func newOfferStatusWatcher(context facade.Context) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
st := context.State()
model, err := context.CachedModel(st.ModelUUID())
if err != nil {
return watcherCommon{}, err
}
// TODO(wallyworld) - enhance this watcher to support
// anonymous api calls with macaroons.
if auth.GetAuthTag() != nil && !isAgent(auth) {
return nil, apiservererrors.ErrPerm
}
watcher, ok := resources.Get(id).(crossmodelrelations.OfferWatcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher
}
return &srvOfferStatusWatcher{
watcherCommon: newWatcherCommon(context),
st: st,
model: model,
watcher: watcher,
}, nil
}
// Next returns when a change has occurred to an entity of the
// collection being watched since the most recent call to Next
// or the Watch call that created the srvOfferStatusWatcher.
func (w *srvOfferStatusWatcher) Next() (params.OfferStatusWatchResult, error) {
if _, ok := <-w.watcher.Changes(); ok {
shim := crossmodel.CacheShim{w.model}
change, err := crossmodel.GetOfferStatusChange(
shim, crossmodel.GetBackend(w.st),
w.watcher.OfferUUID(), w.watcher.OfferName())
if err != nil {
return params.OfferStatusWatchResult{
Error: apiservererrors.ServerError(err),
}, nil
}
return params.OfferStatusWatchResult{
Changes: []params.OfferStatusChange{*change},
}, nil
}
err := w.watcher.Err()
if err == nil {
err = apiservererrors.ErrStoppedWatcher
}
return params.OfferStatusWatchResult{}, err
}
// srvMachineStorageIdsWatcher defines the API wrapping a state.StringsWatcher
// watching machine/storage attachments. This watcher notifies about storage
// entities (volumes/filesystems) being attached to and detached from machines.
//
// TODO(axw) state needs a new watcher, this is a bt of a hack. State watchers
// could do with some deduplication of logic, and I don't want to add to that
// spaghetti right now.
type srvMachineStorageIdsWatcher struct {
watcherCommon
watcher state.StringsWatcher
parser func([]string) ([]params.MachineStorageId, error)
}
func newVolumeAttachmentsWatcher(context facade.Context) (facade.Facade, error) {
return newMachineStorageIdsWatcher(
context,
storagecommon.ParseVolumeAttachmentIds,
)
}
func newVolumeAttachmentPlansWatcher(context facade.Context) (facade.Facade, error) {
return newMachineStorageIdsWatcher(
context,
storagecommon.ParseVolumeAttachmentIds,
)
}
func newFilesystemAttachmentsWatcher(context facade.Context) (facade.Facade, error) {
return newMachineStorageIdsWatcher(
context,
storagecommon.ParseFilesystemAttachmentIds,
)
}
func newMachineStorageIdsWatcher(
context facade.Context,
parser func([]string) ([]params.MachineStorageId, error),
) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
if !isAgent(auth) {
return nil, apiservererrors.ErrPerm
}
watcher, ok := resources.Get(id).(state.StringsWatcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher
}
return &srvMachineStorageIdsWatcher{
watcherCommon: newWatcherCommon(context),
watcher: watcher,
parser: parser,
}, nil
}
// Next returns when a change has occurred to an entity of the
// collection being watched since the most recent call to Next
// or the Watch call that created the srvMachineStorageIdsWatcher.
func (w *srvMachineStorageIdsWatcher) Next() (params.MachineStorageIdsWatchResult, error) {
if stringChanges, ok := <-w.watcher.Changes(); ok {
changes, err := w.parser(stringChanges)
if err != nil {
return params.MachineStorageIdsWatchResult{}, err
}
return params.MachineStorageIdsWatchResult{
Changes: changes,
}, nil
}
err := w.watcher.Err()
if err == nil {
err = apiservererrors.ErrStoppedWatcher
}
return params.MachineStorageIdsWatchResult{}, err
}
// EntitiesWatcher defines an interface based on the StringsWatcher
// but also providing a method for the mapping of the received
// strings to the tags of the according entities.
type EntitiesWatcher interface {
state.StringsWatcher
// MapChanges maps the received strings to their according tag strings.
// The EntityFinder interface representing state or a mock has to be
// upcasted into the needed sub-interface of state for the real mapping.
MapChanges(in []string) ([]string, error)
}
// srvEntitiesWatcher defines the API for methods on a state.StringsWatcher.
// Each client has its own current set of watchers, stored in resources.
// srvEntitiesWatcher notifies about changes for all entities of a given kind,
// sending the changes as a list of strings, which could be transformed
// from state entity ids to their corresponding entity tags.
type srvEntitiesWatcher struct {
watcherCommon
watcher EntitiesWatcher
}
func newEntitiesWatcher(context facade.Context) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
if !isAgent(auth) {
return nil, apiservererrors.ErrPerm
}
watcher, ok := resources.Get(id).(EntitiesWatcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher
}
return &srvEntitiesWatcher{
watcherCommon: newWatcherCommon(context),
watcher: watcher,
}, nil
}
// Next returns when a change has occurred to an entity of the
// collection being watched since the most recent call to Next
// or the Watch call that created the srvEntitiesWatcher.
func (w *srvEntitiesWatcher) Next() (params.EntitiesWatchResult, error) {
if changes, ok := <-w.watcher.Changes(); ok {
mapped, err := w.watcher.MapChanges(changes)
if err != nil {
return params.EntitiesWatchResult{}, errors.Annotate(err, "cannot map changes")
}
return params.EntitiesWatchResult{
Changes: mapped,
}, nil
}
err := w.watcher.Err()
if err == nil {
err = apiservererrors.ErrStoppedWatcher
}
return params.EntitiesWatchResult{}, err
}
var getMigrationBackend = func(st *state.State) migrationBackend {
return st
}
var getControllerBackend = func(pool *state.StatePool) controllerBackend {
return pool.SystemState()
}
// migrationBackend defines model State functionality required by the
// migration watchers.
type migrationBackend interface {
LatestMigration() (state.ModelMigration, error)
}
// migrationBackend defines controller State functionality required by the
// migration watchers.
type controllerBackend interface {
APIHostPortsForClients() ([]network.SpaceHostPorts, error)
ControllerConfig() (controller.Config, error)
}
func newMigrationStatusWatcher(context facade.Context) (facade.Facade, error) {
id := context.ID()
auth := context.Auth()
resources := context.Resources()
st := context.State()
pool := context.StatePool()
if !isAgent(auth) {
return nil, apiservererrors.ErrPerm
}
w, ok := resources.Get(id).(state.NotifyWatcher)
if !ok {
return nil, apiservererrors.ErrUnknownWatcher