1 /* 2 Copyright 2023 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 remotecommand 18 19 import ( 20 "context" 21 ) 22 23 var _ Executor = &FallbackExecutor{} 24 25 type FallbackExecutor struct { 26 primary Executor 27 secondary Executor 28 shouldFallback func(error) bool 29 } 30 31 // NewFallbackExecutor creates an Executor that first attempts to use the 32 // WebSocketExecutor, falling back to the legacy SPDYExecutor if the initial 33 // websocket "StreamWithContext" call fails. 34 // func NewFallbackExecutor(config *restclient.Config, method string, url *url.URL) (Executor, error) { 35 func NewFallbackExecutor(primary, secondary Executor, shouldFallback func(error) bool) (Executor, error) { 36 return &FallbackExecutor{ 37 primary: primary, 38 secondary: secondary, 39 shouldFallback: shouldFallback, 40 }, nil 41 } 42 43 // Stream is deprecated. Please use "StreamWithContext". 44 func (f *FallbackExecutor) Stream(options StreamOptions) error { 45 return f.StreamWithContext(context.Background(), options) 46 } 47 48 // StreamWithContext initially attempts to call "StreamWithContext" using the 49 // primary executor, falling back to calling the secondary executor if the 50 // initial primary call to upgrade to a websocket connection fails. 51 func (f *FallbackExecutor) StreamWithContext(ctx context.Context, options StreamOptions) error { 52 err := f.primary.StreamWithContext(ctx, options) 53 if f.shouldFallback(err) { 54 return f.secondary.StreamWithContext(ctx, options) 55 } 56 return err 57 } 58