| 1 | /* |
| 2 | Copyright 2020 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 | "context" |
| 21 | "fmt" |
| 22 | "io" |
| 23 | "math/rand" |
| 24 | "slices" |
| 25 | "strings" |
| 26 | "sync" |
| 27 | "time" |
| 28 | |
| 29 | "google.golang.org/grpc/metadata" |
| 30 | "k8s.io/klog/v2" |
| 31 | |
| 32 | commonmetrics "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics" |
| 33 | client "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client" |
| 34 | "sigs.k8s.io/apiserver-network-proxy/pkg/server/metrics" |
| 35 | "sigs.k8s.io/apiserver-network-proxy/proto/agent" |
| 36 | "sigs.k8s.io/apiserver-network-proxy/proto/header" |
| 37 | ) |
| 38 | |
| 39 | type ProxyStrategy int |
| 40 | |
| 41 | const ( |
| 42 | // With this strategy the Proxy Server will randomly pick a backend from |
| 43 | // the current healthy backends to establish the tunnel over which to |
| 44 | // forward requests. |
| 45 | ProxyStrategyDefault ProxyStrategy = iota + 1 |
| 46 | // With this strategy the Proxy Server will pick a backend that has the same |
| 47 | // associated host as the request.Host to establish the tunnel. |
| 48 | ProxyStrategyDestHost |
| 49 | // ProxyStrategyDefaultRoute will only forward traffic to agents that have explicity advertised |
| 50 | // they serve the default route through an agent identifier. Typically used in combination with destHost |
| 51 | ProxyStrategyDefaultRoute |
| 52 | ) |
| 53 | |
| 54 | func (ps ProxyStrategy) String() string { |
| 55 | switch ps { |
| 56 | case ProxyStrategyDefault: |
| 57 | return "default" |
| 58 | case ProxyStrategyDestHost: |
| 59 | return "destHost" |
| 60 | case ProxyStrategyDefaultRoute: |
| 61 | return "defaultRoute" |
| 62 | } |
| 63 | panic(fmt.Sprintf("unhandled ProxyStrategy: %d", ps)) |
| 64 | } |
| 65 | |
| 66 | func ParseProxyStrategy(s string) (ProxyStrategy, error) { |
| 67 | switch s { |
| 68 | case ProxyStrategyDefault.String(): |
| 69 | return ProxyStrategyDefault, nil |
| 70 | case ProxyStrategyDestHost.String(): |
| 71 | return ProxyStrategyDestHost, nil |
| 72 | case ProxyStrategyDefaultRoute.String(): |
| 73 | return ProxyStrategyDefaultRoute, nil |
| 74 | default: |
| 75 | return 0, fmt.Errorf("unknown proxy strategy: %s", s) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | // GenProxyStrategiesFromStr generates the list of proxy strategies from the |
| 80 | // comma-seperated string, i.e., destHost. |
| 81 | func ParseProxyStrategies(proxyStrategies string) ([]ProxyStrategy, error) { |
| 82 | var result []ProxyStrategy |
| 83 | |
| 84 | strs := strings.Split(proxyStrategies, ",") |
| 85 | for _, s := range strs { |
| 86 | if len(s) == 0 { |
| 87 | continue |
| 88 | } |
| 89 | ps, err := ParseProxyStrategy(s) |
| 90 | if err != nil { |
| 91 | return nil, err |
| 92 | } |
| 93 | result = append(result, ps) |
| 94 | } |
| 95 | if len(result) == 0 { |
| 96 | return nil, fmt.Errorf("proxy strategies cannot be empty") |
| 97 | } |
| 98 | return result, nil |
| 99 | } |
| 100 | |
| 101 | // Backend abstracts a connected Konnectivity agent. |
| 102 | // |
| 103 | // In the only currently supported case (gRPC), it wraps an |
| 104 | // agent.AgentService_ConnectServer, provides synchronization and |
| 105 | // emits common stream metrics. |
| 106 | type Backend struct { |
| 107 | sendLock sync.Mutex |
| 108 | recvLock sync.Mutex |
| 109 | conn agent.AgentService_ConnectServer |
| 110 | |
| 111 | // cached from conn.Context() |
| 112 | id string |
| 113 | idents header.Identifiers |
| 114 | } |
| 115 | |
| 116 | func (b *Backend) Send(p *client.Packet) error { |
| 117 | b.sendLock.Lock() |
| 118 | defer b.sendLock.Unlock() |
| 119 | |
| 120 | const segment = commonmetrics.SegmentToAgent |
| 121 | metrics.Metrics.ObservePacket(segment, p.Type) |
| 122 | err := b.conn.Send(p) |
| 123 | if err != nil && err != io.EOF { |
| 124 | metrics.Metrics.ObserveStreamError(segment, err, p.Type) |
| 125 | } |
| 126 | return err |
| 127 | } |
| 128 | |
| 129 | func (b *Backend) Recv() (*client.Packet, error) { |
| 130 | b.recvLock.Lock() |
| 131 | defer b.recvLock.Unlock() |
| 132 | |
| 133 | const segment = commonmetrics.SegmentFromAgent |
| 134 | pkt, err := b.conn.Recv() |
| 135 | if err != nil { |
| 136 | if err != io.EOF { |
| 137 | metrics.Metrics.ObserveStreamErrorNoPacket(segment, err) |
| 138 | } |
| 139 | return nil, err |
| 140 | } |
| 141 | metrics.Metrics.ObservePacket(segment, pkt.Type) |
| 142 | return pkt, nil |
| 143 | } |
| 144 | |
| 145 | func (b *Backend) Context() context.Context { |
| 146 | // TODO: does Context require lock protection? |
| 147 | return b.conn.Context() |
| 148 | } |
| 149 | |
| 150 | func (b *Backend) GetAgentID() string { |
| 151 | return b.id |
| 152 | } |
| 153 | |
| 154 | func (b *Backend) GetAgentIdentifiers() header.Identifiers { |
| 155 | return b.idents |
| 156 | } |
| 157 | |
| 158 | func getAgentID(stream agent.AgentService_ConnectServer) (string, error) { |
| 159 | md, ok := metadata.FromIncomingContext(stream.Context()) |
| 160 | if !ok { |
| 161 | return "", fmt.Errorf("failed to get context") |
| 162 | } |
| 163 | agentIDs := md.Get(header.AgentID) |
| 164 | if len(agentIDs) != 1 { |
| 165 | return "", fmt.Errorf("expected one agent ID in the context, got %v", agentIDs) |
| 166 | } |
| 167 | return agentIDs[0], nil |
| 168 | } |
| 169 | |
| 170 | func getAgentIdentifiers(conn agent.AgentService_ConnectServer) (header.Identifiers, error) { |
| 171 | var agentIdentifiers header.Identifiers |
| 172 | md, ok := metadata.FromIncomingContext(conn.Context()) |
| 173 | if !ok { |
| 174 | return agentIdentifiers, fmt.Errorf("failed to get metadata from context") |
| 175 | } |
| 176 | agentIdent := md.Get(header.AgentIdentifiers) |
| 177 | if len(agentIdent) > 1 { |
| 178 | return agentIdentifiers, fmt.Errorf("expected at most one set of agent identifiers in the context, got %v", agentIdent) |
| 179 | } |
| 180 | if len(agentIdent) == 0 { |
| 181 | return agentIdentifiers, nil |
| 182 | } |
| 183 | |
| 184 | return header.GenAgentIdentifiers(agentIdent[0]) |
| 185 | } |
| 186 | |
| 187 | func NewBackend(conn agent.AgentService_ConnectServer) (*Backend, error) { |
| 188 | agentID, err := getAgentID(conn) |
| 189 | if err != nil { |
| 190 | return nil, err |
| 191 | } |
| 192 | agentIdentifiers, err := getAgentIdentifiers(conn) |
| 193 | if err != nil { |
| 194 | return nil, err |
| 195 | } |
| 196 | return &Backend{conn: conn, id: agentID, idents: agentIdentifiers}, nil |
| 197 | } |
| 198 | |
| 199 | // BackendStorage is an interface to manage the storage of the backend |
| 200 | // connections, i.e., get, add and remove |
| 201 | type BackendStorage interface { |
| 202 | // addBackend adds a backend. |
| 203 | addBackend(identifier string, idType header.IdentifierType, backend *Backend) |
| 204 | // removeBackend removes a backend. |
| 205 | removeBackend(identifier string, idType header.IdentifierType, backend *Backend) |
| 206 | // NumBackends returns the number of backends. |
| 207 | NumBackends() int |
| 208 | } |
| 209 | |
| 210 | // BackendManager is an interface to manage backend connections, i.e., |
| 211 | // connection to the proxy agents. |
| 212 | type BackendManager interface { |
| 213 | // Backend returns a single backend. |
| 214 | // WARNING: the context passed to the function should be a session-scoped |
| 215 | // context instead of a request-scoped context, as the backend manager will |
| 216 | // pick a backend for every tunnel session and each tunnel session may |
| 217 | // contains multiple requests. |
| 218 | Backend(ctx context.Context) (*Backend, error) |
| 219 | // AddBackend adds a backend. |
| 220 | AddBackend(backend *Backend) |
| 221 | // RemoveBackend adds a backend. |
| 222 | RemoveBackend(backend *Backend) |
| 223 | BackendStorage |
| 224 | ReadinessManager |
| 225 | } |
| 226 | |
| 227 | var _ BackendManager = &DefaultBackendManager{} |
| 228 | |
| 229 | // DefaultBackendManager is the default backend manager. |
| 230 | type DefaultBackendManager struct { |
| 231 | *DefaultBackendStorage |
| 232 | } |
| 233 | |
| 234 | func (dbm *DefaultBackendManager) Backend(_ context.Context) (*Backend, error) { |
| 235 | klog.V(5).InfoS("Get a random backend through the DefaultBackendManager") |
| 236 | return dbm.DefaultBackendStorage.GetRandomBackend() |
| 237 | } |
| 238 | |
| 239 | func (dbm *DefaultBackendManager) AddBackend(backend *Backend) { |
| 240 | agentID := backend.GetAgentID() |
| 241 | klog.V(5).InfoS("Add the agent to DefaultBackendManager", "agentID", agentID) |
| 242 | dbm.addBackend(agentID, header.UID, backend) |
| 243 | } |
| 244 | |
| 245 | func (dbm *DefaultBackendManager) RemoveBackend(backend *Backend) { |
| 246 | agentID := backend.GetAgentID() |
| 247 | klog.V(5).InfoS("Remove the agent from the DefaultBackendManager", "agentID", agentID) |
| 248 | dbm.removeBackend(agentID, header.UID, backend) |
| 249 | } |
| 250 | |
| 251 | // DefaultBackendStorage is the default backend storage. |
| 252 | type DefaultBackendStorage struct { |
| 253 | mu sync.RWMutex //protects the following |
| 254 | // A map between agentID and its grpc connections. |
| 255 | // For a given agent, ProxyServer prefers backends[agentID][0] to send |
| 256 | // traffic, because backends[agentID][1:] are more likely to be closed |
| 257 | // by the agent to deduplicate connections to the same server. |
| 258 | // |
| 259 | // TODO: fix documentation. This is not always agentID, e.g. in |
| 260 | // the case of DestHostBackendManager. |
| 261 | backends map[string][]*Backend |
| 262 | // agentID is tracked in this slice to enable randomly picking an |
| 263 | // agentID in the Backend() method. There is no reliable way to |
| 264 | // randomly pick a key from a map (in this case, the backends) in |
| 265 | // Golang. |
| 266 | agentIDs []string |
| 267 | random *rand.Rand |
| 268 | // idTypes contains the valid identifier types for this |
| 269 | // DefaultBackendStorage. The DefaultBackendStorage may only tolerate certain |
| 270 | // types of identifiers when associating to a specific BackendManager, |
| 271 | // e.g., when associating to the DestHostBackendManager, it can only use the |
| 272 | // identifiers of types, IPv4, IPv6 and Host. |
| 273 | idTypes []header.IdentifierType |
| 274 | } |
| 275 | |
| 276 | // NewDefaultBackendManager returns a DefaultBackendManager. |
| 277 | func NewDefaultBackendManager() *DefaultBackendManager { |
| 278 | return &DefaultBackendManager{ |
| 279 | DefaultBackendStorage: NewDefaultBackendStorage( |
| 280 | []header.IdentifierType{header.UID})} |
| 281 | } |
| 282 | |
| 283 | // NewDefaultBackendStorage returns a DefaultBackendStorage |
| 284 | func NewDefaultBackendStorage(idTypes []header.IdentifierType) *DefaultBackendStorage { |
| 285 | // Set an explicit value, so that the metric is emitted even when |
| 286 | // no agent ever successfully connects. |
| 287 | metrics.Metrics.SetBackendCount(0) |
| 288 | return &DefaultBackendStorage{ |
| 289 | backends: make(map[string][]*Backend), |
| 290 | random: rand.New(rand.NewSource(time.Now().UnixNano())), /* #nosec G404 */ |
| 291 | idTypes: idTypes, |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | func containIDType(idTypes []header.IdentifierType, idType header.IdentifierType) bool { |
| 296 | return slices.Contains(idTypes, idType) |
| 297 | } |
| 298 | |
| 299 | // addBackend adds a backend. |
| 300 | func (s *DefaultBackendStorage) addBackend(identifier string, idType header.IdentifierType, backend *Backend) { |
| 301 | if !containIDType(s.idTypes, idType) { |
| 302 | klog.V(4).InfoS("fail to add backend", "backend", identifier, "error", &ErrWrongIDType{idType, s.idTypes}) |
| 303 | return |
| 304 | } |
| 305 | klog.V(5).InfoS("Register backend for agent", "agentID", identifier) |
| 306 | s.mu.Lock() |
| 307 | defer s.mu.Unlock() |
| 308 | _, ok := s.backends[identifier] |
| 309 | if ok { |
| 310 | for _, b := range s.backends[identifier] { |
| 311 | if b == backend { |
| 312 | klog.V(1).InfoS("This should not happen. Adding existing backend for agent", "agentID", identifier) |
| 313 | return |
| 314 | } |
| 315 | } |
| 316 | s.backends[identifier] = append(s.backends[identifier], backend) |
| 317 | return |
| 318 | } |
| 319 | s.backends[identifier] = []*Backend{backend} |
| 320 | metrics.Metrics.SetBackendCount(len(s.backends)) |
| 321 | s.agentIDs = append(s.agentIDs, identifier) |
| 322 | } |
| 323 | |
| 324 | // removeBackend removes a backend. |
| 325 | func (s *DefaultBackendStorage) removeBackend(identifier string, idType header.IdentifierType, backend *Backend) { |
| 326 | if !containIDType(s.idTypes, idType) { |
| 327 | klog.ErrorS(&ErrWrongIDType{idType, s.idTypes}, "fail to remove backend") |
| 328 | return |
| 329 | } |
| 330 | klog.V(5).InfoS("Remove connection for agent", "agentID", identifier) |
| 331 | s.mu.Lock() |
| 332 | defer s.mu.Unlock() |
| 333 | backends, ok := s.backends[identifier] |
| 334 | if !ok { |
| 335 | klog.V(1).InfoS("Cannot find agent in backends", "identifier", identifier) |
| 336 | return |
| 337 | } |
| 338 | var found bool |
| 339 | for i, b := range backends { |
| 340 | if b == backend { |
| 341 | s.backends[identifier] = append(s.backends[identifier][:i], s.backends[identifier][i+1:]...) |
| 342 | if i == 0 && len(s.backends[identifier]) != 0 { |
| 343 | klog.V(1).InfoS("This should not happen. Removed connection that is not the first connection", "agentID", identifier) |
| 344 | } |
| 345 | found = true |
| 346 | } |
| 347 | } |
| 348 | if len(s.backends[identifier]) == 0 { |
| 349 | delete(s.backends, identifier) |
| 350 | for i := range s.agentIDs { |
| 351 | if s.agentIDs[i] == identifier { |
| 352 | s.agentIDs[i] = s.agentIDs[len(s.agentIDs)-1] |
| 353 | s.agentIDs = s.agentIDs[:len(s.agentIDs)-1] |
| 354 | break |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | if !found { |
| 359 | klog.V(1).InfoS("Could not find connection matching identifier to remove", "agentID", identifier, "idType", idType) |
| 360 | } |
| 361 | metrics.Metrics.SetBackendCount(len(s.backends)) |
| 362 | } |
| 363 | |
| 364 | // NumBackends resturns the number of available backends |
| 365 | func (s *DefaultBackendStorage) NumBackends() int { |
| 366 | s.mu.RLock() |
| 367 | defer s.mu.RUnlock() |
| 368 | return len(s.backends) |
| 369 | } |
| 370 | |
| 371 | // ErrNotFound indicates that no backend can be found. |
| 372 | type ErrNotFound struct{} |
| 373 | |
| 374 | // Error returns the error message. |
| 375 | func (e *ErrNotFound) Error() string { |
| 376 | return "No agent available" |
| 377 | } |
| 378 | |
| 379 | type ErrWrongIDType struct { |
| 380 | got header.IdentifierType |
| 381 | expect []header.IdentifierType |
| 382 | } |
| 383 | |
| 384 | func (e *ErrWrongIDType) Error() string { |
| 385 | return fmt.Sprintf("incorrect id type: got %s, expect %s", e.got, e.expect) |
| 386 | } |
| 387 | |
| 388 | func ignoreNotFound(err error) error { |
| 389 | if _, ok := err.(*ErrNotFound); ok { |
| 390 | return nil |
| 391 | } |
| 392 | return err |
| 393 | } |
| 394 | |
| 395 | // GetRandomBackend returns a random backend connection from all connected agents. |
| 396 | func (s *DefaultBackendStorage) GetRandomBackend() (*Backend, error) { |
| 397 | s.mu.Lock() |
| 398 | defer s.mu.Unlock() |
| 399 | if len(s.backends) == 0 { |
| 400 | return nil, &ErrNotFound{} |
| 401 | } |
| 402 | agentID := s.agentIDs[s.random.Intn(len(s.agentIDs))] |
| 403 | klog.V(5).InfoS("Pick agent as backend", "agentID", agentID) |
| 404 | // always return the first connection to an agent, because the agent |
| 405 | // will close later connections if there are multiple. |
| 406 | return s.backends[agentID][0], nil |
| 407 | } |