Debian Codegraph @

pkg/server/server.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 server
18
19 import (
20 "bytes"
21 "context"
22 "errors"
23 "fmt"
24 "io"
25 "net/http"
26 runpprof "runtime/pprof"
27 "strconv"
28 "strings"
29 "sync"
30 "time"
31
32 "github.com/google/uuid"
33 "google.golang.org/grpc/codes"
34 "google.golang.org/grpc/metadata"
35 "google.golang.org/grpc/status"
36 authv1 "k8s.io/api/authentication/v1"
37 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
38 "k8s.io/client-go/kubernetes"
39 "k8s.io/klog/v2"
40
41 commonmetrics "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics"
42 "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client"
43 "sigs.k8s.io/apiserver-network-proxy/pkg/server/metrics"
44 "sigs.k8s.io/apiserver-network-proxy/pkg/server/proxystrategies"
45 "sigs.k8s.io/apiserver-network-proxy/pkg/util"
46 "sigs.k8s.io/apiserver-network-proxy/proto/agent"
47 "sigs.k8s.io/apiserver-network-proxy/proto/header"
48 )
49
50 type key int
51
52 type GrpcFrontend struct {
53 stream client.ProxyService_ProxyServer
54 streamUID string
55 sendLock sync.Mutex
56 recvLock sync.Mutex
57 }
58
59 func (g *GrpcFrontend) Send(pkt *client.Packet) error {
60 g.sendLock.Lock()
61 defer g.sendLock.Unlock()
62
63 const segment = commonmetrics.SegmentToClient
64 metrics.Metrics.ObservePacket(segment, pkt.Type)
65 err := g.stream.Send(pkt)
66 if err != nil {
67 metrics.Metrics.ObserveStreamError(segment, err, pkt.Type)
68 }
69 return err
70 }
71
72 func (g *GrpcFrontend) Recv() (*client.Packet, error) {
73 g.recvLock.Lock()
74 defer g.recvLock.Unlock()
75
76 const segment = commonmetrics.SegmentFromClient
77 pkt, err := g.stream.Recv()
78 if err != nil {
79 if err != io.EOF {
80 metrics.Metrics.ObserveStreamErrorNoPacket(segment, err)
81 }
82 return nil, err
83 }
84 metrics.Metrics.ObservePacket(segment, pkt.Type)
85 return pkt, nil
86 }
87
88 const (
89 ModeGRPC = "grpc"
90 ModeHTTPConnect = "http-connect"
91 )
92
93 const defaultBackendDialTimeout = 0
94
95 var errBackendDialTimeout = errors.New("timed out waiting for backend dial")
96
97 type ProxyClientConnection struct {
98 Mode string
99 HTTP io.ReadWriter
100 frontend *GrpcFrontend
101 CloseHTTP func() error
102 connected chan struct{}
103 dialID int64
104 connectID int64
105 agentID string
106 start time.Time
107 backend *Backend
108 dialAddress string // cached for logging
109 }
110
111 const (
112 destHostKey key = iota
113 )
114
115 // mapDialErrorToHTTPStatus maps common TCP/network error strings to appropriate HTTP status codes
116 func mapDialErrorToHTTPStatus(errStr string) int {
117 // Convert to lowercase for case-insensitive matching
118 errLower := strings.ToLower(errStr)
119
120 // Check each error pattern and return appropriate status code
121 switch {
122 // Timeouts - backend didn't respond in time -> 504 Gateway Timeout
123 case strings.Contains(errLower, "i/o timeout"),
124 strings.Contains(errLower, "deadline exceeded"),
125 strings.Contains(errLower, "context deadline exceeded"),
126 strings.Contains(errLower, "timeout"):
127 return 504
128
129 // Resource exhaustion errors -> 503 Service Unavailable
130 case strings.Contains(errLower, "too many open files"),
131 strings.Contains(errLower, "socket: too many open files"):
132 return 503
133
134 // Connection errors -> 502 Bad Gateway
135 case strings.Contains(errLower, "connection refused"),
136 strings.Contains(errLower, "connection reset by peer"),
137 strings.Contains(errLower, "broken pipe"),
138 strings.Contains(errLower, "network is unreachable"),
139 strings.Contains(errLower, "no route to host"),
140 strings.Contains(errLower, "host is unreachable"),
141 strings.Contains(errLower, "network is down"):
142 return 502
143
144 // DNS resolution failures -> 502 Bad Gateway
145 case strings.Contains(errLower, "no such host"),
146 strings.Contains(errLower, "name resolution"),
147 strings.Contains(errLower, "lookup") && strings.Contains(errLower, "no such host"):
148 return 502
149
150 // TLS/SSL errors -> 502 Bad Gateway
151 case strings.Contains(errLower, "tls"),
152 strings.Contains(errLower, "ssl"),
153 strings.Contains(errLower, "certificate"):
154 return 502
155
156 // Default to 502 Bad Gateway for unknown proxy errors
157 default:
158 return 502
159 }
160 }
161
162 func (c *ProxyClientConnection) send(pkt *client.Packet) error {
163 defer func(start time.Time) { metrics.Metrics.ObserveFrontendWriteLatency(time.Since(start)) }(time.Now())
164 if c.Mode == ModeGRPC {
165 return c.frontend.Send(pkt)
166 }
167 if c.Mode == ModeHTTPConnect {
168 if pkt.Type == client.PacketType_CLOSE_RSP {
169 return c.CloseHTTP()
170 } else if pkt.Type == client.PacketType_DIAL_CLS {
171 return c.CloseHTTP()
172 } else if pkt.Type == client.PacketType_DATA {
173 _, err := c.HTTP.Write(pkt.GetData().Data)
174 return err
175 } else if pkt.Type == client.PacketType_DIAL_RSP {
176 dialErr := pkt.GetDialResponse().Error
177 if dialErr != "" {
178 // // Map the error to appropriate HTTP status code
179 statusCode := mapDialErrorToHTTPStatus(dialErr)
180 statusText := http.StatusText(statusCode)
181 body := bytes.NewBufferString(dialErr)
182 t := http.Response{
183 StatusCode: statusCode,
184 Status: fmt.Sprintf("%d %s", statusCode, statusText),
185 Body: io.NopCloser(body),
186 Header: http.Header{
187 "Content-Type": []string{"text/plain; charset=utf-8"},
188 },
189 Proto: "HTTP/1.1",
190 ProtoMinor: 1,
191 ProtoMajor: 1,
192 }
193
194 t.Write(c.HTTP)
195 return c.CloseHTTP()
196 }
197 return nil
198 }
199 return fmt.Errorf("attempt to send via unrecognized connection type %v", pkt.Type)
200 }
201 return fmt.Errorf("attempt to send via unrecognized connection mode %q", c.Mode)
202 }
203
204 func NewPendingDialManager() *PendingDialManager {
205 return &PendingDialManager{
206 pendingDial: make(map[int64]*ProxyClientConnection),
207 }
208 }
209
210 type PendingDialManager struct {
211 mu sync.RWMutex
212 pendingDial map[int64]*ProxyClientConnection
213 }
214
215 func (pm *PendingDialManager) Add(random int64, clientConn *ProxyClientConnection) {
216 pm.mu.Lock()
217 defer pm.mu.Unlock()
218 pm.pendingDial[random] = clientConn
219 metrics.Metrics.SetPendingDialCount(len(pm.pendingDial))
220 }
221
222 func (pm *PendingDialManager) Remove(random int64) *ProxyClientConnection {
223 pm.mu.Lock()
224 defer pm.mu.Unlock()
225 pd := pm.pendingDial[random]
226 delete(pm.pendingDial, random)
227 metrics.Metrics.SetPendingDialCount(len(pm.pendingDial))
228 return pd
229 }
230
231 // removeForStream removes and returns all pending ProxyClientConnection associated with a
232 // given Proxy gRPC connection (expected to be at most 1 while konnectivity-client API gives
233 // single-use tunnels).
234 func (pm *PendingDialManager) removeForStream(streamUID string) []*ProxyClientConnection {
235 var ret []*ProxyClientConnection
236 if streamUID == "" {
237 return ret
238 }
239 pm.mu.Lock()
240 defer pm.mu.Unlock()
241 for dialID, frontend := range pm.pendingDial {
242 if frontend.frontend == nil {
243 continue
244 }
245 if frontend.frontend.streamUID == streamUID {
246 delete(pm.pendingDial, dialID)
247 ret = append(ret, frontend)
248 }
249 }
250 return ret
251 }
252
253 // ProxyServer
254 type ProxyServer struct {
255 // BackendManagers contains a list of BackendManagers
256 BackendManagers []BackendManager
257
258 // Readiness reports if the proxy server is ready, i.e., if the proxy
259 // server has connections to proxy agents (backends). Note that the
260 // proxy server does not check the healthiness of the connections,
261 // though the proxy agents do, so this readiness check might report
262 // ready but there is no healthy connection.
263 Readiness ReadinessManager
264
265 // fmu protects established.
266 fmu sync.RWMutex
267 // conn = Frontend[agentID][connID]
268 established map[string]map[int64]*ProxyClientConnection
269
270 PendingDial *PendingDialManager
271
272 serverID string // unique ID of this server
273 serverCount int // Number of proxy server instances, should be 1 unless it is a HA server.
274
275 // agent authentication
276 AgentAuthenticationOptions *AgentTokenAuthenticationOptions
277
278 // TODO: move strategies into BackendStorage
279 proxyStrategies []proxystrategies.ProxyStrategy
280 xfrChannelSize int
281
282 backendDialTimeout time.Duration
283 }
284
285 // AgentTokenAuthenticationOptions contains list of parameters required for agent token based authentication
286 type AgentTokenAuthenticationOptions struct {
287 Enabled bool
288 AgentNamespace string
289 AgentServiceAccount string
290 AuthenticationAudience string
291 KubernetesClient kubernetes.Interface
292 }
293
294 var _ agent.AgentServiceServer = &ProxyServer{}
295
296 var _ client.ProxyServiceServer = &ProxyServer{}
297
298 func genContext(proxyStrategies []proxystrategies.ProxyStrategy, reqHost string) context.Context {
299 ctx := context.Background()
300 for _, ps := range proxyStrategies {
301 switch ps {
302 case proxystrategies.ProxyStrategyDestHost:
303 addr := util.RemovePortFromHost(reqHost)
304 ctx = context.WithValue(ctx, destHostKey, addr)
305 }
306 }
307 return ctx
308 }
309
310 func (s *ProxyServer) getBackend(reqHost string) (*Backend, error) {
311 ctx := genContext(s.proxyStrategies, reqHost)
312 for _, bm := range s.BackendManagers {
313 be, err := bm.Backend(ctx)
314 if err == nil {
315 return be, nil
316 }
317 if ignoreNotFound(err) != nil {
318 // if can't find a backend through current BackendManager, move on
319 // to the next one
320 return nil, err
321 }
322 }
323 return nil, &ErrNotFound{}
324 }
325
326 func (s *ProxyServer) sendDialRequestToBackend(backend *Backend, pkt *client.Packet) error {
327 timeout := s.backendDialTimeout
328 if timeout <= 0 {
329 return backend.Send(pkt)
330 }
331
332 errCh := make(chan error, 1)
333 go func() {
334 errCh <- backend.Send(pkt)
335 }()
336
337 timer := time.NewTimer(timeout)
338 defer timer.Stop()
339
340 ctx := backend.Context()
341 select {
342 case err := <-errCh:
343 return err
344 case <-ctx.Done():
345 return ctx.Err()
346 case <-timer.C:
347 s.retireBackend(backend, "backend dial request send timed out")
348 return errBackendDialTimeout
349 }
350 }
351
352 func (s *ProxyServer) startPendingDialTimeout(random int64, backend *Backend, frontend *GrpcFrontend) {
353 timeout := s.backendDialTimeout
354 if timeout <= 0 {
355 return
356 }
357
358 go func() {
359 timer := time.NewTimer(timeout)
360 defer timer.Stop()
361
362 select {
363 case <-timer.C:
364 if s.PendingDial.Remove(random) == nil {
365 return
366 }
367 metrics.Metrics.ObserveDialFailure(metrics.DialFailureBackendDialTimeout)
368 resp := &client.Packet{
369 Type: client.PacketType_DIAL_RSP,
370 Payload: &client.Packet_DialResponse{
371 DialResponse: &client.DialResponse{
372 Random: random,
373 Error: errBackendDialTimeout.Error(),
374 },
375 },
376 }
377 if err := frontend.Send(resp); err != nil {
378 klog.V(5).InfoS("Failed to send DIAL_RSP for backend dial timeout", "error", err, "dialID", random)
379 }
380 case <-backend.Context().Done():
381 }
382 }()
383 }
384
385 func (s *ProxyServer) addBackend(backend *Backend) {
386 // TODO: refactor BackendStorage to acquire lock once, not up to 3 times.
387 for _, bm := range s.BackendManagers {
388 bm.AddBackend(backend)
389 }
390 }
391
392 func (s *ProxyServer) removeBackend(backend *Backend) {
393 for _, bm := range s.BackendManagers {
394 bm.RemoveBackend(backend)
395 }
396 }
397
398 func (s *ProxyServer) retireBackend(backend *Backend, reason string) {
399 backend.Retire()
400 klog.V(2).InfoS("Retire backend connection", "agentID", backend.GetAgentID(), "reason", reason)
401 s.removeBackend(backend)
402 }
403
404 func (s *ProxyServer) addEstablished(agentID string, connID int64, p *ProxyClientConnection) {
405 s.fmu.Lock()
406 defer s.fmu.Unlock()
407 if _, ok := s.established[agentID]; !ok {
408 s.established[agentID] = make(map[int64]*ProxyClientConnection)
409 }
410 s.established[agentID][connID] = p
411
412 metrics.Metrics.SetEstablishedConnCount(s.getCount(s.established))
413 }
414
415 func (s *ProxyServer) removeEstablished(agentID string, connID int64) *ProxyClientConnection {
416 var ret *ProxyClientConnection
417 s.fmu.Lock()
418 defer s.fmu.Unlock()
419 conns, ok := s.established[agentID]
420 if !ok {
421 return nil
422 }
423 if ret, ok = conns[connID]; !ok {
424 return nil
425 }
426 delete(s.established[agentID], connID)
427 if len(s.established[agentID]) == 0 {
428 delete(s.established, agentID)
429 }
430 metrics.Metrics.SetEstablishedConnCount(s.getCount(s.established))
431 return ret
432 }
433
434 func (s *ProxyServer) getFrontend(agentID string, connID int64) (*ProxyClientConnection, error) {
435 s.fmu.RLock()
436 defer s.fmu.RUnlock()
437 conns, ok := s.established[agentID]
438 if !ok {
439 return nil, fmt.Errorf("can't find agentID %s in the established", agentID)
440 }
441 conn, ok := conns[connID]
442 if !ok {
443 return nil, fmt.Errorf("can't find connID %d in the established[%s]", connID, agentID)
444 }
445 return conn, nil
446 }
447
448 func (s *ProxyServer) removeEstablishedForBackendConn(agentID string, backend *Backend) ([]*ProxyClientConnection, error) {
449 var ret []*ProxyClientConnection
450 if backend == nil {
451 return ret, nil
452 }
453 s.fmu.Lock()
454 defer s.fmu.Unlock()
455 established, ok := s.established[agentID]
456 if !ok {
457 return nil, fmt.Errorf("can't find agentID %s in the established", agentID)
458 }
459 for _, frontend := range established {
460 if frontend.backend == backend {
461 delete(s.established, agentID)
462 ret = append(ret, frontend)
463 }
464 }
465
466 metrics.Metrics.SetEstablishedConnCount(s.getCount(s.established))
467 return ret, nil
468 }
469
470 func (s *ProxyServer) getCount(established map[string](map[int64]*ProxyClientConnection)) int {
471 count := 0
472 for _, frontend := range established {
473 count = count + len(frontend)
474 }
475 return count
476 }
477
478 // removeEstablishedForStream removes and returns all established ProxyClientConnection associated with a given
479 // Proxy gRPC connection (expected to be at most 1 while konnectivity-client API gives single-use
480 // tunnels).
481 func (s *ProxyServer) removeEstablishedForStream(streamUID string) []*ProxyClientConnection {
482 var ret []*ProxyClientConnection
483 if streamUID == "" {
484 return ret
485 }
486 s.fmu.Lock()
487 defer s.fmu.Unlock()
488 for agentID, established := range s.established {
489 for connID, frontend := range established {
490 if frontend.frontend == nil {
491 continue
492 }
493 if frontend.frontend.streamUID == streamUID {
494 delete(established, connID)
495 ret = append(ret, frontend)
496 }
497 }
498 if len(established) == 0 {
499 delete(s.established, agentID)
500 }
501 }
502 return ret
503 }
504
505 // NewProxyServer creates a new ProxyServer instance
506 func NewProxyServer(serverID string, proxyStrategies []proxystrategies.ProxyStrategy, serverCount int, agentAuthenticationOptions *AgentTokenAuthenticationOptions, channelSize int) *ProxyServer {
507 var bms []BackendManager
508 for _, ps := range proxyStrategies {
509 switch ps {
510 case proxystrategies.ProxyStrategyDestHost:
511 bms = append(bms, NewDestHostBackendManager())
512 case proxystrategies.ProxyStrategyDefault:
513 bms = append(bms, NewDefaultBackendManager())
514 case proxystrategies.ProxyStrategyDefaultRoute:
515 bms = append(bms, NewDefaultRouteBackendManager())
516 default:
517 klog.ErrorS(nil, "Unknown proxy strategy", "strategy", ps)
518 }
519 }
520
521 return &ProxyServer{
522 established: make(map[string](map[int64]*ProxyClientConnection)),
523 PendingDial: NewPendingDialManager(),
524 serverID: serverID,
525 serverCount: serverCount,
526 BackendManagers: bms,
527 AgentAuthenticationOptions: agentAuthenticationOptions,
528 // use the first backend-manager as the Readiness Manager
529 Readiness: bms[0],
530 proxyStrategies: proxyStrategies,
531 xfrChannelSize: channelSize,
532 backendDialTimeout: defaultBackendDialTimeout,
533 }
534 }
535
536 func (s *ProxyServer) SetBackendDialTimeout(timeout time.Duration) {
537 s.backendDialTimeout = timeout
538 }
539
540 // Proxy handles incoming streams from gRPC frontend.
541 func (s *ProxyServer) Proxy(stream client.ProxyService_ProxyServer) error {
542 metrics.Metrics.ConnectionInc(metrics.Proxy)
543 defer metrics.Metrics.ConnectionDec(metrics.Proxy)
544
545 md, ok := metadata.FromIncomingContext(stream.Context())
546 if !ok {
547 return fmt.Errorf("failed to get context")
548 }
549 userAgent := md.Get(header.UserAgent)
550 streamUID := uuid.New().String()
551 klog.V(5).InfoS("Proxy request from client", "userAgent", userAgent, "serverID", s.serverID, "streamUID", streamUID)
552
553 recvCh := make(chan *client.Packet, s.xfrChannelSize)
554 stopCh := make(chan error, 1)
555
556 frontend := GrpcFrontend{
557 stream: stream,
558 streamUID: streamUID,
559 }
560
561 defer func() {
562 // The frontend stream and goroutines are completely shut down, so we will never get a
563 // subsequent close message from the frontend. This can happen for several reasons, such as
564 // stream canceled. Clean any lingering tunnel connections to avoid resource leaks.
565 for _, p := range s.PendingDial.removeForStream(streamUID) {
566 klog.V(2).InfoS("frontend stream shutdown, cleaning dial", "dialID", p.dialID)
567 // TODO: add agent support to handle this
568 s.sendBackendDialClose(p.backend, p.dialID, "frontend stream shutdown")
569 }
570 for _, f := range s.removeEstablishedForStream(streamUID) {
571 klog.V(2).InfoS("frontend stream shutdown, cleaning frontend", "connectionID", f.connectID, "dialID", f.dialID)
572 s.sendBackendClose(f.backend, f.connectID, f.dialID, "frontend stream shutdown")
573 }
574 }()
575
576 labels := runpprof.Labels(
577 "serverCount", strconv.Itoa(s.serverCount),
578 "userAgent", strings.Join(userAgent, ", "),
579 )
580 // Start goroutine to receive packets from frontend and push to recvCh
581 go runpprof.Do(context.Background(), labels, func(context.Context) { s.readFrontendToChannel(&frontend, userAgent, recvCh, stopCh) })
582
583 s.serveRecvFrontend(&frontend, recvCh)
584
585 return <-stopCh
586 }
587
588 func (s *ProxyServer) readFrontendToChannel(frontend *GrpcFrontend, userAgent []string, recvCh chan *client.Packet, stopCh chan error) {
589 defer close(stopCh)
590 defer close(recvCh)
591
592 for {
593 in, err := frontend.Recv()
594 if err == io.EOF {
595 klog.V(2).InfoS("Receive stream from frontend closed", "userAgent", userAgent)
596 return
597 }
598 if err != nil {
599 if status.Code(err) == codes.Canceled {
600 klog.V(2).InfoS("Stream read from frontend cancelled", "userAgent", userAgent)
601 } else {
602 klog.ErrorS(err, "Stream read from frontend failure", "userAgent", userAgent)
603 }
604 stopCh <- err
605 return
606 }
607
608 select {
609 case recvCh <- in: // Send didn't block, carry on.
610 default: // Send blocked; record it and try again.
611 klog.V(2).InfoS("Receive channel from frontend is full", "userAgent", userAgent)
612 fullRecvChannelMetric := metrics.Metrics.FullRecvChannel(metrics.Proxy)
613 fullRecvChannelMetric.Inc()
614 recvCh <- in
615 fullRecvChannelMetric.Dec()
616 }
617 }
618 }
619
620 func (s *ProxyServer) serveRecvFrontend(frontend *GrpcFrontend, recvCh <-chan *client.Packet) {
621 klog.V(5).Infoln("start serving frontend stream")
622
623 var firstConnID int64
624 // The first packet should be a DIAL_REQ, we will randomly get a
625 // backend from the BackendManger then.
626 // TODO: either add agentID to protocol (DATA, CLOSE_RSP, etc) or replace {agentID,
627 // connectionID} with a simpler key (#462).
628 var backend *Backend
629 var err error
630
631 defer func() {
632 klog.V(5).InfoS("Close frontend streaming", "connectionID", firstConnID, "streamUID", frontend.streamUID)
633 if backend == nil {
634 klog.V(2).InfoS("Streaming closed before backend initialized")
635 }
636
637 // As the read side of the recvCh channel, we cannot close it.
638 // However readFrontendToChannel() may be blocked writing to the channel,
639 // so we need to consume the channel until it is closed.
640 discardedPktCount := 0
641 for range recvCh {
642 // Ignore values as this indicates there was a problem
643 // with the remote connection.
644 discardedPktCount++
645 }
646 if discardedPktCount > 0 {
647 klog.V(2).InfoS("Discard packets while exiting serveRecvFrontend", "pktCount", discardedPktCount, "connectionID", firstConnID)
648 }
649 }()
650
651 for pkt := range recvCh {
652 switch pkt.Type {
653 case client.PacketType_DIAL_REQ:
654 random := pkt.GetDialRequest().Random
655 address := pkt.GetDialRequest().Address
656 klog.V(3).InfoS("Received DIAL_REQ", "dialID", random, "dialAddress", address)
657 // TODO: if we track what agent has historically served
658 // the address, then we can send the Dial_REQ to the
659 // same agent. That way we save the agent from creating
660 // a new connection to the address.
661 backend, err = s.getBackend(address)
662 if err != nil {
663 klog.ErrorS(err, "Failed to get a backend", "dialID", random)
664 metrics.Metrics.ObserveDialFailure(metrics.DialFailureNoAgent)
665
666 resp := &client.Packet{
667 Type: client.PacketType_DIAL_RSP,
668 Payload: &client.Packet_DialResponse{
669 DialResponse: &client.DialResponse{
670 Random: random,
671 Error: err.Error(),
672 },
673 },
674 }
675 if err := frontend.Send(resp); err != nil {
676 klog.V(5).InfoS("Failed to send DIAL_RSP for no backend", "error", err, "dialID", random)
677 }
678 // The Dial is failing; no reason to keep this goroutine.
679 return
680 }
681 s.PendingDial.Add(
682 random,
683 &ProxyClientConnection{
684 Mode: "grpc",
685 frontend: frontend,
686 dialID: random,
687 connected: make(chan struct{}),
688 start: time.Now(),
689 backend: backend,
690 dialAddress: address,
691 })
692 if err := s.sendDialRequestToBackend(backend, pkt); err != nil {
693 klog.ErrorS(err, "DIAL_REQ to Backend failed", "dialID", random)
694 if s.PendingDial.Remove(random) != nil {
695 reason := metrics.DialFailureBackendClose
696 if errors.Is(err, errBackendDialTimeout) {
697 reason = metrics.DialFailureBackendDialTimeout
698 }
699 metrics.Metrics.ObserveDialFailure(reason)
700 }
701 resp := &client.Packet{
702 Type: client.PacketType_DIAL_RSP,
703 Payload: &client.Packet_DialResponse{
704 DialResponse: &client.DialResponse{
705 Random: random,
706 Error: err.Error(),
707 },
708 },
709 }
710 if err := frontend.Send(resp); err != nil {
711 klog.V(5).InfoS("Failed to send DIAL_RSP for backend send failure", "error", err, "dialID", random)
712 }
713 return
714 }
715 klog.V(5).InfoS("DIAL_REQ sent to backend", "dialID", random)
716 s.startPendingDialTimeout(random, backend, frontend)
717
718 case client.PacketType_CLOSE_REQ:
719 connID := pkt.GetCloseRequest().ConnectID
720 klog.V(5).InfoS("Received CLOSE_REQ", "connectionID", connID)
721 if backend == nil {
722 klog.V(2).InfoS("Backend has not been initialized for this connection", "connectionID", connID)
723 s.sendFrontendClose(frontend, connID, "backend uninitialized")
724 continue
725 }
726 if err := backend.Send(pkt); err != nil {
727 // TODO: retry with other backends connecting to this agent.
728 klog.ErrorS(err, "CLOSE_REQ to Backend failed", "connectionID", connID)
729 s.sendFrontendClose(frontend, connID, "CLOSE_REQ to backend failed")
730 } else {
731 klog.V(5).InfoS("CLOSE_REQ sent to backend", "connectionID", connID)
732 }
733 klog.V(3).InfoS("Closing frontend streaming per CLOSE_REQ", "connectionID", connID)
734 return
735
736 case client.PacketType_DIAL_CLS:
737 random := pkt.GetCloseDial().Random
738 klog.V(5).InfoS("Received DIAL_CLOSE", "dialID", random)
739 // Currently not worrying about backend as we do not have an established connection,
740 if pd := s.PendingDial.Remove(random); pd != nil {
741 klog.ErrorS(nil, "Dial cancelled (DIAL_CLS) by frontend",
742 "dialID", random,
743 "dialAddress", pd.dialAddress,
744 "dialDuration", time.Since(pd.start),
745 )
746 metrics.Metrics.ObserveDialFailure(metrics.DialFailureFrontendClose)
747 } else {
748 // TODO: Fix the leaked connection due to race (client cancels a pending dial but
749 // server has completed the dial).
750 klog.ErrorS(nil, "Unrecognized dial cancelled (DIAL_CLS) by frontend", "dialID", random)
751 }
752
753 case client.PacketType_DATA:
754 connID := pkt.GetData().ConnectID
755 data := pkt.GetData().Data
756 klog.V(5).InfoS("Received data from connection", "bytes", len(data), "connectionID", connID)
757 if backend == nil {
758 klog.V(2).InfoS("Backend has not been initialized for this connection", "connectionID", connID)
759 s.sendFrontendClose(frontend, connID, "backend not initialized")
760 return
761 }
762
763 if connID == 0 {
764 klog.ErrorS(nil, "Received packet missing ConnectID from frontend", "packetType", "DATA")
765 continue
766 }
767 if firstConnID == 0 {
768 firstConnID = connID
769 } else if firstConnID != connID {
770 klog.ErrorS(nil, "Data does not match first connection id", "firstConnectionID", firstConnID, "connectionID", connID)
771 // Something went very wrong if we get here. Close both connections to avoid leaks.
772 s.sendBackendClose(backend, connID, 0, "mismatched connection IDs")
773 s.sendBackendClose(backend, firstConnID, 0, "mismatched connection IDs")
774 s.sendFrontendClose(frontend, connID, "mismatched connection IDs")
775 s.sendFrontendClose(frontend, firstConnID, "mismatched connection IDs")
776 return
777 }
778 if err := backend.Send(pkt); err != nil {
779 // TODO: retry with other backends connecting to this agent.
780 klog.ErrorS(err, "DATA to Backend failed", "connectionID", connID)
781 continue
782 }
783 klog.V(5).Infoln("DATA sent to Backend")
784
785 default:
786 klog.V(5).InfoS("Ignoring unrecognized packet from frontend",
787 "type", pkt.Type, "connectionID", firstConnID)
788 }
789 }
790 }
791
792 func (s *ProxyServer) validateAuthToken(ctx context.Context, token string) (username string, err error) {
793 trReq := &authv1.TokenReview{
794 Spec: authv1.TokenReviewSpec{
795 Token: token,
796 Audiences: []string{s.AgentAuthenticationOptions.AuthenticationAudience},
797 },
798 }
799 r, err := s.AgentAuthenticationOptions.KubernetesClient.AuthenticationV1().TokenReviews().Create(ctx, trReq, metav1.CreateOptions{})
800 if err != nil {
801 return "", fmt.Errorf("Failed to authenticate request. err:%v", err)
802 }
803
804 if r.Status.Error != "" {
805 return "", fmt.Errorf("lookup failed: %s", r.Status.Error)
806 }
807
808 if !r.Status.Authenticated {
809 return "", fmt.Errorf("lookup failed: service account jwt not valid")
810 }
811
812 // The username is of format: system:serviceaccount:(NAMESPACE):(SERVICEACCOUNT)
813 username = r.Status.User.Username
814 parts := strings.Split(username, ":")
815 if len(parts) != 4 {
816 return "", fmt.Errorf("lookup failed: unexpected username format")
817 }
818 // Validate the user that comes back from token review is a service account
819 if parts[0] != "system" || parts[1] != "serviceaccount" {
820 return "", fmt.Errorf("lookup failed: username returned is not a service account")
821 }
822
823 ns := parts[2]
824 sa := parts[3]
825 if s.AgentAuthenticationOptions.AgentNamespace != ns {
826 return "", fmt.Errorf("lookup failed: incoming request from %q namespace. Expected %q", ns, s.AgentAuthenticationOptions.AgentNamespace)
827 }
828
829 if s.AgentAuthenticationOptions.AgentServiceAccount != sa {
830 return "", fmt.Errorf("lookup failed: incoming request from %q service account. Expected %q", sa, s.AgentAuthenticationOptions.AgentServiceAccount)
831 }
832
833 return username, nil
834 }
835
836 func (s *ProxyServer) authenticateAgentViaToken(ctx context.Context) error {
837 md, ok := metadata.FromIncomingContext(ctx)
838 if !ok {
839 return fmt.Errorf("Failed to retrieve metadata from context")
840 }
841
842 authContext := md.Get(header.AuthenticationTokenContextKey)
843 if len(authContext) == 0 {
844 return fmt.Errorf("Authentication context was not found in metadata")
845 }
846
847 if len(authContext) > 1 {
848 return fmt.Errorf("too many (%d) tokens are received", len(authContext))
849 }
850
851 if !strings.HasPrefix(authContext[0], header.AuthenticationTokenContextSchemePrefix) {
852 return fmt.Errorf("received token does not have %q prefix", header.AuthenticationTokenContextSchemePrefix)
853 }
854
855 username, err := s.validateAuthToken(ctx, strings.TrimPrefix(authContext[0], header.AuthenticationTokenContextSchemePrefix))
856 if err != nil {
857 return fmt.Errorf("Failed to validate authentication token, err:%v", err)
858 }
859
860 klog.V(5).InfoS("Agent successfully authenticated via token", "username", username)
861 return nil
862 }
863
864 // Connect is for agent to connect to ProxyServer as next hop
865 func (s *ProxyServer) Connect(stream agent.AgentService_ConnectServer) error {
866 metrics.Metrics.ConnectionInc(metrics.Connect)
867 defer metrics.Metrics.ConnectionDec(metrics.Connect)
868
869 backend, err := NewBackend(stream)
870 if err != nil {
871 klog.ErrorS(err, "Invalid backend")
872 return err
873 }
874 agentID := backend.GetAgentID()
875
876 klog.V(2).InfoS("Connect request from agent", "agentID", agentID, "serverID", s.serverID)
877 labels := runpprof.Labels(
878 "serverCount", strconv.Itoa(s.serverCount),
879 "agentID", agentID,
880 )
881 ctx := runpprof.WithLabels(context.Background(), labels)
882 runpprof.SetGoroutineLabels(ctx)
883
884 if s.AgentAuthenticationOptions.Enabled {
885 if err := s.authenticateAgentViaToken(stream.Context()); err != nil {
886 klog.ErrorS(err, "Client authentication failed", "agentID", agentID)
887 return err
888 }
889 }
890
891 h := metadata.Pairs(header.ServerID, s.serverID, header.ServerCount, strconv.Itoa(s.serverCount))
892 if err := stream.SendHeader(h); err != nil {
893 klog.ErrorS(err, "Failed to send server count back to agent", "agentID", agentID)
894 return err
895 }
896
897 klog.V(2).InfoS("Agent connected", "agentID", agentID, "serverID", s.serverID)
898 s.addBackend(backend)
899 defer s.removeBackend(backend)
900
901 recvCh := make(chan *client.Packet, s.xfrChannelSize)
902
903 go runpprof.Do(context.Background(), labels, func(context.Context) { s.serveRecvBackend(backend, agentID, recvCh) })
904
905 stopCh := make(chan error, 1)
906 go runpprof.Do(context.Background(), labels, func(context.Context) { s.readBackendToChannel(backend, recvCh, stopCh) })
907
908 select {
909 case err := <-stopCh:
910 return err
911 case <-backend.Done():
912 klog.V(2).InfoS("Backend connection retired", "agentID", agentID)
913 return nil
914 }
915 }
916
917 func (s *ProxyServer) readBackendToChannel(backend *Backend, recvCh chan *client.Packet, stopCh chan error) {
918 defer close(recvCh)
919
920 agentID := backend.GetAgentID()
921 for {
922 in, err := backend.Recv()
923 if err == io.EOF {
924 klog.V(2).InfoS("Receive stream from agent is closed", "agentID", agentID)
925 close(stopCh)
926 return
927 }
928 if err != nil {
929 if status.Code(err) == codes.Canceled {
930 klog.V(2).InfoS("Stream read from agent cancelled", "agentID", agentID)
931 } else {
932 klog.ErrorS(err, "Receive stream from agent read failure", "agentID", agentID)
933 }
934 stopCh <- err
935 close(stopCh)
936 return
937 }
938
939 select {
940 case recvCh <- in: // Send didn't block, carry on.
941 default: // Send blocked; record it and try again.
942 klog.V(2).InfoS("Receive channel from agent is full", "agentID", agentID)
943 fullRecvChannelMetric := metrics.Metrics.FullRecvChannel(metrics.Connect)
944 fullRecvChannelMetric.Inc()
945 recvCh <- in
946 fullRecvChannelMetric.Dec()
947 }
948 }
949 }
950
951 // route the packet back to the correct client
952 func (s *ProxyServer) serveRecvBackend(backend *Backend, agentID string, recvCh <-chan *client.Packet) {
953 defer func() {
954 // Drain recvCh to ensure that readBackendToChannel is not blocked on a channel write.
955 // This should never happen, as termination of this function should only be initiated by closing recvCh.
956 discardedPktCount := 0
957 for range recvCh {
958 discardedPktCount++
959 }
960 if discardedPktCount > 0 {
961 klog.V(2).InfoS("Discard packets while exiting serveRecvBackend", "pktCount", discardedPktCount, "agentID", agentID)
962 }
963 }()
964
965 defer func() {
966 // Close all established connections when the agent connection is closed
967 // TODO(#126): connections in PendingDial state should also be closed.
968 established, err := s.removeEstablishedForBackendConn(agentID, backend)
969 if err != nil {
970 return
971 }
972 if len(established) > 0 {
973 klog.V(2).InfoS("Close established connections to agent",
974 "count", len(established), "agentID", agentID)
975 }
976
977 for _, frontend := range established {
978 pkt := &client.Packet{
979 Type: client.PacketType_CLOSE_RSP,
980 Payload: &client.Packet_CloseResponse{
981 CloseResponse: &client.CloseResponse{},
982 },
983 }
984 pkt.GetCloseResponse().ConnectID = frontend.connectID
985 if err := frontend.send(pkt); err != nil {
986 klog.ErrorS(err, "CLOSE_RSP to frontend failed", "agentID", agentID)
987 }
988 }
989 }()
990
991 for pkt := range recvCh {
992 switch pkt.Type {
993 case client.PacketType_DIAL_RSP:
994 resp := pkt.GetDialResponse()
995 klog.V(5).InfoS("Received DIAL_RSP", "dialID", resp.Random, "agentID", agentID, "connectionID", resp.ConnectID)
996
997 frontend := s.PendingDial.Remove(resp.Random)
998 if frontend == nil {
999 klog.V(2).InfoS("DIAL_RSP not recognized; dropped", "dialID", resp.Random, "agentID", agentID, "connectionID", resp.ConnectID)
1000 metrics.Metrics.ObserveDialFailure(metrics.DialFailureUnrecognizedResponse)
1001 if resp.ConnectID != 0 {
1002 s.sendBackendClose(backend, resp.ConnectID, resp.Random, "unknown dial id")
1003 }
1004 } else {
1005 dialErr := false
1006 if resp.Error != "" {
1007 // Dial response with error should not contain a valid ConnID.
1008 klog.ErrorS(errors.New(resp.Error), "DIAL_RSP contains failure", "dialID", resp.Random, "agentID", agentID)
1009 metrics.Metrics.ObserveDialFailure(metrics.DialFailureErrorResponse)
1010 dialErr = true
1011 }
1012 err := frontend.send(pkt)
1013 if err != nil {
1014 klog.ErrorS(err, "DIAL_RSP send to frontend stream failure",
1015 "dialID", resp.Random, "agentID", agentID, "connectionID", resp.ConnectID)
1016 if !dialErr { // Avoid double-counting.
1017 metrics.Metrics.ObserveDialFailure(metrics.DialFailureSendResponse)
1018 }
1019 // If we never finish setting up the tunnel for ConnectID, then the connection is dead.
1020 // Currently, the agent will no resend DIAL_RSP, so connection is dead.
1021 // We already attempted to tell the frontend that. We should ensure we tell the backend.
1022 s.sendBackendClose(backend, resp.ConnectID, resp.Random, "dial error")
1023 dialErr = true
1024 }
1025 // Avoid adding the frontend if there was an error dialing the destination
1026 if dialErr {
1027 break
1028 }
1029 frontend.connectID = resp.ConnectID
1030 frontend.agentID = agentID
1031 // TODO: this connection may be cleaned on serveRecvFrontend exit, make it independent.
1032 s.addEstablished(agentID, resp.ConnectID, frontend)
1033 close(frontend.connected)
1034 metrics.Metrics.ObserveDialLatency(time.Since(frontend.start))
1035 klog.V(3).InfoS("Proxy connection established",
1036 "dialID", resp.Random,
1037 "connectionID", resp.ConnectID,
1038 "agentID", agentID,
1039 "dialAddress", frontend.dialAddress,
1040 "dialDuration", time.Since(frontend.start),
1041 )
1042 }
1043
1044 case client.PacketType_DIAL_CLS:
1045 resp := pkt.GetCloseDial()
1046 klog.V(5).InfoS("Received DIAL_CLS", "agentID", agentID, "dialID", resp.Random)
1047 frontend := s.PendingDial.Remove(resp.Random)
1048 if frontend == nil {
1049 klog.V(2).InfoS("DIAL_CLS not recognized; dropped", "dialID", resp.Random, "agentID", agentID)
1050 } else {
1051 if err := frontend.send(pkt); err != nil {
1052 klog.ErrorS(err, "DIAL_CLS send to client stream error", "agentID", agentID, "dialID", resp.Random)
1053 } else {
1054 klog.V(5).InfoS("DIAL_CLS sent to frontend", "dialID", resp.Random)
1055 }
1056 klog.ErrorS(nil, "Dial terminated (DIAL_CLS) by backend",
1057 "dialID", resp.Random,
1058 "agentID", agentID,
1059 "dialAddress", frontend.dialAddress,
1060 "dialDuration", time.Since(frontend.start),
1061 )
1062 metrics.Metrics.ObserveDialFailure(metrics.DialFailureBackendClose)
1063 }
1064
1065 case client.PacketType_DATA:
1066 resp := pkt.GetData()
1067 klog.V(5).InfoS("Received data from agent", "bytes", len(resp.Data), "agentID", agentID, "connectionID", resp.ConnectID)
1068 if resp.ConnectID == 0 {
1069 klog.ErrorS(nil, "Received packet missing ConnectID from agent", "packetType", "DATA")
1070 continue
1071 }
1072
1073 frontend, err := s.getFrontend(agentID, resp.ConnectID)
1074 if err != nil {
1075 klog.V(2).InfoS("could not get frontend client; closing connection", "agentID", agentID, "connectionID", resp.ConnectID, "error", err)
1076 s.sendBackendClose(backend, resp.ConnectID, 0, "missing frontend")
1077 break
1078 }
1079 if err := frontend.send(pkt); err != nil {
1080 klog.ErrorS(err, "send to client stream failure", "agentID", agentID, "connectionID", resp.ConnectID)
1081 } else {
1082 klog.V(5).InfoS("DATA sent to frontend")
1083 }
1084
1085 case client.PacketType_CLOSE_RSP:
1086 resp := pkt.GetCloseResponse()
1087 klog.V(5).InfoS("Received CLOSE_RSP", "agentID", agentID, "connectionID", resp.ConnectID)
1088 frontend := s.removeEstablished(agentID, resp.ConnectID)
1089 if frontend == nil {
1090 // assuming it is already closed, just log it
1091 klog.V(2).InfoS("could not get frontend client for closing", "agentID", agentID, "connectionID", resp.ConnectID)
1092 break
1093 }
1094 if err := frontend.send(pkt); err != nil {
1095 // Normal when frontend closes it.
1096 klog.ErrorS(err, "CLOSE_RSP send to client stream error", "agentID", agentID, "connectionID", resp.ConnectID)
1097 } else {
1098 klog.V(5).InfoS("CLOSE_RSP sent to frontend", "connectionID", resp.ConnectID)
1099 }
1100
1101 case client.PacketType_DRAIN:
1102 klog.V(2).InfoS("agent is draining", "agentID", agentID)
1103 backend.SetDraining()
1104 klog.V(2).InfoS("marked backend as draining, will not route new requests to this agent", "agentID", agentID)
1105 default:
1106 klog.V(5).InfoS("Ignoring unrecognized packet from backend", "packet", pkt, "agentID", agentID)
1107 }
1108 }
1109 klog.V(3).InfoS("Close backend of agent", "agentID", agentID)
1110 }
1111
1112 func (s *ProxyServer) sendBackendClose(backend *Backend, connectID int64, random int64, reason string) {
1113 agentID := backend.GetAgentID()
1114 pkt := &client.Packet{
1115 Type: client.PacketType_CLOSE_REQ,
1116 Payload: &client.Packet_CloseRequest{
1117 CloseRequest: &client.CloseRequest{
1118 ConnectID: connectID,
1119 },
1120 },
1121 }
1122 if err := backend.Send(pkt); err != nil {
1123 klog.V(5).ErrorS(err, "Failed to send close to agent", "closeReason", reason, "dialID", random, "agentID", agentID, "connectionID", connectID)
1124 }
1125 }
1126
1127 func (s *ProxyServer) sendBackendDialClose(backend *Backend, random int64, reason string) {
1128 agentID := backend.GetAgentID()
1129 pkt := &client.Packet{
1130 Type: client.PacketType_DIAL_CLS,
1131 Payload: &client.Packet_CloseDial{
1132 CloseDial: &client.CloseDial{
1133 Random: random,
1134 },
1135 },
1136 }
1137 if err := backend.Send(pkt); err != nil {
1138 klog.V(5).ErrorS(err, "Failed to send dial close to agent", "closeReason", reason, "dialID", random, "agentID", agentID)
1139 }
1140 }
1141
1142 func (s *ProxyServer) sendFrontendClose(frontend *GrpcFrontend, connectID int64, reason string) {
1143 pkt := &client.Packet{
1144 Type: client.PacketType_CLOSE_RSP,
1145 Payload: &client.Packet_CloseResponse{
1146 CloseResponse: &client.CloseResponse{
1147 ConnectID: connectID,
1148 Error: reason,
1149 },
1150 },
1151 }
1152 if err := frontend.Send(pkt); err != nil {
1153 klog.V(5).ErrorS(err, "Failed to send close to frontend", "closeReason", reason, "connectionID", connectID)
1154 }
1155 }