-
Notifications
You must be signed in to change notification settings - Fork 45
/
endpoint.go
218 lines (192 loc) · 6.05 KB
/
endpoint.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
package eds
import (
"fmt"
"time"
"github.com/gojektech/consul-envoy-xds/agent"
"github.com/gojektech/consul-envoy-xds/pubsub"
"log"
cp "github.com/envoyproxy/go-control-plane/envoy/api/v2"
cpcore "github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
eds "github.com/envoyproxy/go-control-plane/envoy/api/v2/endpoint"
"github.com/envoyproxy/go-control-plane/envoy/api/v2/route"
"github.com/gojektech/consul-envoy-xds/config"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/watch"
"strings"
)
//Endpoint is an agent catalog service
type Endpoint interface {
Clusters() []*cp.Cluster
Routes() []*cp.RouteConfiguration
CLA() []*cp.ClusterLoadAssignment
WatchPlan(publish func(*pubsub.Event)) (*watch.Plan, error)
}
const (
regexPathIdentifier = "%regex:"
)
type service struct {
services map[string]Service
agent agent.ConsulAgent
httpRateLimitConfig *config.HTTPHeaderRateLimitConfig
enableHealthCheck bool
}
func (s *service) serviceNames() []string {
var names []string
for k := range s.services {
names = append(names, k)
}
return names
}
func (s *service) getLbEndpoints(services []*api.CatalogService) []eds.LbEndpoint {
var hosts []eds.LbEndpoint
for _, s := range services {
hosts = append(hosts, NewServiceHost(s).LbEndpoint())
}
return hosts
}
func (s *service) CLA() []*cp.ClusterLoadAssignment {
serviceList, _ := s.getCatalogServiceEndpoints(s.enableHealthCheck)
log.Printf("discovered services from consul catalog for EDS: %v", serviceList)
var cLAs []*cp.ClusterLoadAssignment
for _, services := range serviceList {
if len(services) > 0 {
cLAs = append(cLAs, &cp.ClusterLoadAssignment{
ClusterName: services[0].ServiceName,
Policy: &cp.ClusterLoadAssignment_Policy{
DropOverload: 0.0,
},
Endpoints: []eds.LocalityLbEndpoints{{
Locality: s.agent.Locality(),
LbEndpoints: s.getLbEndpoints(services),
}},
})
}
}
return cLAs
}
func (s *service) Clusters() []*cp.Cluster {
serviceList, _ := s.getCatalogServiceEndpoints(s.enableHealthCheck)
log.Printf("discovered services from consul catalog for CDS: %v", serviceList)
var clusters []*cp.Cluster
for _, services := range serviceList {
if len(services) > 0 {
clusters = append(clusters, &cp.Cluster{
Name: services[0].ServiceName,
Type: cp.Cluster_EDS,
ConnectTimeout: 1 * time.Second,
ProtocolSelection: cp.Cluster_USE_DOWNSTREAM_PROTOCOL,
EdsClusterConfig: &cp.Cluster_EdsClusterConfig{
EdsConfig: &cpcore.ConfigSource{
ConfigSourceSpecifier: &cpcore.ConfigSource_Ads{
Ads: &cpcore.AggregatedConfigSource{},
},
},
},
})
}
}
return clusters
}
func (s *service) Routes() []*cp.RouteConfiguration {
var routes []route.Route
for _, serviceName := range s.serviceNames() {
routes = append(routes, getRoutes(serviceName, s.services[serviceName].Whitelist)...)
}
routeConfig := &cp.RouteConfiguration{
Name: "local_route",
VirtualHosts: []route.VirtualHost{{
Name: "local_service",
Domains: []string{"*"},
Routes: routes,
RateLimits: getRateLimits(s.httpRateLimitConfig),
}},
}
return []*cp.RouteConfiguration{routeConfig}
}
func (s *service) WatchPlan(publish func(*pubsub.Event)) (*watch.Plan, error) {
plan, err := watch.Parse(map[string]interface{}{
"type": "services",
"datacenter": s.agent.WatchParams()["datacenter"],
"token": s.agent.WatchParams()["token"],
})
if err != nil {
return nil, err
}
plan.Handler = func(idx uint64, data interface{}) {
log.Println(fmt.Sprintf("consul watch triggerred: %v", data))
publish(&pubsub.Event{CLA: s.CLA(), Clusters: s.Clusters(), Routes: s.Routes()})
}
return plan, nil
}
func (s *service) getCatalogServiceEndpoints(enableHealthCheck bool) ([][]*api.CatalogService, error) {
if enableHealthCheck {
healthCheckCatalogSvc, err := s.agent.HealthCheckCatalogServiceEndpoints(s.serviceNames()...)
return healthCheckCatalogSvc, err
}
catalogSvc, err := s.agent.CatalogServiceEndpoints(s.serviceNames()...)
return catalogSvc, err
}
func getRoutes(cluster string, whitelistPaths []string) []route.Route {
var routes []route.Route
for _, whitelistPath := range whitelistPaths {
routes = append(routes, route.Route{
Match: getPathSpecifier(whitelistPath),
Action: &route.Route_Route{
Route: &route.RouteAction{
ClusterSpecifier: &route.RouteAction_Cluster{
Cluster: cluster,
},
},
},
})
}
return routes
}
func getPathSpecifier(whitelistPath string) route.RouteMatch {
if strings.HasPrefix(whitelistPath, regexPathIdentifier) {
regexPath := strings.Replace(whitelistPath, regexPathIdentifier, "", -1)
return route.RouteMatch{
PathSpecifier: &route.RouteMatch_Regex{
Regex: regexPath,
},
}
}
return route.RouteMatch{
PathSpecifier: &route.RouteMatch_Prefix{
Prefix: whitelistPath,
}}
}
func getRateLimits(httpRateLimitConfig *config.HTTPHeaderRateLimitConfig) []*route.RateLimit {
var rateLimits []*route.RateLimit
if httpRateLimitConfig.IsEnabled {
rateLimits = append(rateLimits, getHTTPHeaderRateLimit(httpRateLimitConfig))
}
return rateLimits
}
func getHTTPHeaderRateLimit(httpRateLimitConfig *config.HTTPHeaderRateLimitConfig) *route.RateLimit {
actionSpecifier := route.RateLimit_Action_RequestHeaders_{
RequestHeaders: &route.RateLimit_Action_RequestHeaders{
HeaderName: httpRateLimitConfig.HeaderName,
DescriptorKey: httpRateLimitConfig.DescriptorKey,
},
}
routeAction := route.RateLimit_Action{
ActionSpecifier: &actionSpecifier,
}
return &route.RateLimit{
Actions: []*route.RateLimit_Action{&routeAction},
}
}
//NewEndpoint creates an ServiceEndpoint representation
func NewEndpoint(services []Service, a agent.ConsulAgent, httpRateLimitConfig *config.HTTPHeaderRateLimitConfig, enableHealthCheck bool) Endpoint {
svcMap := map[string]Service{}
for _, s := range services {
svcMap[s.Name] = s
}
return &service{
services: svcMap,
agent: a,
httpRateLimitConfig: httpRateLimitConfig,
enableHealthCheck: enableHealthCheck,
}
}