-
Notifications
You must be signed in to change notification settings - Fork 411
/
egress_selector.go
384 lines (339 loc) · 11.4 KB
/
egress_selector.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
379
380
381
382
383
384
/*
Copyright 2019 The Kubernetes Authors.
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 egressselector
import (
"bufio"
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
"google.golang.org/grpc"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apiserver/pkg/apis/apiserver"
egressmetrics "k8s.io/apiserver/pkg/server/egressselector/metrics"
"k8s.io/klog/v2"
utiltrace "k8s.io/utils/trace"
client "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client"
)
var directDialer utilnet.DialFunc = http.DefaultTransport.(*http.Transport).DialContext
// EgressSelector is the map of network context type to context dialer, for network egress.
type EgressSelector struct {
egressToDialer map[EgressType]utilnet.DialFunc
}
// EgressType is an indicator of which egress selection should be used for sending traffic.
// See https://github.com/kubernetes/enhancements/blob/master/keps/sig-api-machinery/1281-network-proxy/README.md#network-context
type EgressType int
const (
// ControlPlane is the EgressType for traffic intended to go to the control plane.
ControlPlane EgressType = iota
// Etcd is the EgressType for traffic intended to go to Kubernetes persistence store.
Etcd
// Cluster is the EgressType for traffic intended to go to the system being managed by Kubernetes.
Cluster
)
// NetworkContext is the struct used by Kubernetes API Server to indicate where it intends traffic to be sent.
type NetworkContext struct {
// EgressSelectionName is the unique name of the
// EgressSelectorConfiguration which determines
// the network we route the traffic to.
EgressSelectionName EgressType
}
// Lookup is the interface to get the dialer function for the network context.
type Lookup func(networkContext NetworkContext) (utilnet.DialFunc, error)
// String returns the canonical string representation of the egress type
func (s EgressType) String() string {
switch s {
case ControlPlane:
return "controlplane"
case Etcd:
return "etcd"
case Cluster:
return "cluster"
default:
return "invalid"
}
}
// AsNetworkContext is a helper function to make it easy to get the basic NetworkContext objects.
func (s EgressType) AsNetworkContext() NetworkContext {
return NetworkContext{EgressSelectionName: s}
}
func lookupServiceName(name string) (EgressType, error) {
switch strings.ToLower(name) {
// 'master' is deprecated, interpret "master" as controlplane internally until removed in v1.22.
case "master":
klog.Warning("EgressSelection name 'master' is deprecated, use 'controlplane' instead")
return ControlPlane, nil
case "controlplane":
return ControlPlane, nil
case "etcd":
return Etcd, nil
case "cluster":
return Cluster, nil
}
return -1, fmt.Errorf("unrecognized service name %s", name)
}
func tunnelHTTPConnect(proxyConn net.Conn, proxyAddress, addr string) (net.Conn, error) {
fmt.Fprintf(proxyConn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", addr, "127.0.0.1")
br := bufio.NewReader(proxyConn)
res, err := http.ReadResponse(br, nil)
if err != nil {
proxyConn.Close()
return nil, fmt.Errorf("reading HTTP response from CONNECT to %s via proxy %s failed: %v",
addr, proxyAddress, err)
}
if res.StatusCode != 200 {
proxyConn.Close()
return nil, fmt.Errorf("proxy error from %s while dialing %s, code %d: %v",
proxyAddress, addr, res.StatusCode, res.Status)
}
// It's safe to discard the bufio.Reader here and return the
// original TCP conn directly because we only use this for
// TLS, and in TLS the client speaks first, so we know there's
// no unbuffered data. But we can double-check.
if br.Buffered() > 0 {
proxyConn.Close()
return nil, fmt.Errorf("unexpected %d bytes of buffered data from CONNECT proxy %q",
br.Buffered(), proxyAddress)
}
return proxyConn, nil
}
type proxier interface {
// proxy returns a connection to addr.
proxy(ctx context.Context, addr string) (net.Conn, error)
}
var _ proxier = &httpConnectProxier{}
type httpConnectProxier struct {
conn net.Conn
proxyAddress string
}
func (t *httpConnectProxier) proxy(ctx context.Context, addr string) (net.Conn, error) {
return tunnelHTTPConnect(t.conn, t.proxyAddress, addr)
}
var _ proxier = &grpcProxier{}
type grpcProxier struct {
tunnel client.Tunnel
}
func (g *grpcProxier) proxy(ctx context.Context, addr string) (net.Conn, error) {
return g.tunnel.DialContext(ctx, "tcp", addr)
}
type proxyServerConnector interface {
// connect establishes connection to the proxy server, and returns a
// proxier based on the connection.
connect() (proxier, error)
}
type tcpHTTPConnectConnector struct {
proxyAddress string
tlsConfig *tls.Config
}
func (t *tcpHTTPConnectConnector) connect() (proxier, error) {
conn, err := tls.Dial("tcp", t.proxyAddress, t.tlsConfig)
if err != nil {
return nil, err
}
return &httpConnectProxier{conn: conn, proxyAddress: t.proxyAddress}, nil
}
type udsHTTPConnectConnector struct {
udsName string
}
func (u *udsHTTPConnectConnector) connect() (proxier, error) {
conn, err := net.Dial("unix", u.udsName)
if err != nil {
return nil, err
}
return &httpConnectProxier{conn: conn, proxyAddress: u.udsName}, nil
}
type udsGRPCConnector struct {
udsName string
}
func (u *udsGRPCConnector) connect() (proxier, error) {
udsName := u.udsName
dialOption := grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {
c, err := net.Dial("unix", udsName)
if err != nil {
klog.Errorf("failed to create connection to uds name %s, error: %v", udsName, err)
}
return c, err
})
ctx := context.TODO()
tunnel, err := client.CreateSingleUseGrpcTunnel(ctx, udsName, dialOption, grpc.WithInsecure())
if err != nil {
return nil, err
}
return &grpcProxier{tunnel: tunnel}, nil
}
type dialerCreator struct {
connector proxyServerConnector
direct bool
options metricsOptions
}
type metricsOptions struct {
transport string
protocol string
}
func (d *dialerCreator) createDialer() utilnet.DialFunc {
if d.direct {
return directDialer
}
return func(ctx context.Context, network, addr string) (net.Conn, error) {
trace := utiltrace.New(fmt.Sprintf("Proxy via %s protocol over %s", d.options.protocol, d.options.transport), utiltrace.Field{Key: "address", Value: addr})
defer trace.LogIfLong(500 * time.Millisecond)
start := egressmetrics.Metrics.Clock().Now()
proxier, err := d.connector.connect()
if err != nil {
egressmetrics.Metrics.ObserveDialFailure(d.options.protocol, d.options.transport, egressmetrics.StageConnect)
return nil, err
}
conn, err := proxier.proxy(ctx, addr)
if err != nil {
egressmetrics.Metrics.ObserveDialFailure(d.options.protocol, d.options.transport, egressmetrics.StageProxy)
return nil, err
}
egressmetrics.Metrics.ObserveDialLatency(egressmetrics.Metrics.Clock().Now().Sub(start), d.options.protocol, d.options.transport)
return conn, nil
}
}
func getTLSConfig(t *apiserver.TLSConfig) (*tls.Config, error) {
clientCert := t.ClientCert
clientKey := t.ClientKey
caCert := t.CABundle
clientCerts, err := tls.LoadX509KeyPair(clientCert, clientKey)
if err != nil {
return nil, fmt.Errorf("failed to read key pair %s & %s, got %v", clientCert, clientKey, err)
}
certPool := x509.NewCertPool()
if caCert != "" {
certBytes, err := ioutil.ReadFile(caCert)
if err != nil {
return nil, fmt.Errorf("failed to read cert file %s, got %v", caCert, err)
}
ok := certPool.AppendCertsFromPEM(certBytes)
if !ok {
return nil, fmt.Errorf("failed to append CA cert to the cert pool")
}
} else {
// Use host's root CA set instead of providing our own
certPool = nil
}
return &tls.Config{
Certificates: []tls.Certificate{clientCerts},
RootCAs: certPool,
}, nil
}
func getProxyAddress(urlString string) (string, error) {
proxyURL, err := url.Parse(urlString)
if err != nil {
return "", fmt.Errorf("invalid proxy server url %q: %v", urlString, err)
}
return proxyURL.Host, nil
}
func connectionToDialerCreator(c apiserver.Connection) (*dialerCreator, error) {
switch c.ProxyProtocol {
case apiserver.ProtocolHTTPConnect:
if c.Transport.UDS != nil {
return &dialerCreator{
connector: &udsHTTPConnectConnector{
udsName: c.Transport.UDS.UDSName,
},
options: metricsOptions{
transport: egressmetrics.TransportUDS,
protocol: egressmetrics.ProtocolHTTPConnect,
},
}, nil
} else if c.Transport.TCP != nil {
tlsConfig, err := getTLSConfig(c.Transport.TCP.TLSConfig)
if err != nil {
return nil, err
}
proxyAddress, err := getProxyAddress(c.Transport.TCP.URL)
if err != nil {
return nil, err
}
return &dialerCreator{
connector: &tcpHTTPConnectConnector{
tlsConfig: tlsConfig,
proxyAddress: proxyAddress,
},
options: metricsOptions{
transport: egressmetrics.TransportTCP,
protocol: egressmetrics.ProtocolHTTPConnect,
},
}, nil
} else {
return nil, fmt.Errorf("Either a TCP or UDS transport must be specified")
}
case apiserver.ProtocolGRPC:
if c.Transport.UDS != nil {
return &dialerCreator{
connector: &udsGRPCConnector{
udsName: c.Transport.UDS.UDSName,
},
options: metricsOptions{
transport: egressmetrics.TransportUDS,
protocol: egressmetrics.ProtocolGRPC,
},
}, nil
}
return nil, fmt.Errorf("UDS transport must be specified for GRPC")
case apiserver.ProtocolDirect:
return &dialerCreator{direct: true}, nil
default:
return nil, fmt.Errorf("unrecognized service connection protocol %q", c.ProxyProtocol)
}
}
// NewEgressSelector configures lookup mechanism for Lookup.
// It does so based on a EgressSelectorConfiguration which was read at startup.
func NewEgressSelector(config *apiserver.EgressSelectorConfiguration) (*EgressSelector, error) {
if config == nil || config.EgressSelections == nil {
// No Connection Services configured, leaving the serviceMap empty, will return default dialer.
return nil, nil
}
cs := &EgressSelector{
egressToDialer: make(map[EgressType]utilnet.DialFunc),
}
for _, service := range config.EgressSelections {
name, err := lookupServiceName(service.Name)
if err != nil {
return nil, err
}
dialerCreator, err := connectionToDialerCreator(service.Connection)
if err != nil {
return nil, fmt.Errorf("failed to create dialer for egressSelection %q: %v", name, err)
}
cs.egressToDialer[name] = dialerCreator.createDialer()
}
return cs, nil
}
// NewEgressSelectorWithMap returns a EgressSelector with the supplied EgressType to DialFunc map.
func NewEgressSelectorWithMap(m map[EgressType]utilnet.DialFunc) *EgressSelector {
if m == nil {
m = make(map[EgressType]utilnet.DialFunc)
}
return &EgressSelector{
egressToDialer: m,
}
}
// Lookup gets the dialer function for the network context.
// This is configured for the Kubernetes API Server at startup.
func (cs *EgressSelector) Lookup(networkContext NetworkContext) (utilnet.DialFunc, error) {
if cs.egressToDialer == nil {
// The round trip wrapper will over-ride the dialContext method appropriately
return nil, nil
}
return cs.egressToDialer[networkContext.EgressSelectionName], nil
}