|
| 1 | +package terminal |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "net/url" |
| 8 | + |
| 9 | + "k8s.io/client-go/rest" |
| 10 | + "k8s.io/client-go/tools/remotecommand" |
| 11 | +) |
| 12 | + |
| 13 | +// FallbackExecutor tries WebSocket first and falls back to SPDY if needed |
| 14 | +type FallbackExecutor struct { |
| 15 | + executor remotecommand.Executor |
| 16 | +} |
| 17 | + |
| 18 | +// NewFallbackExecutor creates a new executor that tries WebSocket first and falls back to SPDY |
| 19 | +func NewFallbackExecutor(config *rest.Config, method string, url *url.URL) (remotecommand.Executor, error) { |
| 20 | + var wsExecutor, spdyExecutor remotecommand.Executor |
| 21 | + var wsErr, spdyErr error |
| 22 | + |
| 23 | + // Try to create WebSocket executor |
| 24 | + wsExecutor, wsErr = remotecommand.NewWebSocketExecutor(config, method, url.String()) |
| 25 | + if wsErr != nil { |
| 26 | + log.Printf("Warning: Failed to create WebSocket executor: %v", wsErr) |
| 27 | + } |
| 28 | + |
| 29 | + // Try to create SPDY executor |
| 30 | + spdyExecutor, spdyErr = remotecommand.NewSPDYExecutor(config, method, url) |
| 31 | + if spdyErr != nil { |
| 32 | + log.Printf("Warning: Failed to create SPDY executor: %v", spdyErr) |
| 33 | + } |
| 34 | + |
| 35 | + // Handle different scenarios |
| 36 | + if wsErr != nil && spdyErr != nil { |
| 37 | + // Both failed |
| 38 | + return nil, fmt.Errorf("failed to create any executor: WebSocket error: %v, SPDY error: %v", wsErr, spdyErr) |
| 39 | + } |
| 40 | + |
| 41 | + if wsErr != nil { |
| 42 | + // Only WebSocket failed, use SPDY |
| 43 | + return spdyExecutor, nil |
| 44 | + } |
| 45 | + |
| 46 | + if spdyErr != nil { |
| 47 | + // Only SPDY failed, use WebSocket |
| 48 | + return wsExecutor, nil |
| 49 | + } |
| 50 | + |
| 51 | + // Both succeeded, create fallback executor |
| 52 | + fallbackExecutor, err := remotecommand.NewFallbackExecutor(wsExecutor, spdyExecutor, func(err error) bool { |
| 53 | + // Fall back to SPDY if WebSocket fails due to connection issues |
| 54 | + log.Printf("WebSocket failed, falling back to SPDY: %v", err) |
| 55 | + return true |
| 56 | + }) |
| 57 | + if err != nil { |
| 58 | + return nil, fmt.Errorf("failed to create fallback executor: %v", err) |
| 59 | + } |
| 60 | + |
| 61 | + return &FallbackExecutor{ |
| 62 | + executor: fallbackExecutor, |
| 63 | + }, nil |
| 64 | +} |
| 65 | + |
| 66 | +// Stream is deprecated. Please use StreamWithContext. |
| 67 | +func (e *FallbackExecutor) Stream(options remotecommand.StreamOptions) error { |
| 68 | + return e.executor.Stream(options) |
| 69 | +} |
| 70 | + |
| 71 | +// StreamWithContext delegates to the underlying fallback executor |
| 72 | +func (e *FallbackExecutor) StreamWithContext(ctx context.Context, options remotecommand.StreamOptions) error { |
| 73 | + return e.executor.StreamWithContext(ctx, options) |
| 74 | +} |
0 commit comments