-
Notifications
You must be signed in to change notification settings - Fork 24
/
entity_cache.go
364 lines (320 loc) · 9.81 KB
/
entity_cache.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
package entitycache
import (
"context"
"sync"
"go.uber.org/fx"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
entitycachev1 "github.com/fluxninja/aperture/api/gen/proto/go/aperture/common/entitycache/v1"
"github.com/fluxninja/aperture/pkg/config"
"github.com/fluxninja/aperture/pkg/discovery/common"
"github.com/fluxninja/aperture/pkg/log"
"github.com/fluxninja/aperture/pkg/net/grpcgateway"
"github.com/fluxninja/aperture/pkg/notifiers"
"github.com/fluxninja/aperture/pkg/services"
)
// Module sets up EntityCache with Fx.
func Module() fx.Option {
return fx.Options(
fx.Provide(provideEntityCache),
grpcgateway.RegisterHandler{Handler: entitycachev1.RegisterEntityCacheServiceHandlerFromEndpoint}.Annotate(),
fx.Invoke(RegisterEntityCacheService),
)
}
// ServiceKey holds key for service.
type ServiceKey struct {
Name string `json:"name"`
}
func (sk ServiceKey) lessThan(sk2 ServiceKey) bool {
return sk.Name < sk2.Name
}
// keyFromService returns a service key for given service.
func (c *EntityCache) keyFromService(service *entitycachev1.Service) *ServiceKey {
return &ServiceKey{
Name: service.Name,
}
}
// Merge merges `mergedService` into `originalService`. This sums `EntitiesCount`.
func Merge(originalService, mergedService *entitycachev1.Service) {
originalService.EntitiesCount += mergedService.EntitiesCount
}
// Entity represents a pod, vm, etc.
//
// Entities can be created with NewEntity.
type Entity struct {
// ID of the entity
ID EntityID `json:"id,omitempty"`
// IP Address of this entity
IPAddress string `json:"ip_address"`
// Services is a List of names of services this entity is a part of.
// We store "well-known-labels" (identifying a service) in a separate
// fields for easier access. Note: we could store `[]agent_core/services/ServiceID`
// here directly, but right now it'd cause cyclic dependency.
Services []string `json:"services"`
// EntityName is the name of this entity
EntityName string `json:"name"`
}
// IP returns IP of this entity.
func (e *Entity) IP() string {
return e.IPAddress
}
// Name returns Name of this entity.
func (e *Entity) Name() string {
return e.EntityName
}
// EntityID is a unique Entity identifier.
type EntityID struct {
Prefix string `json:"prefix,omitempty"`
UID string `json:"uid,omitempty"`
}
// NewEntity creates a new entity from ID and IP address from the tagger.
func NewEntity(id EntityID, ipAddress, name string, services []string) *Entity {
return &Entity{
ID: id,
IPAddress: ipAddress,
Services: services,
EntityName: name,
}
}
// EntityCache maps IP addresses and Entity names to entities.
type EntityCache struct {
entitycachev1.UnimplementedEntityCacheServiceServer
sync.RWMutex
entitiesByIP map[string]*Entity
entitiesByName map[string]*Entity
}
// FxIn are the parameters for ProvideEntityCache.
type FxIn struct {
fx.In
Lifecycle fx.Lifecycle
EntityTrackers notifiers.Trackers `name:"entity_trackers"`
}
// provideEntityCache creates Entity Cache.
func provideEntityCache(in FxIn) (*EntityCache, error) {
entityCache := NewEntityCache()
// create a ConfigPrefixNotifier
configPrefixNotifier := ¬ifiers.UnmarshalPrefixNotifier{
GetUnmarshallerFunc: config.KoanfUnmarshallerConstructor{}.NewKoanfUnmarshaller,
UnmarshalNotifyFunc: entityCache.processUpdate,
}
in.Lifecycle.Append(fx.Hook{
OnStart: func(context.Context) error {
err := in.EntityTrackers.AddPrefixNotifier(configPrefixNotifier)
if err != nil {
log.Error().Err(err).Msg("failed to add config prefix notifier")
return err
}
return nil
},
OnStop: func(context.Context) error {
err := in.EntityTrackers.RemovePrefixNotifier(configPrefixNotifier)
if err != nil {
log.Error().Err(err).Msg("failed to remove prefix notifier")
return err
}
return nil
},
})
return entityCache, nil
}
func (c *EntityCache) processUpdate(event notifiers.Event, unmarshaller config.Unmarshaller) {
log.Trace().Str("event", event.String()).Msg("Updating entity")
var rawEntity common.Entity
if err := unmarshaller.UnmarshalKey("", &rawEntity); err != nil {
log.Error().Err(err).Msg("Failed to unmarshal entity")
return
}
entity := discoveryEntityToCacheEntity(&rawEntity)
ip := entity.IP()
name := entity.Name()
switch event.Type {
case notifiers.Write:
log.Trace().Str("entity", entity.ID.Prefix+entity.ID.UID).Str("ip", ip).Str("name", name).Msg("new entity")
c.Put(entity)
case notifiers.Remove:
log.Trace().Str("entity", entity.ID.Prefix+entity.ID.UID).Str("ip", ip).Str("name", name).Msg("removing entity")
c.Remove(entity)
}
}
func discoveryEntityToCacheEntity(entity *common.Entity) *Entity {
return NewEntity(EntityID{
Prefix: entity.Prefix,
UID: entity.UID,
}, entity.IPAddress, entity.Name, entity.Services)
}
// NewEntityCache creates a new, empty EntityCache.
func NewEntityCache() *EntityCache {
entitiesByIP := make(map[string]*Entity)
entitiesByName := make(map[string]*Entity)
return &EntityCache{
entitiesByIP: entitiesByIP,
entitiesByName: entitiesByName,
}
}
// Put maps given IP address and name to the entity it currently represents.
func (c *EntityCache) Put(entity *Entity) {
c.Lock()
defer c.Unlock()
entityIP := entity.IP()
if entityIP != "" {
c.entitiesByIP[entityIP] = entity
}
entityName := entity.Name()
if entityName != "" {
c.entitiesByName[entityName] = entity
}
}
// GetByIP retrieves entity with a given IP address.
func (c *EntityCache) GetByIP(entityIP string) *Entity {
c.RLock()
defer c.RUnlock()
v, ok := c.entitiesByIP[entityIP]
if !ok {
return nil
}
return v
}
// GetByName retrieves entity with a given name.
func (c *EntityCache) GetByName(entityName string) *Entity {
c.RLock()
defer c.RUnlock()
v, ok := c.entitiesByName[entityName]
if !ok {
return nil
}
return v
}
// Clear removes all entities from the cache.
func (c *EntityCache) Clear() {
c.RLock()
defer c.RUnlock()
c.entitiesByIP = make(map[string]*Entity)
c.entitiesByName = make(map[string]*Entity)
}
// Remove removes entity from the cache and returns `true` if any of IP address
// or name mapping exists.
// If no such entity was found, returns `false`.
func (c *EntityCache) Remove(entity *Entity) bool {
c.Lock()
defer c.Unlock()
entityIP := entity.IP()
_, okByIP := c.entitiesByIP[entityIP]
if okByIP {
delete(c.entitiesByIP, entityIP)
}
entityName := entity.Name()
_, okByName := c.entitiesByName[entityName]
if okByName {
delete(c.entitiesByName, entityName)
}
return okByIP || okByName
}
// Services returns a list of services based on entities in cache.
//
// Each service is identified by 2 values:
// - agent group
// - service name
//
// This shouldn't happen in real world, but entities which have multiple values
// for an agent group is ignored.
// Entities which have multiple values for service name will create one service
// for each of them.
func (c *EntityCache) Services() *entitycachev1.ServicesList {
c.RLock()
defer c.RUnlock()
services := map[ServiceKey]*entitycachev1.Service{}
overlapping := make(map[pair]int)
for _, entity := range c.entitiesByIP {
entityServices, err := servicesFromEntity(entity)
if err != nil {
log.Trace().Err(err).Str("entity", entity.ID.UID).Msg("Failed getting services from entity. Skipping")
continue
}
var serviceKeys []ServiceKey
for _, es := range entityServices {
key := *c.keyFromService(es)
serviceKeys = append(serviceKeys, key)
if _, ok := services[key]; !ok {
services[key] = es
continue
}
Merge(services[key], es)
}
// for each pair in entityServices count number of overlapping entities
for _, pair := range eachPair(serviceKeys) {
overlapping[pair]++
}
}
entityCache := &entitycachev1.ServicesList{
Services: make([]*entitycachev1.Service, 0, len(services)),
OverlappingServices: make([]*entitycachev1.OverlappingService, 0, len(overlapping)),
}
for _, svc := range services {
entityCache.Services = append(entityCache.Services, svc)
}
for k, v := range overlapping {
entityCache.OverlappingServices = append(entityCache.OverlappingServices, &entitycachev1.OverlappingService{
Service1: k.x.Name,
Service2: k.y.Name,
EntitiesCount: int32(v),
})
}
return entityCache
}
type pair struct {
x, y ServiceKey
}
// GetServicesList returns a list of services based on entities in cache.
func (c *EntityCache) GetServicesList(ctx context.Context, _ *emptypb.Empty) (*entitycachev1.ServicesList, error) {
return c.Services(), nil
}
// eachPair returns each pair of elements in a slice. Elements in the pair are sorted so that
// x < y.
func eachPair(services []ServiceKey) []pair {
n := len(services)
pairs := make([]pair, 0, n*n)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
if services[i].lessThan(services[j]) {
pairs = append(pairs, pair{
x: services[i],
y: services[j],
})
} else {
pairs = append(pairs, pair{
x: services[j],
y: services[i],
})
}
}
}
return pairs
}
// ServiceIDsFromEntity returns a list of services the entity is a part of.
func ServiceIDsFromEntity(entity *Entity) []services.ServiceID {
var svcs []services.ServiceID
if entity != nil {
svcs = make([]services.ServiceID, 0, len(entity.Services))
for _, service := range entity.Services {
svcs = append(svcs, services.ServiceID{
Service: service,
})
}
}
return svcs
}
func servicesFromEntity(entity *Entity) ([]*entitycachev1.Service, error) {
svcIDs := ServiceIDsFromEntity(entity)
svcs := make([]*entitycachev1.Service, 0, len(svcIDs))
for _, svc := range svcIDs {
svcs = append(svcs, &entitycachev1.Service{
Name: svc.Service,
EntitiesCount: 1,
})
}
return svcs, nil
}
// RegisterEntityCacheService registers a service for entity cache.
func RegisterEntityCacheService(server *grpc.Server, cache *EntityCache) {
entitycachev1.RegisterEntityCacheServiceServer(server, cache)
}