github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/cmd/deck/pluginhelp.go (about) 1 /* 2 Copyright 2017 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 main 18 19 import ( 20 "encoding/json" 21 "fmt" 22 "net/http" 23 "sync" 24 "time" 25 26 "sigs.k8s.io/prow/pkg/pluginhelp" 27 ) 28 29 // cacheLife is the time that we keep a pluginhelp.Help struct before considering it stale. 30 // We consider help valid for a minute to prevent excessive calls to hook. 31 const cacheLife = time.Minute 32 33 type helpAgent struct { 34 path string 35 36 sync.Mutex 37 help *pluginhelp.Help 38 expiry time.Time 39 } 40 41 func newHelpAgent(path string) *helpAgent { 42 return &helpAgent{ 43 path: path, 44 } 45 } 46 47 func (ha *helpAgent) getHelp() (*pluginhelp.Help, error) { 48 ha.Lock() 49 defer ha.Unlock() 50 if time.Now().Before(ha.expiry) { 51 return ha.help, nil 52 } 53 54 var help pluginhelp.Help 55 resp, err := http.Get(ha.path) 56 if err != nil { 57 return nil, fmt.Errorf("error Getting plugin help: %w", err) 58 } 59 defer resp.Body.Close() 60 if resp.StatusCode < 200 || resp.StatusCode > 299 { 61 return nil, fmt.Errorf("response has status code %d", resp.StatusCode) 62 } 63 if err := json.NewDecoder(resp.Body).Decode(&help); err != nil { 64 return nil, fmt.Errorf("error decoding json plugin help: %w", err) 65 } 66 67 ha.help = &help 68 ha.expiry = time.Now().Add(cacheLife) 69 return &help, nil 70 }