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