forked from cloudfoundry/gorouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
registry.go
274 lines (220 loc) · 6.2 KB
/
registry.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
package registry
import (
"encoding/json"
"strings"
"sync"
"time"
"code.cloudfoundry.org/gorouter/config"
"code.cloudfoundry.org/gorouter/metrics/reporter"
"code.cloudfoundry.org/gorouter/registry/container"
"code.cloudfoundry.org/gorouter/route"
"code.cloudfoundry.org/lager"
)
//go:generate counterfeiter -o fakes/fake_registry_interface.go . RegistryInterface
type RegistryInterface interface {
Register(uri route.Uri, endpoint *route.Endpoint)
Unregister(uri route.Uri, endpoint *route.Endpoint)
Lookup(uri route.Uri) *route.Pool
LookupWithInstance(uri route.Uri, appId, appIndex string) *route.Pool
StartPruningCycle()
StopPruningCycle()
NumUris() int
NumEndpoints() int
MarshalJSON() ([]byte, error)
}
type PruneStatus int
const (
CONNECTED = PruneStatus(iota)
DISCONNECTED
)
type RouteRegistry struct {
sync.RWMutex
logger lager.Logger
// Access to the Trie datastructure should be governed by the RWMutex of RouteRegistry
byUri *container.Trie
// used for ability to suspend pruning
suspendPruning func() bool
pruningStatus PruneStatus
pruneStaleDropletsInterval time.Duration
dropletStaleThreshold time.Duration
reporter reporter.RouteRegistryReporter
ticker *time.Ticker
timeOfLastUpdate time.Time
}
func NewRouteRegistry(logger lager.Logger, c *config.Config, reporter reporter.RouteRegistryReporter) *RouteRegistry {
r := &RouteRegistry{}
r.logger = logger
r.byUri = container.NewTrie()
r.pruneStaleDropletsInterval = c.PruneStaleDropletsInterval
r.dropletStaleThreshold = c.DropletStaleThreshold
r.suspendPruning = func() bool { return false }
r.reporter = reporter
return r
}
func (r *RouteRegistry) Register(uri route.Uri, endpoint *route.Endpoint) {
t := time.Now()
data := lager.Data{"uri": uri, "backend": endpoint.CanonicalAddr(), "modification_tag": endpoint.ModificationTag}
r.reporter.CaptureRegistryMessage(endpoint)
r.Lock()
uri = uri.RouteKey()
pool := r.byUri.Find(uri)
if pool == nil {
contextPath := parseContextPath(uri)
pool = route.NewPool(r.dropletStaleThreshold/4, contextPath)
r.byUri.Insert(uri, pool)
r.logger.Debug("uri-added", lager.Data{"uri": uri})
}
endpointAdded := pool.Put(endpoint)
r.timeOfLastUpdate = t
r.Unlock()
if endpointAdded {
r.logger.Debug("endpoint-registered", data)
} else {
r.logger.Debug("endpoint-not-registered", data)
}
}
func (r *RouteRegistry) Unregister(uri route.Uri, endpoint *route.Endpoint) {
data := lager.Data{"uri": uri, "backend": endpoint.CanonicalAddr(), "modification_tag": endpoint.ModificationTag}
r.reporter.CaptureRegistryMessage(endpoint)
r.Lock()
uri = uri.RouteKey()
pool := r.byUri.Find(uri)
if pool != nil {
endpointRemoved := pool.Remove(endpoint)
if endpointRemoved {
r.logger.Debug("endpoint-unregistered", data)
} else {
r.logger.Debug("endpoint-not-unregistered", data)
}
if pool.IsEmpty() {
r.byUri.Delete(uri)
}
}
r.Unlock()
}
func (r *RouteRegistry) Lookup(uri route.Uri) *route.Pool {
started := time.Now()
r.RLock()
uri = uri.RouteKey()
var err error
pool := r.byUri.MatchUri(uri)
for pool == nil && err == nil {
uri, err = uri.NextWildcard()
pool = r.byUri.MatchUri(uri)
}
r.RUnlock()
endLookup := time.Now()
r.reporter.CaptureLookupTime(endLookup.Sub(started))
return pool
}
func (r *RouteRegistry) LookupWithInstance(uri route.Uri, appId string, appIndex string) *route.Pool {
uri = uri.RouteKey()
p := r.Lookup(uri)
var surgicalPool *route.Pool
p.Each(func(e *route.Endpoint) {
if (e.ApplicationId == appId) && (e.PrivateInstanceIndex == appIndex) {
surgicalPool = route.NewPool(0, "")
surgicalPool.Put(e)
}
})
return surgicalPool
}
func (r *RouteRegistry) StartPruningCycle() {
if r.pruneStaleDropletsInterval > 0 {
r.Lock()
r.ticker = time.NewTicker(r.pruneStaleDropletsInterval)
r.Unlock()
go func() {
for {
select {
case <-r.ticker.C:
r.logger.Info("start-pruning-droplets")
r.pruneStaleDroplets()
r.logger.Info("finished-pruning-droplets")
msSinceLastUpdate := uint64(time.Since(r.TimeOfLastUpdate()) / time.Millisecond)
r.reporter.CaptureRouteStats(r.NumUris(), msSinceLastUpdate)
}
}
}()
}
}
func (r *RouteRegistry) StopPruningCycle() {
r.Lock()
if r.ticker != nil {
r.ticker.Stop()
}
r.Unlock()
}
func (registry *RouteRegistry) NumUris() int {
registry.RLock()
uriCount := registry.byUri.PoolCount()
registry.RUnlock()
return uriCount
}
func (r *RouteRegistry) TimeOfLastUpdate() time.Time {
r.RLock()
t := r.timeOfLastUpdate
r.RUnlock()
return t
}
func (r *RouteRegistry) NumEndpoints() int {
r.RLock()
count := r.byUri.EndpointCount()
r.RUnlock()
return count
}
func (r *RouteRegistry) MarshalJSON() ([]byte, error) {
r.RLock()
defer r.RUnlock()
return json.Marshal(r.byUri.ToMap())
}
func (r *RouteRegistry) pruneStaleDroplets() {
r.Lock()
defer r.Unlock()
// suspend pruning if option enabled and if NATS is unavailable
if r.suspendPruning() {
r.logger.Info("prune-suspended")
r.pruningStatus = DISCONNECTED
return
} else {
if r.pruningStatus == DISCONNECTED {
// if we are coming back from being disconnected from source,
// bulk update routes / mark updated to avoid pruning right away
r.logger.Debug("prune-unsuspended-refresh-routes-start")
r.freshenRoutes()
r.logger.Debug("prune-unsuspended-refresh-routes-complete")
}
r.pruningStatus = CONNECTED
}
r.byUri.EachNodeWithPool(func(t *container.Trie) {
endpoints := t.Pool.PruneEndpoints(r.dropletStaleThreshold)
t.Snip()
if len(endpoints) > 0 {
addresses := []string{}
for _, e := range endpoints {
addresses = append(addresses, e.CanonicalAddr())
}
r.logger.Info("pruned-route", lager.Data{"uri": t.ToPath(), "endpoints": addresses})
}
})
}
func (r *RouteRegistry) SuspendPruning(f func() bool) {
r.Lock()
r.suspendPruning = f
r.Unlock()
}
// bulk update to mark pool / endpoints as updated
func (r *RouteRegistry) freshenRoutes() {
now := time.Now()
r.byUri.EachNodeWithPool(func(t *container.Trie) {
t.Pool.MarkUpdated(now)
})
}
func parseContextPath(uri route.Uri) string {
contextPath := "/"
split := strings.SplitN(strings.TrimPrefix(uri.String(), "/"), "/", 2)
if len(split) > 1 {
contextPath += split[1]
}
return contextPath
}