This repository has been archived by the owner on Feb 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.go
378 lines (324 loc) · 10.8 KB
/
route.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
package main
import (
"bytes"
"fmt"
"sync"
"sync/atomic"
)
type RouteConfig interface {
Matcher() *Matcher
Dests() []*Destination
}
type baseRouteConfig struct {
matcher Matcher
dests []*Destination
}
func (c baseRouteConfig) Matcher() *Matcher {
return &c.matcher
}
func (c baseRouteConfig) Dests() []*Destination {
return c.dests
}
type consistentHashingRouteConfig struct {
baseRouteConfig
Hasher *ConsistentHasher
}
type Route interface {
Dispatch(buf []byte)
Match(s []byte) bool
Snapshot() RouteSnapshot
Key() string
Flush() error
Shutdown() error
DelDestination(index int) error
UpdateDestination(index int, opts map[string]string) error
Update(opts map[string]string) error
}
type RouteSnapshot struct {
Matcher Matcher `json:"matcher"`
Dests []*Destination `json:"destination"`
Type string `json:"type"`
Key string `json:"key"`
}
type baseRoute struct {
sync.Mutex // only needed for the multiple writers
config atomic.Value // for reading and writing
key string
}
type RouteSendAllMatch struct {
baseRoute
}
type RouteSendFirstMatch struct {
baseRoute
}
type RouteConsistentHashing struct {
baseRoute
}
// NewRouteSendAllMatch creates a sendAllMatch route.
// We will automatically run the route and the given destinations
func NewRouteSendAllMatch(key, prefix, sub, regex string, destinations []*Destination) (Route, error) {
m, err := NewMatcher(prefix, sub, regex)
if err != nil {
return nil, err
}
r := &RouteSendAllMatch{baseRoute{sync.Mutex{}, atomic.Value{}, key}}
r.config.Store(baseRouteConfig{*m, destinations})
r.run()
return r, nil
}
// NewRouteSendFirstMatch creates a sendFirstMatch route.
// We will automatically run the route and the given destinations
func NewRouteSendFirstMatch(key, prefix, sub, regex string, destinations []*Destination) (Route, error) {
m, err := NewMatcher(prefix, sub, regex)
if err != nil {
return nil, err
}
r := &RouteSendFirstMatch{baseRoute{sync.Mutex{}, atomic.Value{}, key}}
r.config.Store(baseRouteConfig{*m, destinations})
r.run()
return r, nil
}
func NewRouteConsistentHashing(key, prefix, sub, regex string, destinations []*Destination) (Route, error) {
m, err := NewMatcher(prefix, sub, regex)
if err != nil {
return nil, err
}
r := &RouteConsistentHashing{baseRoute{sync.Mutex{}, atomic.Value{}, key}}
hasher := NewConsistentHasher(destinations)
r.config.Store(consistentHashingRouteConfig{baseRouteConfig{*m, destinations},
&hasher})
r.run()
return r, nil
}
func (route *baseRoute) run() {
conf := route.config.Load().(RouteConfig)
for _, dest := range conf.Dests() {
dest.Run()
}
}
func (route *RouteSendAllMatch) Dispatch(buf []byte) {
conf := route.config.Load().(RouteConfig)
for _, dest := range conf.Dests() {
if dest.Match(buf) {
// dest should handle this as quickly as it can
log.Info("route %s sending to dest %s: %s", route.key, dest.Addr, buf)
dest.in <- buf
}
}
}
func (route *RouteSendFirstMatch) Dispatch(buf []byte) {
conf := route.config.Load().(RouteConfig)
for _, dest := range conf.Dests() {
if dest.Match(buf) {
// dest should handle this as quickly as it can
log.Info("route %s sending to dest %s: %s", route.key, dest.Addr, buf)
dest.in <- buf
break
}
}
}
func (route *RouteConsistentHashing) Dispatch(buf []byte) {
conf := route.config.Load().(consistentHashingRouteConfig)
if pos := bytes.IndexByte(buf, ' '); pos > 0 {
name := buf[0:pos]
dest := conf.Dests()[conf.Hasher.GetDestinationIndex(name)]
// dest should handle this as quickly as it can
log.Info("route %s sending to dest %s: %s", route.key, dest.Addr, name)
dest.in <- buf
} else {
log.Error("could not parse %s\n", buf)
}
}
func (route *baseRoute) Key() string {
return route.key
}
func (route *baseRoute) Match(s []byte) bool {
conf := route.config.Load().(RouteConfig)
return conf.Matcher().Match(s)
}
func (route *baseRoute) Flush() error {
conf := route.config.Load().(RouteConfig)
for _, d := range conf.Dests() {
err := d.Flush()
if err != nil {
return err
}
}
return nil
}
func (route *baseRoute) Shutdown() error {
conf := route.config.Load().(RouteConfig)
destErrs := make([]error, 0)
for _, d := range conf.Dests() {
err := d.Shutdown()
if err != nil {
destErrs = append(destErrs, err)
}
}
if len(destErrs) == 0 {
return nil
}
errStr := ""
for _, e := range destErrs {
errStr += " " + e.Error()
}
return fmt.Errorf("one or more destinations failed to shutdown:" + errStr)
}
// to view the state of the table/route at any point in time
func makeSnapshot(route *baseRoute, routeType string) RouteSnapshot {
conf := route.config.Load().(RouteConfig)
dests := make([]*Destination, len(conf.Dests()))
for i, d := range conf.Dests() {
dests[i] = d.Snapshot()
}
return RouteSnapshot{*conf.Matcher(), dests, routeType, route.key}
}
func (route *RouteSendAllMatch) Snapshot() RouteSnapshot {
return makeSnapshot(&route.baseRoute, "sendAllMatch")
}
func (route *RouteSendFirstMatch) Snapshot() RouteSnapshot {
return makeSnapshot(&route.baseRoute, "sendFirstMatch")
}
func (route *RouteConsistentHashing) Snapshot() RouteSnapshot {
return makeSnapshot(&route.baseRoute, "consistentHashing")
}
// baseConfigExtender is a function that takes a baseRouteConfig and returns
// a configuration object that implements RouteConfig. This function may be
// the identity function, i.e., it may simply return its argument.
// This mechanism supports maintaining different configuration objects for
// different route types and creating a route-appropriate configuration object
// on a configuration change.
// The baseRoute object implements private methods (addDestination,
// delDestination, etc.) that create a new baseRouteConfig object that reflects
// the configuration change. This baseRouteConfig object is applicable to all
// route types. However, some route types, like ConsistentHashingRoute, have
// additional configuration and therefore have a distinct configuration object
// that embeds baseRouteConfig (in the case of ConsistentHashingRoute, the object
// is consistentHashingRouteConfig). This route-type-specific configuration also
// needs to be updated on a base configuration change (e.g., on a change
// affecting destinations). Accordingly, the public entry points that effect the
// configuration change (Add, DelDestination, etc.) are implemented for baseRoute
// and also for any route type, like ConsistentHashingRoute, that creates a
// configuration object. These public entry points call the private method,
// passing in a callback function of type baseConfigExtender, which takes a
// baseRouteConfig and either returns it unchanged or creates an outer
// configuration object with the baseRouteConfig embedded in it.
// The private method then stores the RouteConfig object returned by the callback.
type baseConfigExtender func(baseRouteConfig) RouteConfig
func baseRouteConfigExtender(baseConfig baseRouteConfig) RouteConfig {
return baseConfig
}
func consistentHashingRouteConfigExtender(baseConfig baseRouteConfig) RouteConfig {
hasher := NewConsistentHasher(baseConfig.Dests())
return consistentHashingRouteConfig{baseConfig, &hasher}
}
// Add adds a new Destination to the Route and automatically runs it for you.
// The destination must not be running already!
func (route *baseRoute) addDestination(dest *Destination, extendConfig baseConfigExtender) {
route.Lock()
defer route.Unlock()
conf := route.config.Load().(RouteConfig)
dest.Run()
newDests := append(conf.Dests(), dest)
newConf := extendConfig(baseRouteConfig{*conf.Matcher(), newDests})
route.config.Store(newConf)
}
func (route *baseRoute) Add(dest *Destination) {
route.addDestination(dest, baseRouteConfigExtender)
}
func (route *RouteConsistentHashing) Add(dest *Destination) {
route.addDestination(dest, consistentHashingRouteConfigExtender)
}
func (route *baseRoute) delDestination(index int, extendConfig baseConfigExtender) error {
route.Lock()
defer route.Unlock()
conf := route.config.Load().(RouteConfig)
if index >= len(conf.Dests()) {
return fmt.Errorf("Invalid index %d", index)
}
conf.Dests()[index].Shutdown()
newDests := append(conf.Dests()[:index], conf.Dests()[index+1:]...)
newConf := extendConfig(baseRouteConfig{*conf.Matcher(), newDests})
route.config.Store(newConf)
return nil
}
func (route *baseRoute) DelDestination(index int) error {
return route.delDestination(index, baseRouteConfigExtender)
}
func (route *RouteConsistentHashing) DelDestination(index int) error {
return route.delDestination(index, consistentHashingRouteConfigExtender)
}
func (route *baseRoute) update(opts map[string]string, extendConfig baseConfigExtender) error {
route.Lock()
defer route.Unlock()
conf := route.config.Load().(RouteConfig)
matcher := conf.Matcher()
prefix := matcher.Prefix
sub := matcher.Sub
regex := matcher.Regex
updateMatcher := false
for name, val := range opts {
switch name {
case "prefix":
prefix = val
updateMatcher = true
case "sub":
sub = val
updateMatcher = true
case "regex":
regex = val
updateMatcher = true
default:
return fmt.Errorf("no such option '%s'", name)
}
}
if updateMatcher {
matcher, err := NewMatcher(prefix, sub, regex)
if err != nil {
return err
}
conf = extendConfig(baseRouteConfig{*matcher, conf.Dests()})
}
route.config.Store(conf)
return nil
}
func (route *baseRoute) Update(opts map[string]string) error {
return route.update(opts, baseRouteConfigExtender)
}
func (route *RouteConsistentHashing) Update(opts map[string]string) error {
return route.update(opts, consistentHashingRouteConfigExtender)
}
func (route *baseRoute) updateDestination(index int, opts map[string]string, extendConfig baseConfigExtender) error {
route.Lock()
defer route.Unlock()
conf := route.config.Load().(RouteConfig)
if index >= len(conf.Dests()) {
return fmt.Errorf("Invalid index %d", index)
}
err := conf.Dests()[index].Update(opts)
if err != nil {
return err
}
conf = extendConfig(baseRouteConfig{*conf.Matcher(), conf.Dests()})
route.config.Store(conf)
return nil
}
func (route *baseRoute) UpdateDestination(index int, opts map[string]string) error {
return route.updateDestination(index, opts, baseRouteConfigExtender)
}
func (route *RouteConsistentHashing) UpdateDestination(index int, opts map[string]string) error {
return route.updateDestination(index, opts, consistentHashingRouteConfigExtender)
}
func (route *baseRoute) updateMatcher(matcher Matcher, extendConfig baseConfigExtender) {
route.Lock()
defer route.Unlock()
conf := route.config.Load().(RouteConfig)
conf = extendConfig(baseRouteConfig{matcher, conf.Dests()})
route.config.Store(conf)
}
func (route *baseRoute) UpdateMatcher(matcher Matcher) {
route.updateMatcher(matcher, baseRouteConfigExtender)
}
func (route *RouteConsistentHashing) UpdateMatcher(matcher Matcher) {
route.updateMatcher(matcher, consistentHashingRouteConfigExtender)
}