-
Notifications
You must be signed in to change notification settings - Fork 24
/
rate-limiter.go
187 lines (164 loc) · 6.52 KB
/
rate-limiter.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
package ratelimiter
import (
"context"
"path"
clientv3 "go.etcd.io/etcd/client/v3"
"go.uber.org/fx"
"go.uber.org/multierr"
"google.golang.org/protobuf/proto"
policylangv1 "github.com/fluxninja/aperture/v2/api/gen/proto/go/aperture/policy/language/v1"
policysyncv1 "github.com/fluxninja/aperture/v2/api/gen/proto/go/aperture/policy/sync/v1"
"github.com/fluxninja/aperture/v2/pkg/config"
etcdclient "github.com/fluxninja/aperture/v2/pkg/etcd/client"
etcdwriter "github.com/fluxninja/aperture/v2/pkg/etcd/writer"
"github.com/fluxninja/aperture/v2/pkg/notifiers"
"github.com/fluxninja/aperture/v2/pkg/policies/controlplane/iface"
"github.com/fluxninja/aperture/v2/pkg/policies/controlplane/runtime"
"github.com/fluxninja/aperture/v2/pkg/policies/controlplane/runtime/tristate"
"github.com/fluxninja/aperture/v2/pkg/policies/flowcontrol/selectors"
"github.com/fluxninja/aperture/v2/pkg/policies/paths"
)
type rateLimiterSync struct {
policyReadAPI iface.Policy
rateLimiterProto *policylangv1.RateLimiter
decision *policysyncv1.RateLimiterDecision
decisionWriter *etcdwriter.Writer
componentID string
configEtcdPaths []string
decisionEtcdPaths []string
}
// Name implements runtime.Component.
func (*rateLimiterSync) Name() string { return "RateLimiter" }
// Type implements runtime.Component.
func (*rateLimiterSync) Type() runtime.ComponentType { return runtime.ComponentTypeSink }
// ShortDescription implements runtime.Component.
func (limiterSync *rateLimiterSync) ShortDescription() string {
return iface.GetSelectorsShortDescription(limiterSync.rateLimiterProto.GetSelectors())
}
// IsActuator implements runtime.Component.
func (*rateLimiterSync) IsActuator() bool { return true }
// NewRateLimiterAndOptions creates fx options for RateLimiter.
func NewRateLimiterAndOptions(
rateLimiterProto *policylangv1.RateLimiter,
componentID runtime.ComponentID,
policyReadAPI iface.Policy,
) (runtime.Component, fx.Option, error) {
s := rateLimiterProto.GetSelectors()
agentGroups := selectors.UniqueAgentGroups(s)
var configEtcdPaths, decisionEtcdPaths []string
for _, agentGroup := range agentGroups {
etcdKey := paths.AgentComponentKey(agentGroup, policyReadAPI.GetPolicyName(), componentID.String())
configEtcdPath := path.Join(paths.RateLimiterConfigPath, etcdKey)
configEtcdPaths = append(configEtcdPaths, configEtcdPath)
decisionEtcdPath := path.Join(paths.RateLimiterDecisionsPath, etcdKey)
decisionEtcdPaths = append(decisionEtcdPaths, decisionEtcdPath)
}
limiterSync := &rateLimiterSync{
rateLimiterProto: rateLimiterProto,
decision: &policysyncv1.RateLimiterDecision{},
policyReadAPI: policyReadAPI,
configEtcdPaths: configEtcdPaths,
decisionEtcdPaths: decisionEtcdPaths,
componentID: componentID.String(),
}
return limiterSync, fx.Options(
fx.Invoke(
limiterSync.setupSync,
),
), nil
}
func (limiterSync *rateLimiterSync) setupSync(scopedKV *etcdclient.SessionScopedKV, lifecycle fx.Lifecycle) {
logger := limiterSync.policyReadAPI.GetStatusRegistry().GetLogger()
lifecycle.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
wrapper := &policysyncv1.RateLimiterWrapper{
RateLimiter: limiterSync.rateLimiterProto,
CommonAttributes: &policysyncv1.CommonAttributes{
PolicyName: limiterSync.policyReadAPI.GetPolicyName(),
PolicyHash: limiterSync.policyReadAPI.GetPolicyHash(),
ComponentId: limiterSync.componentID,
},
}
dat, err := proto.Marshal(wrapper)
if err != nil {
logger.Error().Err(err).Msg("failed to marshal rate limiter config")
return err
}
var merr error
for _, configEtcdPath := range limiterSync.configEtcdPaths {
_, err = scopedKV.Put(clientv3.WithRequireLeader(ctx), configEtcdPath, string(dat))
if err != nil {
logger.Error().Err(err).Msg("failed to put rate limiter config")
merr = multierr.Append(merr, err)
}
}
limiterSync.decisionWriter = etcdwriter.NewWriter(&scopedKV.KVWrapper)
return merr
},
OnStop: func(ctx context.Context) error {
limiterSync.decisionWriter.Close()
deleteEtcdPath := func(paths []string) error {
var merr error
for _, path := range paths {
_, err := scopedKV.Delete(clientv3.WithRequireLeader(ctx), path)
if err != nil {
logger.Error().Err(err).Msgf("failed to delete etcd path %s", path)
merr = multierr.Append(merr, err)
}
}
return merr
}
merr := deleteEtcdPath(limiterSync.configEtcdPaths)
merr = multierr.Append(merr, deleteEtcdPath(limiterSync.decisionEtcdPaths))
return merr
},
})
}
// Execute implements runtime.Component.Execute.
func (limiterSync *rateLimiterSync) Execute(inPortReadings runtime.PortToReading, circuitAPI runtime.CircuitAPI) (runtime.PortToReading, error) {
bucketCapacity := inPortReadings.ReadSingleReadingPort("bucket_capacity")
fillAmount := inPortReadings.ReadSingleReadingPort("fill_amount")
ptBool := tristate.FromReading(inPortReadings.ReadSingleReadingPort("pass_through"))
decision := &policysyncv1.RateLimiterDecision{
PassThrough: true,
}
if !bucketCapacity.Valid() || !fillAmount.Valid() {
return nil, limiterSync.publishDecision(decision)
}
decision.BucketCapacity = bucketCapacity.Value()
decision.FillAmount = fillAmount.Value()
decision.PassThrough = ptBool.IsTrue()
return nil, limiterSync.publishDecision(decision)
}
func (limiterSync *rateLimiterSync) publishDecision(decision *policysyncv1.RateLimiterDecision) error {
logger := limiterSync.policyReadAPI.GetStatusRegistry().GetLogger()
// Publish only if there's a change
if !proto.Equal(limiterSync.decision, decision) {
limiterSync.decision = decision
// Publish decision
logger.Debug().Msg("publishing rate limiter decision")
wrapper := &policysyncv1.RateLimiterDecisionWrapper{
RateLimiterDecision: decision,
CommonAttributes: &policysyncv1.CommonAttributes{
PolicyName: limiterSync.policyReadAPI.GetPolicyName(),
PolicyHash: limiterSync.policyReadAPI.GetPolicyHash(),
ComponentId: limiterSync.componentID,
},
}
dat, err := proto.Marshal(wrapper)
if err != nil {
logger.Error().Err(err).Msg("failed to marshal rate limiter decision")
return err
}
if limiterSync.decisionWriter == nil {
logger.Panic().Msg("decision writer is nil")
}
for _, decisionEtcdPath := range limiterSync.decisionEtcdPaths {
limiterSync.decisionWriter.Write(decisionEtcdPath, dat)
}
}
return nil
}
// DynamicConfigUpdate is a no-op for rate limiter.
func (limiterSync *rateLimiterSync) DynamicConfigUpdate(event notifiers.Event, unmarshaller config.Unmarshaller) {
}