github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/pluginhelp/externalplugins/externalplugins.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 externalplugins provides the plugin help components to be compiled into external plugin binaries. 18 // Since external plugins only need to serve a "/help" endpoint this package just provides an 19 // http.HandlerFunc that wraps an ExternalPluginHelpProvider function. 20 package externalplugins 21 22 import ( 23 "encoding/json" 24 "errors" 25 "fmt" 26 "io" 27 "net/http" 28 29 "github.com/sirupsen/logrus" 30 31 "sigs.k8s.io/prow/pkg/config" 32 "sigs.k8s.io/prow/pkg/pluginhelp" 33 ) 34 35 // ExternalPluginHelpProvider is a func type that returns a PluginHelp struct for an external 36 // plugin based on the specified enabledRepos. 37 type ExternalPluginHelpProvider func([]config.OrgRepo) (*pluginhelp.PluginHelp, error) 38 39 // ServeExternalPluginHelp returns a HandlerFunc that serves plugin help information that is 40 // provided by the specified ExternalPluginHelpProvider. 41 func ServeExternalPluginHelp(mux *http.ServeMux, log *logrus.Entry, provider ExternalPluginHelpProvider) { 42 mux.HandleFunc( 43 "/help", 44 func(w http.ResponseWriter, r *http.Request) { 45 w.Header().Set("Cache-Control", "no-cache") 46 47 serverError := func(action string, err error) { 48 log.WithError(err).Errorf("Error %s.", action) 49 msg := fmt.Sprintf("500 Internal server error %s: %v", action, err) 50 http.Error(w, msg, http.StatusInternalServerError) 51 } 52 53 if r.Method != http.MethodPost { 54 log.Errorf("Invalid request method: %v.", r.Method) 55 http.Error(w, "405 Method not allowed", http.StatusMethodNotAllowed) 56 return 57 } 58 b, err := io.ReadAll(r.Body) 59 if err != nil { 60 serverError("reading request body", err) 61 return 62 } 63 var enabledRepos []config.OrgRepo 64 if err := json.Unmarshal(b, &enabledRepos); err != nil { 65 serverError("unmarshaling request body", err) 66 return 67 } 68 if provider == nil { 69 serverError("generating plugin help", errors.New("help provider is nil")) 70 return 71 } 72 help, err := provider(enabledRepos) 73 if err != nil { 74 serverError("generating plugin help", err) 75 return 76 } 77 b, err = json.Marshal(help) 78 if err != nil { 79 serverError("marshaling plugin help", err) 80 return 81 } 82 83 fmt.Fprint(w, string(b)) 84 }, 85 ) 86 }