Debian Codegraph @

pkg/agent/client.go

raw symbols SCIP
1 /*
2 Copyright 2019 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package agent
18
19 import (
20 "context"
21 "fmt"
22 "io"
23 "net"
24 "os"
25 runpprof "runtime/pprof"
26 "strconv"
27 "sync"
28 "sync/atomic"
29 "time"
30
31 "google.golang.org/grpc"
32 "google.golang.org/grpc/codes"
33 "google.golang.org/grpc/connectivity"
34 "google.golang.org/grpc/metadata"
35 "google.golang.org/grpc/status"
36 "k8s.io/klog/v2"
37
38 commonmetrics "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics"
39 "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client"
40 "sigs.k8s.io/apiserver-network-proxy/pkg/agent/metrics"
41 "sigs.k8s.io/apiserver-network-proxy/proto/agent"
42 "sigs.k8s.io/apiserver-network-proxy/proto/header"
43 )
44
45 const dialTimeout = 5 * time.Second
46
47 // endpointConn tracks a connection from agent to node network.
48 type endpointConn struct {
49 conn net.Conn
50 connID int64
51 cleanFunc func()
52 dataCh chan []byte
53 cleanOnce sync.Once
54 warnChLim bool
55 dialDone chan struct{}
56 }
57
58 func (e *endpointConn) cleanup() {
59 e.cleanOnce.Do(e.cleanFunc)
60 }
61
62 func (e *endpointConn) send(msg []byte) {
63 // TODO (cheftako@): Get perf test working and compare this solution with a lock based solution.
64 defer func() {
65 // Handles the race condition where we write to a closed channel
66 if err := recover(); err != nil {
67 klog.InfoS("Recovered from attempt to write to closed channel")
68 }
69 }()
70 if e.warnChLim && len(e.dataCh) >= cap(e.dataCh) {
71 klog.V(2).InfoS("Data channel on agent is full", "connectionID", e.connID)
72 }
73
74 e.dataCh <- msg
75 }
76
77 type connectionManager struct {
78 mu sync.RWMutex
79 connections map[int64]*endpointConn
80 }
81
82 func (cm *connectionManager) Add(connID int64, eConn *endpointConn) {
83 cm.mu.Lock()
84 defer cm.mu.Unlock()
85 metrics.Metrics.EndpointConnectionInc()
86 cm.connections[connID] = eConn
87 }
88
89 func (cm *connectionManager) Get(connID int64) (*endpointConn, bool) {
90 cm.mu.RLock()
91 defer cm.mu.RUnlock()
92 eConn, ok := cm.connections[connID]
93 return eConn, ok
94 }
95
96 func (cm *connectionManager) Delete(connID int64) {
97 cm.mu.Lock()
98 defer cm.mu.Unlock()
99 // Delete for a connID is called from cleanFunc, which is
100 // protected by cleanOnce.
101 metrics.Metrics.EndpointConnectionDec()
102 delete(cm.connections, connID)
103 }
104
105 func (cm *connectionManager) List() []*endpointConn {
106 cm.mu.RLock()
107 defer cm.mu.RUnlock()
108 endpointConns := make([]*endpointConn, 0, len(cm.connections))
109 for _, eConn := range cm.connections {
110 endpointConns = append(endpointConns, eConn)
111 }
112 return endpointConns
113 }
114
115 func newConnectionManager() *connectionManager {
116 return &connectionManager{
117 connections: make(map[int64]*endpointConn),
118 }
119 }
120
121 // Client runs on the node network side. It connects to proxy server and establishes
122 // a stream connection from which it sends and receives network traffic.
123 type Client struct {
124 nextConnID int64
125
126 connManager *connectionManager
127
128 cs *ClientSet // the clientset that includes this AgentClient.
129
130 stream agent.AgentService_ConnectClient
131 agentID string
132 agentIdentifiers string
133 serverID string // the id of the proxy server this client connects to.
134
135 // connect opts
136 address string
137 opts []grpc.DialOption
138 conn *grpc.ClientConn
139
140 drainCh <-chan struct{}
141 drainOnce sync.Once
142 stopCh chan struct{}
143
144 // locks
145 sendLock sync.Mutex
146 recvLock sync.Mutex
147 probeInterval time.Duration // interval between probe pings
148
149 // file path contains service account token.
150 // token's value is auto-rotated by kubernetes, based on projected volume configuration.
151 serviceAccountTokenPath string
152
153 warnOnChannelLimit bool
154 }
155
156 func newAgentClient(address, agentID, agentIdentifiers string, cs *ClientSet, opts ...grpc.DialOption) (*Client, int, error) {
157 a := &Client{
158 cs: cs,
159 address: address,
160 agentID: agentID,
161 agentIdentifiers: agentIdentifiers,
162 opts: opts,
163 probeInterval: cs.probeInterval,
164 drainCh: cs.drainCh,
165 stopCh: make(chan struct{}),
166 serviceAccountTokenPath: cs.serviceAccountTokenPath,
167 connManager: newConnectionManager(),
168 warnOnChannelLimit: cs.warnOnChannelLimit,
169 }
170 serverCount, err := a.Connect()
171 if err != nil {
172 return nil, 0, err
173 }
174 return a, serverCount, nil
175 }
176
177 // Connect makes the grpc dial to the proxy server. It returns the count
178 // of the number of servers this agent should connected to.
179 func (a *Client) Connect() (int, error) {
180 conn, err := grpc.Dial(a.address, a.opts...)
181 if err != nil {
182 return 0, err
183 }
184 ctx := metadata.AppendToOutgoingContext(context.Background(),
185 header.AgentID, a.agentID,
186 header.AgentIdentifiers, a.agentIdentifiers)
187 if a.serviceAccountTokenPath != "" {
188 if ctx, err = a.initializeAuthContext(ctx); err != nil {
189 err := conn.Close()
190 if err != nil {
191 klog.ErrorS(err, "failed to close gRPC connection", "agentID", a.agentID)
192 }
193 return 0, err
194 }
195 }
196 stream, err := agent.NewAgentServiceClient(conn).Connect(ctx)
197 if err != nil {
198 conn.Close() /* #nosec G104 */
199 return 0, err
200 }
201 serverID, err := serverID(stream)
202 if err != nil {
203 conn.Close() /* #nosec G104 */
204 return 0, err
205 }
206 serverCount, err := serverCount(stream)
207 if err != nil {
208 conn.Close() /* #nosec G104 */
209 return 0, err
210 }
211 a.conn = conn
212 a.stream = stream
213 a.serverID = serverID
214 klog.V(2).InfoS("Connect to server", "serverID", serverID)
215 return serverCount, nil
216 }
217
218 // Close closes the Connect gRPC connection.
219 func (a *Client) Close() {
220 if a.conn == nil {
221 klog.Errorln("Unexpected empty AgentClient.conn")
222 }
223 err := a.conn.Close()
224 if err != nil {
225 klog.ErrorS(err, "failed to close gRPC connection", "serverID", a.serverID, "agentID", a.agentID)
226 }
227 close(a.stopCh)
228 }
229
230 func (a *Client) Send(pkt *client.Packet) error {
231 a.sendLock.Lock()
232 defer a.sendLock.Unlock()
233
234 const segment = commonmetrics.SegmentFromAgent
235 metrics.Metrics.ObservePacket(segment, pkt.Type)
236 err := a.stream.Send(pkt)
237 if err != nil && err != io.EOF {
238 metrics.Metrics.ObserveServerFailureDeprecated(metrics.DirectionToServer)
239 metrics.Metrics.ObserveStreamError(segment, err, pkt.Type)
240 a.cs.RemoveClient(a.serverID)
241 }
242 return err
243 }
244
245 func (a *Client) Recv() (*client.Packet, error) {
246 a.recvLock.Lock()
247 defer a.recvLock.Unlock()
248
249 const segment = commonmetrics.SegmentToAgent
250 pkt, err := a.stream.Recv()
251 if err != nil {
252 if err != io.EOF {
253 metrics.Metrics.ObserveServerFailureDeprecated(metrics.DirectionFromServer)
254 metrics.Metrics.ObserveStreamErrorNoPacket(segment, err)
255 }
256 return nil, err
257 }
258 metrics.Metrics.ObservePacket(segment, pkt.Type)
259 return pkt, nil
260 }
261
262 func serverCount(stream agent.AgentService_ConnectClient) (int, error) {
263 md, err := stream.Header()
264 if err != nil {
265 return 0, err
266 }
267 scounts := md.Get(header.ServerCount)
268 if len(scounts) != 1 {
269 return 0, fmt.Errorf("expected one server count, got %d", len(scounts))
270 }
271 scount := scounts[0]
272 return strconv.Atoi(scount)
273 }
274
275 func serverID(stream agent.AgentService_ConnectClient) (string, error) {
276 // TODO: this is a blocking call. Add a timeout?
277 md, err := stream.Header()
278 if err != nil {
279 return "", err
280 }
281 sids := md.Get(header.ServerID)
282 if len(sids) != 1 {
283 return "", fmt.Errorf("expected one server ID in the context, got %v", sids)
284 }
285 return sids[0], nil
286 }
287
288 func (a *Client) initializeAuthContext(ctx context.Context) (context.Context, error) {
289 var err error
290 var b []byte
291
292 // load current service account's token value
293 if b, err = os.ReadFile(a.serviceAccountTokenPath); err != nil {
294 klog.ErrorS(err, "Failed to read token", "path", a.serviceAccountTokenPath)
295 return nil, err
296 }
297 ctx = metadata.AppendToOutgoingContext(ctx, header.AuthenticationTokenContextKey, header.AuthenticationTokenContextSchemePrefix+string(b))
298
299 return ctx, nil
300 }
301
302 // Connect connects to proxy server to establish a gRPC stream,
303 // on which the proxied traffic is multiplexed through the stream
304 // and piped to the local connection. It register itself as a
305 // backend from proxy server, so proxy server will route traffic
306 // to this agent.
307 //
308 // The caller needs to call Serve to start serving proxy requests
309 // coming from proxy server.
310
311 // Serve starts to serve proxied requests from proxy server over the
312 // gRPC stream. Successful Connect is required before Serve. The
313 // The requests include things like opening a connection to a server,
314 // streaming data and close the connection.
315 func (a *Client) Serve() {
316 defer a.cs.RemoveClient(a.serverID)
317 defer func() {
318 // close all of conns with remote when Client exits
319 for _, eConn := range a.connManager.List() {
320 eConn.cleanup()
321 }
322 klog.V(2).InfoS("cleanup all of conn contexts when client exits")
323 }()
324
325 klog.V(2).InfoS("Start serving", "serverID", a.serverID, "agentID", a.agentID)
326 go a.probe()
327 for {
328 select {
329 case <-a.stopCh:
330 klog.V(2).InfoS("stop agent client.")
331 return
332 case <-a.drainCh:
333 a.drainOnce.Do(func() {
334 klog.V(2).InfoS("drain agent client", "serverID", a.serverID, "agentID", a.agentID)
335 drainPkt := &client.Packet{
336 Type: client.PacketType_DRAIN,
337 Payload: &client.Packet_Drain{
338 Drain: &client.Drain{},
339 },
340 }
341 if err := a.Send(drainPkt); err != nil {
342 klog.ErrorS(err, "drain failure", "")
343 }
344 })
345 default:
346 }
347
348 pkt, err := a.Recv()
349 if err != nil {
350 if err == io.EOF {
351 klog.V(2).InfoS("received EOF, exit", "serverID", a.serverID, "agentID", a.agentID)
352 return
353 }
354 if status.Code(err) == codes.Canceled {
355 klog.V(2).InfoS("stream canceled", "serverID", a.serverID, "agentID", a.agentID)
356 } else {
357 klog.ErrorS(err, "could not read stream", "serverID", a.serverID, "agentID", a.agentID)
358 }
359 return
360 }
361
362 if pkt == nil {
363 klog.V(3).InfoS("empty packet received")
364 continue
365 }
366
367 klog.V(5).InfoS("[tracing] recv packet", "type", pkt.Type)
368 switch pkt.Type {
369 case client.PacketType_DIAL_REQ:
370 dialReq := pkt.GetDialRequest()
371 klog.V(3).InfoS("Received DIAL_REQ", "serverID", a.serverID, "agentID", a.agentID, "dialID", dialReq.Random, "dialAddress", dialReq.Address)
372 dialResp := &client.Packet{
373 Type: client.PacketType_DIAL_RSP,
374 Payload: &client.Packet_DialResponse{DialResponse: &client.DialResponse{}},
375 }
376 dialResp.GetDialResponse().Random = dialReq.Random
377
378 connID := atomic.AddInt64(&a.nextConnID, 1)
379 dataCh := make(chan []byte, a.cs.xfrChannelSize)
380 dialDone := make(chan struct{})
381 eConn := &endpointConn{
382 dataCh: dataCh,
383 dialDone: dialDone,
384 warnChLim: a.warnOnChannelLimit,
385 }
386 eConn.cleanFunc = func() {
387 // block on purpose
388 <-dialDone
389 if eConn.conn == nil {
390 // TODO: move this guard lower
391 klog.ErrorS(fmt.Errorf("remote connection is nil"), "could not send CLOSE_RESP to nil connection")
392 return
393 }
394 klog.V(4).InfoS("close connection", "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
395 var closePkt *client.Packet
396 if connID == 0 {
397 closePkt = &client.Packet{
398 Type: client.PacketType_DIAL_CLS,
399 Payload: &client.Packet_CloseDial{CloseDial: &client.CloseDial{}},
400 }
401 closePkt.GetCloseDial().Random = dialReq.Random
402 } else {
403 closePkt = &client.Packet{
404 Type: client.PacketType_CLOSE_RSP,
405 Payload: &client.Packet_CloseResponse{CloseResponse: &client.CloseResponse{}},
406 }
407 closePkt.GetCloseResponse().ConnectID = connID
408 }
409 if err := a.Send(closePkt); err != nil {
410 klog.ErrorS(err, "close response failure", "")
411 }
412 close(dataCh)
413 a.connManager.Delete(connID)
414 if err := eConn.conn.Close(); err != nil {
415 klog.ErrorS(err, "failed to close connection to remote", "dialID", dialReq.Random, "connectionID", connID)
416 }
417 }
418 labels := runpprof.Labels(
419 "agentID", a.agentID,
420 "agentIdentifiers", a.agentIdentifiers,
421 "serverAddress", a.address,
422 "serverID", a.serverID,
423 "dialID", strconv.FormatInt(dialReq.Random, 10),
424 "dialAddress", dialReq.Address,
425 )
426 go runpprof.Do(context.Background(), labels, func(context.Context) {
427 defer close(dialDone)
428 start := time.Now()
429 conn, err := net.DialTimeout(dialReq.Protocol, dialReq.Address, dialTimeout)
430 if err != nil {
431 reason := metrics.DialFailureUnknown
432 if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
433 reason = metrics.DialFailureTimeout
434 }
435 metrics.Metrics.ObserveDialFailure(reason)
436 // Do not log agent errors for remote unavailable.
437 klog.V(1).InfoS("error dialing backend", "error", err, "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
438 dialResp.GetDialResponse().Error = err.Error()
439 if err := a.Send(dialResp); err != nil {
440 klog.ErrorS(err, "could not send DIAL_RSP with error", "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
441 }
442 // Cannot invoke clean up as we have no conn yet.
443 return
444 }
445 metrics.Metrics.ObserveDialLatency(time.Since(start))
446 klog.V(3).InfoS("Endpoint connection established", "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
447 eConn.conn = conn
448 a.connManager.Add(connID, eConn)
449 dialResp.GetDialResponse().ConnectID = connID
450 labels := runpprof.Labels(
451 "agentID", a.agentID,
452 "agentIdentifiers", a.agentIdentifiers,
453 "serverAddress", a.address,
454 "serverID", a.serverID,
455 "connectionID", strconv.FormatInt(connID, 10),
456 "dialAddress", dialReq.Address,
457 )
458 if err := a.Send(dialResp); err != nil {
459 klog.ErrorS(err, "could not send DIAL_RSP", "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
460 // clean-up is normally called from remoteToProxy which we will never invoke.
461 // So we are invoking it here to force the clean-up to occur.
462 // However, cleanup will block until dialDone is closed.
463 // So placing cleanup on its own goroutine to wait for the deferred close(dialDone) to kick in.
464 go runpprof.Do(context.Background(), labels, func(context.Context) { eConn.cleanup() })
465 return
466 }
467 go runpprof.Do(context.Background(), labels, func(context.Context) { a.remoteToProxy(connID, eConn) })
468 go runpprof.Do(context.Background(), labels, func(context.Context) { a.proxyToRemote(connID, eConn) })
469 })
470
471 case client.PacketType_DATA:
472 data := pkt.GetData()
473 klog.V(4).InfoS("received DATA", "connectionID", data.ConnectID)
474 if data.ConnectID == 0 {
475 klog.ErrorS(nil, "Received packet missing ConnectID from frontend", "packetType", "DATA")
476 continue
477 }
478
479 eConn, ok := a.connManager.Get(data.ConnectID)
480 if ok {
481 eConn.send(data.Data)
482 } else {
483 klog.V(2).InfoS("received DATA for unrecognized connection", "connectionID", data.ConnectID)
484 a.Send(&client.Packet{
485 Type: client.PacketType_CLOSE_RSP,
486 Payload: &client.Packet_CloseResponse{
487 CloseResponse: &client.CloseResponse{
488 ConnectID: data.ConnectID,
489 Error: "unrecognized connectID",
490 },
491 },
492 })
493 continue
494 }
495
496 case client.PacketType_CLOSE_REQ:
497 closeReq := pkt.GetCloseRequest()
498 connID := closeReq.ConnectID
499
500 klog.V(4).InfoS("received CLOSE_REQ", "connectionID", connID)
501
502 eConn, ok := a.connManager.Get(connID)
503 if ok {
504 eConn.cleanup()
505 } else {
506 klog.V(4).InfoS("Failed to find connection context for close", "connectionID", connID)
507 resp := &client.Packet{
508 Type: client.PacketType_CLOSE_RSP,
509 Payload: &client.Packet_CloseResponse{CloseResponse: &client.CloseResponse{}},
510 }
511 resp.GetCloseResponse().ConnectID = connID
512 resp.GetCloseResponse().Error = "Unknown connectID"
513 if err := a.Send(resp); err != nil {
514 klog.ErrorS(err, "could not send CLOSE_RSP", err, "connectionID", connID)
515 continue
516 }
517 }
518
519 default:
520 klog.V(5).InfoS("unrecognized packet", "type", pkt)
521 }
522 }
523 }
524
525 func (a *Client) remoteToProxy(connID int64, eConn *endpointConn) {
526 defer func() {
527 if panicInfo := recover(); panicInfo != nil {
528 klog.V(2).InfoS("Exiting remoteToProxy with recovery", "panicInfo", panicInfo, "connectionID", connID)
529 } else {
530 klog.V(4).InfoS("Exiting remoteToProxy", "connectionID", connID)
531 }
532 }()
533 defer eConn.cleanup()
534
535 var buf [1 << 12]byte
536 resp := &client.Packet{
537 Type: client.PacketType_DATA,
538 }
539
540 for {
541 n, err := eConn.conn.Read(buf[:])
542 klog.V(5).InfoS("received data from remote", "bytes", n, "connectionID", connID)
543
544 if err == io.EOF {
545 klog.V(2).InfoS("remote connection EOF", "connectionID", connID)
546 return
547 } else if err != nil {
548 // "use of closed network connection" errors are expected upon receiving CLOSE_REQ
549 // If connID doesn't exist in connManager, we assume the connection was meant to be closed.
550 if _, ok := a.connManager.Get(connID); !ok {
551 klog.V(5).InfoS("reading from a closed connection", "connectionID", connID, "err", err)
552 } else {
553 klog.ErrorS(err, "connection read failure", "connectionID", connID)
554 }
555 return
556 }
557
558 resp.Payload = &client.Packet_Data{Data: &client.Data{
559 Data: buf[:n],
560 ConnectID: connID,
561 }}
562 if err := a.Send(resp); err != nil {
563 klog.ErrorS(err, "could not send DATA", "connectionID", connID)
564 }
565 }
566 }
567
568 func (a *Client) proxyToRemote(connID int64, eConn *endpointConn) {
569 defer func() {
570 if panicInfo := recover(); panicInfo != nil {
571 klog.V(2).InfoS("Exiting proxyToRemote with recovery", "panicInfo", panicInfo, "connectionID", connID)
572 } else {
573 klog.V(4).InfoS("Exiting proxyToRemote", "connectionID", connID)
574 }
575 }()
576 // Not safe to call cleanup here, as cleanup() closes the dataCh
577 // and we are the receiver for the dataCh. Also we now have a later
578 // defer which will block until dataCh is closed.
579 defer func() {
580 // As the read side of the dataCh channel, we cannot close it.
581 // However serve() may be blocked writing to the channel,
582 // so we need to consume the channel until it is closed.
583 discardedPktCount := 0
584 for range eConn.dataCh {
585 // Ignore values as this indicates there was a problem
586 // with the remote connection.
587 discardedPktCount++
588 }
589 if discardedPktCount > 0 {
590 klog.V(2).InfoS("Discard packets while exiting proxyToRemote", "pktCount", discardedPktCount, "connectionID", connID)
591 }
592 }()
593
594 for d := range eConn.dataCh {
595 pos := 0
596 for {
597 n, err := eConn.conn.Write(d[pos:])
598 if err == nil {
599 klog.V(4).InfoS("write to remote", "connectionID", connID, "lastData", n, "dataSize", len(d))
600 break
601 } else if n > 0 {
602 // https://golang.org/pkg/io/#Writer specifies return non nil error if n < len(d)
603 klog.ErrorS(err, "write to remote with failure", "connectionID", connID, "lastData", n)
604 pos += n
605 } else {
606 // "use of closed network connection" errors are expected upon receiving CLOSE_REQ
607 // If connID doesn't exist in connManager, we assume the connection was meant to be closed.
608 if _, ok := a.connManager.Get(connID); !ok {
609 klog.V(5).InfoS("writing to a closed connection", "connectionID", connID, "err", err)
610 } else {
611 klog.ErrorS(err, "conn write failure", "connectionID", connID)
612 }
613
614 return
615 }
616 }
617 }
618 }
619
620 func (a *Client) probe() {
621 for {
622 select {
623 case <-a.stopCh:
624 return
625 case <-time.After(a.probeInterval):
626 if a.conn == nil {
627 continue
628 }
629 // health check
630 if a.conn.GetState() == connectivity.Ready {
631 continue
632 }
633 }
634 klog.V(1).InfoS("Removing client used for server connection", "state", a.conn.GetState(), "serverID", a.serverID)
635 a.cs.RemoveClient(a.serverID)
636 return
637 }
638 }