generated from xmidt-org/.go-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
manager.go
212 lines (182 loc) · 5.45 KB
/
manager.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
// Copyright 2021 Comcast Cable Communications Management, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package quota
import (
"context"
"errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/xmidt-org/ears/internal/pkg/config"
"github.com/xmidt-org/ears/internal/pkg/syncer"
"github.com/xmidt-org/ears/pkg/tenant"
"sync"
"time"
)
type QuotaManager struct {
limiters map[string]*QuotaLimiter
tenantStorer tenant.TenantStorer
syncer syncer.DeltaSyncer
lock *sync.Mutex
backendLimiterType string
redisAddr string
logger *zerolog.Logger
ticker *time.Ticker
done context.CancelFunc
ctx context.Context
}
const LimiterTypeNone = "none"
const LimiterTypeRedis = "redis"
const LimiterTypeInMemory = "inmemory"
func validateLimiterType(limiterType string) bool {
return limiterType == LimiterTypeNone ||
limiterType == LimiterTypeRedis ||
limiterType == LimiterTypeInMemory
}
func NewQuotaManager(logger *zerolog.Logger, tenantStorer tenant.TenantStorer, syncer syncer.DeltaSyncer, config config.Config) (*QuotaManager, error) {
backendLimiterType := config.GetString("ears.ratelimiter.type")
if !validateLimiterType(backendLimiterType) {
return nil, &BadConfigError{"ears.ratelimiter.type", backendLimiterType}
}
redisAddr := ""
if backendLimiterType == LimiterTypeRedis {
redisAddr = config.GetString("ears.ratelimiter.endpoint")
if redisAddr == "" {
return nil, &ConfigNotFoundError{"ears.ratelimiter.endpoint"}
}
}
return &QuotaManager{
limiters: make(map[string]*QuotaLimiter),
tenantStorer: tenantStorer,
syncer: syncer,
lock: &sync.Mutex{},
backendLimiterType: backendLimiterType,
redisAddr: redisAddr,
logger: logger,
}, nil
}
func (m *QuotaManager) Start() {
m.syncer.RegisterLocalSyncer("tenant", m)
//Start backup quota syncer that wakes up every minute to sync on tenant quota
ticker := time.NewTicker(time.Minute)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
m.done = cancel
m.ctx = ctx
m.ticker = ticker
go func() {
for {
m.logger.Info().Str("op", "PeriodicQuotaSync").Msg("sync tenant quotas")
select {
case <-m.ctx.Done():
return
case <-m.ticker.C:
m.syncAllItems()
}
}
}()
}
func (m *QuotaManager) Stop() {
m.syncer.UnregisterLocalSyncer("tenant", m)
if m.ticker != nil {
m.ticker.Stop()
m.done()
}
}
// Wait until rate limiter allows it to go through or context cancellation
func (m *QuotaManager) Wait(ctx context.Context, tid tenant.Id) error {
limiter, err := m.getLimiter(ctx, tid)
if limiter == nil || err != nil {
return nil
}
return limiter.Wait(ctx)
}
func (m *QuotaManager) TenantLimit(ctx context.Context, tid tenant.Id) int {
limiter, err := m.getLimiter(ctx, tid)
if err != nil {
return 0
}
return limiter.Limit()
}
func (m *QuotaManager) SyncItem(ctx context.Context, tid tenant.Id, itemId string, add bool) error {
limiter, err := m.getLimiter(ctx, tid)
if limiter == nil {
return nil
}
if err != nil {
return err
}
config, err := m.tenantStorer.GetConfig(ctx, tid)
tenantRqs := 0
if err != nil {
var tenantNotFound *tenant.TenantNotFoundError
if !errors.As(err, &tenantNotFound) {
return err
}
} else {
tenantRqs = config.Quota.EventsPerSec
}
return limiter.SetLimit(tenantRqs)
}
//PublishQuota publishes tenant quota to ratelimiters in all nodes so they can sync to the new quota
func (m *QuotaManager) PublishQuota(ctx context.Context, tid tenant.Id) error {
err := m.SyncItem(ctx, tid, "ignored", true)
if err != nil {
log.Ctx(ctx).Error().Str("op", "PublishQuota").Str("action", "SyncItem").Str("error", err.Error()).Msg("Error syncing local quota")
}
m.syncer.PublishSyncRequest(ctx, tid, syncer.ITEM_TYPE_TENANT, "ignored", true)
return nil
}
func (m *QuotaManager) getLimiter(ctx context.Context, tid tenant.Id) (*QuotaLimiter, error) {
m.lock.Lock()
defer m.lock.Unlock()
if m.backendLimiterType == LimiterTypeNone {
return nil, nil
}
limiter, ok := m.limiters[tid.Key()]
if ok {
return limiter, nil
}
config, err := m.tenantStorer.GetConfig(ctx, tid)
tenantRqs := 0
if err != nil {
var tenantNotFound *tenant.TenantNotFoundError
if !errors.As(err, &tenantNotFound) {
return nil, err
}
} else {
tenantRqs = config.Quota.EventsPerSec
}
instanceCount := m.syncer.GetInstanceCount(ctx)
if instanceCount == 0 {
return nil, &NoEarsInstances{}
}
initialRqs := tenantRqs / instanceCount
limiter = NewQuotaLimiter(tid, m.backendLimiterType, m.redisAddr, initialRqs, tenantRqs)
m.limiters[tid.Key()] = limiter
return limiter, nil
}
func (m *QuotaManager) syncAllItems() {
//make a copy of quota limiters
m.lock.Lock()
limiters := make([]*QuotaLimiter, len(m.limiters))
i := 0
for _, limiter := range m.limiters {
limiters[i] = limiter
i++
}
m.lock.Unlock()
for _, limiter := range limiters {
m.SyncItem(m.ctx, limiter.tid, "ignored", true)
}
}