Debian Codegraph @

pkg/agent/client.go

raw
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 select {
358 case <-a.stopCh:
359 klog.V(5).InfoS("could not read stream because agent client is shutting down", "serverID", a.serverID, "agentID", a.agentID, "err", err)
360 default:
361 // If stopCh is not closed, this is a legitimate, unexpected error.
362 klog.ErrorS(err, "could not read stream", "serverID", a.serverID, "agentID", a.agentID)
363 }
364 }
365 return
366 }
367
368 if pkt == nil {
369 klog.V(3).InfoS("empty packet received")
370 continue
371 }
372
373 klog.V(5).InfoS("[tracing] recv packet", "type", pkt.Type)
374 switch pkt.Type {
375 case client.PacketType_DIAL_REQ:
376 dialReq := pkt.GetDialRequest()
377 klog.V(3).InfoS("Received DIAL_REQ", "serverID", a.serverID, "agentID", a.agentID, "dialID", dialReq.Random, "dialAddress", dialReq.Address)
378 dialResp := &client.Packet{
379 Type: client.PacketType_DIAL_RSP,
380 Payload: &client.Packet_DialResponse{DialResponse: &client.DialResponse{}},
381 }
382 dialResp.GetDialResponse().Random = dialReq.Random
383
384 connID := atomic.AddInt64(&a.nextConnID, 1)
385 dataCh := make(chan []byte, a.cs.xfrChannelSize)
386 dialDone := make(chan struct{})
387 eConn := &endpointConn{
388 dataCh: dataCh,
389 dialDone: dialDone,
390 warnChLim: a.warnOnChannelLimit,
391 }
392 eConn.cleanFunc = func() {
393 // block on purpose
394 <-dialDone
395 if eConn.conn == nil {
396 // TODO: move this guard lower
397 klog.ErrorS(fmt.Errorf("remote connection is nil"), "could not send CLOSE_RESP to nil connection")
398 return
399 }
400 klog.V(4).InfoS("close connection", "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
401 var closePkt *client.Packet
402 if connID == 0 {
403 closePkt = &client.Packet{
404 Type: client.PacketType_DIAL_CLS,
405 Payload: &client.Packet_CloseDial{CloseDial: &client.CloseDial{}},
406 }
407 closePkt.GetCloseDial().Random = dialReq.Random
408 } else {
409 closePkt = &client.Packet{
410 Type: client.PacketType_CLOSE_RSP,
411 Payload: &client.Packet_CloseResponse{CloseResponse: &client.CloseResponse{}},
412 }
413 closePkt.GetCloseResponse().ConnectID = connID
414 }
415 if err := a.Send(closePkt); err != nil {
416 if err == io.EOF {
417 klog.V(4).InfoS("received EOF; connection already closed", "connectionID", connID, "dialID", dialReq.Random, "err", err)
418 } else if _, ok := a.connManager.Get(connID); !ok {
419 klog.V(5).InfoS("connection already closed", "connectionID", connID, "dialID", dialReq.Random, "err", err)
420 } else {
421 klog.ErrorS(err, "close response failure", "connectionID", connID, "dialID", dialReq.Random)
422 }
423 }
424 close(dataCh)
425 a.connManager.Delete(connID)
426 if err := eConn.conn.Close(); err != nil {
427 klog.ErrorS(err, "failed to close connection to remote", "dialID", dialReq.Random, "connectionID", connID)
428 }
429 }
430 labels := runpprof.Labels(
431 "agentID", a.agentID,
432 "agentIdentifiers", a.agentIdentifiers,
433 "serverAddress", a.address,
434 "serverID", a.serverID,
435 "dialID", strconv.FormatInt(dialReq.Random, 10),
436 "dialAddress", dialReq.Address,
437 )
438 go runpprof.Do(context.Background(), labels, func(context.Context) {
439 defer close(dialDone)
440 start := time.Now()
441 conn, err := net.DialTimeout(dialReq.Protocol, dialReq.Address, dialTimeout)
442 if err != nil {
443 reason := metrics.DialFailureUnknown
444 if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
445 reason = metrics.DialFailureTimeout
446 }
447 metrics.Metrics.ObserveDialFailure(reason)
448 // Do not log agent errors for remote unavailable.
449 klog.V(1).InfoS("error dialing backend", "error", err, "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
450 dialResp.GetDialResponse().Error = err.Error()
451 if err := a.Send(dialResp); err != nil {
452 klog.ErrorS(err, "could not send DIAL_RSP with error", "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
453 }
454 // Cannot invoke clean up as we have no conn yet.
455 return
456 }
457 metrics.Metrics.ObserveDialLatency(time.Since(start))
458 klog.V(3).InfoS("Endpoint connection established", "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
459 eConn.conn = conn
460 a.connManager.Add(connID, eConn)
461 dialResp.GetDialResponse().ConnectID = connID
462 labels := runpprof.Labels(
463 "agentID", a.agentID,
464 "agentIdentifiers", a.agentIdentifiers,
465 "serverAddress", a.address,
466 "serverID", a.serverID,
467 "connectionID", strconv.FormatInt(connID, 10),
468 "dialAddress", dialReq.Address,
469 )
470 if err := a.Send(dialResp); err != nil {
471 klog.ErrorS(err, "could not send DIAL_RSP", "dialID", dialReq.Random, "connectionID", connID, "dialAddress", dialReq.Address)
472 // clean-up is normally called from remoteToProxy which we will never invoke.
473 // So we are invoking it here to force the clean-up to occur.
474 // However, cleanup will block until dialDone is closed.
475 // So placing cleanup on its own goroutine to wait for the deferred close(dialDone) to kick in.
476 go runpprof.Do(context.Background(), labels, func(context.Context) { eConn.cleanup() })
477 return
478 }
479 go runpprof.Do(context.Background(), labels, func(context.Context) { a.remoteToProxy(connID, eConn) })
480 go runpprof.Do(context.Background(), labels, func(context.Context) { a.proxyToRemote(connID, eConn) })
481 })
482
483 case client.PacketType_DATA:
484 data := pkt.GetData()
485 klog.V(4).InfoS("received DATA", "connectionID", data.ConnectID)
486 if data.ConnectID == 0 {
487 klog.ErrorS(nil, "Received packet missing ConnectID from frontend", "packetType", "DATA")
488 continue
489 }
490
491 eConn, ok := a.connManager.Get(data.ConnectID)
492 if ok {
493 eConn.send(data.Data)
494 } else {
495 klog.V(2).InfoS("received DATA for unrecognized connection", "connectionID", data.ConnectID)
496 a.Send(&client.Packet{
497 Type: client.PacketType_CLOSE_RSP,
498 Payload: &client.Packet_CloseResponse{
499 CloseResponse: &client.CloseResponse{
500 ConnectID: data.ConnectID,
501 Error: "unrecognized connectID",
502 },
503 },
504 })
505 continue
506 }
507
508 case client.PacketType_CLOSE_REQ:
509 closeReq := pkt.GetCloseRequest()
510 connID := closeReq.ConnectID
511
512 klog.V(4).InfoS("received CLOSE_REQ", "connectionID", connID)
513
514 eConn, ok := a.connManager.Get(connID)
515 if ok {
516 eConn.cleanup()
517 } else {
518 klog.V(4).InfoS("Failed to find connection context for close", "connectionID", connID)
519 resp := &client.Packet{
520 Type: client.PacketType_CLOSE_RSP,
521 Payload: &client.Packet_CloseResponse{CloseResponse: &client.CloseResponse{}},
522 }
523 resp.GetCloseResponse().ConnectID = connID
524 resp.GetCloseResponse().Error = "Unknown connectID"
525 if err := a.Send(resp); err != nil {
526 klog.ErrorS(err, "could not send CLOSE_RSP", err, "connectionID", connID)
527 continue
528 }
529 }
530
531 default:
532 klog.V(5).InfoS("unrecognized packet", "type", pkt)
533 }
534 }
535 }
536
537 func (a *Client) remoteToProxy(connID int64, eConn *endpointConn) {
538 defer func() {
539 if panicInfo := recover(); panicInfo != nil {
540 klog.V(2).InfoS("Exiting remoteToProxy with recovery", "panicInfo", panicInfo, "connectionID", connID)
541 } else {
542 klog.V(4).InfoS("Exiting remoteToProxy", "connectionID", connID)
543 }
544 }()
545 defer eConn.cleanup()
546
547 var buf [1 << 12]byte
548 resp := &client.Packet{
549 Type: client.PacketType_DATA,
550 }
551
552 for {
553 n, err := eConn.conn.Read(buf[:])
554 klog.V(5).InfoS("received data from remote", "bytes", n, "connectionID", connID)
555
556 if err == io.EOF {
557 klog.V(2).InfoS("remote connection EOF", "connectionID", connID)
558 return
559 } else if err != nil {
560 // "use of closed network connection" errors are expected upon receiving CLOSE_REQ
561 // If connID doesn't exist in connManager, we assume the connection was meant to be closed.
562 if _, ok := a.connManager.Get(connID); !ok {
563 klog.V(5).InfoS("reading from a closed connection", "connectionID", connID, "err", err)
564 } else {
565 klog.ErrorS(err, "connection read failure", "connectionID", connID)
566 }
567 return
568 }
569
570 resp.Payload = &client.Packet_Data{Data: &client.Data{
571 Data: buf[:n],
572 ConnectID: connID,
573 }}
574 if err := a.Send(resp); err != nil {
575 klog.ErrorS(err, "could not send DATA", "connectionID", connID)
576 }
577 }
578 }
579
580 func (a *Client) proxyToRemote(connID int64, eConn *endpointConn) {
581 defer func() {
582 if panicInfo := recover(); panicInfo != nil {
583 klog.V(2).InfoS("Exiting proxyToRemote with recovery", "panicInfo", panicInfo, "connectionID", connID)
584 } else {
585 klog.V(4).InfoS("Exiting proxyToRemote", "connectionID", connID)
586 }
587 }()
588 // Not safe to call cleanup here, as cleanup() closes the dataCh
589 // and we are the receiver for the dataCh. Also we now have a later
590 // defer which will block until dataCh is closed.
591 defer func() {
592 // As the read side of the dataCh channel, we cannot close it.
593 // However serve() may be blocked writing to the channel,
594 // so we need to consume the channel until it is closed.
595 discardedPktCount := 0
596 for range eConn.dataCh {
597 // Ignore values as this indicates there was a problem
598 // with the remote connection.
599 discardedPktCount++
600 }
601 if discardedPktCount > 0 {
602 klog.V(2).InfoS("Discard packets while exiting proxyToRemote", "pktCount", discardedPktCount, "connectionID", connID)
603 }
604 }()
605
606 for d := range eConn.dataCh {
607 pos := 0
608 for {
609 n, err := eConn.conn.Write(d[pos:])
610 if err == nil {
611 klog.V(4).InfoS("write to remote", "connectionID", connID, "lastData", n, "dataSize", len(d))
612 break
613 } else if n > 0 {
614 // https://golang.org/pkg/io/#Writer specifies return non nil error if n < len(d)
615 klog.ErrorS(err, "write to remote with failure", "connectionID", connID, "lastData", n)
616 pos += n
617 } else {
618 // "use of closed network connection" errors are expected upon receiving CLOSE_REQ
619 // If connID doesn't exist in connManager, we assume the connection was meant to be closed.
620 if _, ok := a.connManager.Get(connID); !ok {
621 klog.V(5).InfoS("writing to a closed connection", "connectionID", connID, "err", err)
622 } else {
623 klog.ErrorS(err, "conn write failure", "connectionID", connID)
624 }
625
626 return
627 }
628 }
629 }
630 }
631
632 func (a *Client) probe() {
633 for {
634 select {
635 case <-a.stopCh:
636 return
637 case <-time.After(a.probeInterval):
638 if a.conn == nil {
639 continue
640 }
641 // health check
642 if a.conn.GetState() == connectivity.Ready {
643 continue
644 }
645 }
646 klog.V(1).InfoS("Removing client used for server connection", "state", a.conn.GetState(), "serverID", a.serverID)
647 a.cs.RemoveClient(a.serverID)
648 return
649 }
650 }