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