/
config.go
256 lines (225 loc) · 7.44 KB
/
config.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
// Copyright 2017 Google 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 proxyconfigmap
import (
"encoding/json"
"fmt"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"github.com/ianlewis/memcached-operator/pkg/apis/ianlewis.org/v1alpha1"
"github.com/ianlewis/memcached-operator/pkg/controller"
)
// Pool is a memcached server pool
type Pool struct {
Servers []string `json:"servers"`
}
// OperationPolicies configures operation policies for different actions via mcrouter
type OperationPolicies struct {
Add *StringOrRoute `json:"add,omitempty"`
Set *StringOrRoute `json:"set,omitempty"`
Delete *StringOrRoute `json:"delete,omitempty"`
Get *StringOrRoute `json:"empty,omitempty"`
}
// StringOrRoute describes an mcrouter route. It can be either an object or a string.
type StringOrRoute struct {
Route *Route
StringVal string
}
// MarshalJSON implements the json.Marshaller interface.
func (r StringOrRoute) MarshalJSON() ([]byte, error) {
if r.StringVal != "" {
return json.Marshal(r.StringVal)
} else {
return json.Marshal(r.Route)
}
}
// Route is the object version of a mcrouter route
type Route struct {
Type string `json:"type"`
DefaultPolicy *StringOrRoute `json:"default_policy,omitempty"`
OperationPolicies *OperationPolicies `json:"operation_policies,omitempty"`
Children []StringOrRoute `json:"children,omitempty"`
}
// McRouterConfig represents JSON configuration for mcrouter.
type McRouterConfig struct {
Pools map[string]Pool `json:"pools,omitempty"`
Route StringOrRoute `json:"route,omitempty"`
}
func (c *Controller) configForProxy(p *v1alpha1.MemcachedProxy) (*McRouterConfig, error) {
config := &McRouterConfig{}
config.Pools = make(map[string]Pool)
// A map of pool name to ServiceSpec
services := make(map[string]*v1alpha1.ServiceSpec)
// Parse the proxy's rules and create the mcrouter routes
// A list of services is also built up when parsing the rules
route, _, err := c.routeForRule(p.Spec.Rules, services)
if err != nil {
return nil, err
}
config.Route = route
// Create a memcached server pool for each service found
for poolName, s := range services {
pool, err := c.poolForService(s)
if err != nil {
return nil, err
}
config.Pools[poolName] = pool
}
return config, nil
}
// poolNameForService generates a unique pool name for each service and port combination
func poolNameForServiceSpec(s *v1alpha1.ServiceSpec) string {
return controller.MakeName("", []string{s.Name, s.Port.String()})
}
// poolForService creates a mcroute pool for the given service spec.
func (c *Controller) poolForService(s *v1alpha1.ServiceSpec) (Pool, error) {
pool := Pool{}
// Get the service
svc, err := c.sLister.Services(s.Namespace).Get(s.Name)
if err != nil {
return pool, fmt.Errorf("failed to get service %q: %v", s.Namespace+"/"+s.Name, err)
}
// Find the service port. We need to be able to resolve the service port by name.
var port *corev1.ServicePort
for _, p := range svc.Spec.Ports {
np := p
switch s.Port.Type {
case intstr.Int:
if p.Port == s.Port.IntVal {
port = &np
}
default:
if p.Name == s.Port.StrVal {
port = &np
}
}
}
if port == nil {
return pool, fmt.Errorf("failed to find port %q for service %q", s.Port.String(), s.Namespace+"/"+s.Name)
}
// Get the endpoints for the service
ep, err := c.epLister.Endpoints(svc.Namespace).Get(svc.Name)
if err != nil {
return pool, fmt.Errorf("failed to get endpoints %q: %v", svc.Namespace+"/"+svc.Name, err)
}
// Build the list of servers from the endpoints
// We need to find the right port in the endpoints in order to know what endpoint subset
// to build the addresses from. Here we match the endpoint subset's ports with the service's port
// specified in the proxy object.
for _, subset := range ep.Subsets {
for _, eport := range subset.Ports {
if portMatches(eport, port.TargetPort) {
for _, addr := range subset.Addresses {
pool.Servers = append(pool.Servers, addr.IP+":"+fmt.Sprint(port.Port))
}
}
}
}
return pool, nil
}
// portMatches returns true if the endpoint port is a TCP port and matches the given service target port
func portMatches(eport corev1.EndpointPort, targetPort intstr.IntOrString) bool {
switch targetPort.Type {
case intstr.Int:
return eport.Protocol == corev1.ProtocolTCP && eport.Port == targetPort.IntVal
default:
return eport.Protocol == corev1.ProtocolTCP && eport.Name == targetPort.StrVal
}
}
// routeForRule creates a mcrouter route from a memcached proxy rule
func (c *Controller) routeForRule(r v1alpha1.RuleSpec, services map[string]*v1alpha1.ServiceSpec) (StringOrRoute, map[string]*v1alpha1.ServiceSpec, error) {
if r.Type == v1alpha1.ReplicatedRuleType {
// Create a replicated route
// See: https://github.com/facebook/mcrouter/wiki/Replicated-pools-setup
var route StringOrRoute
if r.Service != nil {
// Replicate among a group of servers in a pool
poolName := poolNameForServiceSpec(r.Service)
services[poolName] = r.Service
route = StringOrRoute{
Route: &Route{
Type: "OperationSelectorRoute",
DefaultPolicy: &StringOrRoute{
StringVal: "AllSyncRoute|Pool|" + poolName,
},
OperationPolicies: &OperationPolicies{
Delete: &StringOrRoute{
StringVal: "LatestRoute|Pool|" + poolName,
},
},
},
}
} else {
// Replicate among a group of child routes
var children []StringOrRoute
for _, route := range r.Children {
child, _, err := c.routeForRule(route, services)
if err != nil {
return StringOrRoute{}, services, err
}
children = append(children, child)
}
route = StringOrRoute{
Route: &Route{
Type: "OperationSelectorRoute",
DefaultPolicy: &StringOrRoute{
Route: &Route{
Type: "AllSyncRoute",
Children: children,
},
},
OperationPolicies: &OperationPolicies{
Delete: &StringOrRoute{
Route: &Route{
Type: "LatestRoute",
Children: children,
},
},
},
},
}
}
return route, services, nil
} else if r.Type == v1alpha1.ShardedRuleType {
// Create a sharded rule
// See: https://github.com/facebook/mcrouter/wiki/Sharded-pools-setup
var route StringOrRoute
if r.Service != nil {
// Shard among a group of servers in a pool
poolName := poolNameForServiceSpec(r.Service)
services[poolName] = r.Service
route = StringOrRoute{
StringVal: "PoolRoute|" + poolName,
}
} else {
// Shard among a group of child routes
var children []StringOrRoute
for _, route := range r.Children {
child, _, err := c.routeForRule(route, services)
if err != nil {
return StringOrRoute{}, services, err
}
children = append(children, child)
}
route = StringOrRoute{
Route: &Route{
Type: "HashRoute",
Children: children,
},
}
}
return route, services, nil
}
return StringOrRoute{}, services, fmt.Errorf("unknown rule type: %q", r.Type)
}