github.com/stefanmcshane/helm@v0.0.0-20221213002717-88a4a2c6e77d/pkg/cli/roundtripper.go (about) 1 /* 2 Copyright The Helm 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 cli 18 19 import ( 20 "bytes" 21 "encoding/json" 22 "io" 23 "net/http" 24 "strings" 25 ) 26 27 type retryingRoundTripper struct { 28 wrapped http.RoundTripper 29 } 30 31 func (rt *retryingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { 32 return rt.roundTrip(req, 1, nil) 33 } 34 35 func (rt *retryingRoundTripper) roundTrip(req *http.Request, retry int, prevResp *http.Response) (*http.Response, error) { 36 if retry < 0 { 37 return prevResp, nil 38 } 39 resp, rtErr := rt.wrapped.RoundTrip(req) 40 if rtErr != nil { 41 return resp, rtErr 42 } 43 if resp.Header.Get("content-type") != "application/json" { 44 return resp, rtErr 45 } 46 b, err := io.ReadAll(resp.Body) 47 resp.Body.Close() 48 if err != nil { 49 return resp, rtErr 50 } 51 52 var ke kubernetesError 53 r := bytes.NewReader(b) 54 err = json.NewDecoder(r).Decode(&ke) 55 r.Seek(0, io.SeekStart) 56 resp.Body = io.NopCloser(r) 57 if err != nil { 58 return resp, rtErr 59 } 60 if ke.Code < 500 { 61 return resp, rtErr 62 } 63 // Matches messages like "etcdserver: leader changed" 64 if strings.HasSuffix(ke.Message, "etcdserver: leader changed") { 65 return rt.roundTrip(req, retry-1, resp) 66 } 67 // Matches messages like "rpc error: code = Unknown desc = raft proposal dropped" 68 if strings.HasSuffix(ke.Message, "raft proposal dropped") { 69 return rt.roundTrip(req, retry-1, resp) 70 } 71 return resp, rtErr 72 } 73 74 type kubernetesError struct { 75 Message string `json:"message"` 76 Code int `json:"code"` 77 }