github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/cmd/jenkins-operator/logs.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 "fmt" 21 "net/http" 22 "regexp" 23 "strings" 24 25 "github.com/sirupsen/logrus" 26 27 "sigs.k8s.io/prow/pkg/jenkins" 28 ) 29 30 var reJenkinsJobURL = regexp.MustCompile(`^(/?job)/([A-Za-z0-9-._]([A-Za-z0-9-._/]*[A-Za-z0-9-_])?)/(\d+)/consoleText$`) 31 32 func handleLog(jc *jenkins.Client) http.HandlerFunc { 33 return func(w http.ResponseWriter, r *http.Request) { 34 w.Header().Set("Cache-Control", "no-cache") 35 w.Header().Set("Access-Control-Allow-Origin", "*") 36 w.Header().Set("Access-Control-Allow-Methods", "GET") 37 38 // Needs to be a GET request. 39 if r.Method != http.MethodGet { 40 http.Error(w, "405 Method not allowed", http.StatusMethodNotAllowed) 41 return 42 } 43 44 // Needs to get Jenkins logs. 45 if !strings.HasSuffix(r.URL.Path, "consoleText") { 46 http.Error(w, "403 Forbidden: Request may only access raw Jenkins logs", http.StatusForbidden) 47 return 48 } 49 50 realPath, err := getRealJenkinsLogPath(r.URL.Path) 51 if err != nil { 52 http.Error(w, fmt.Sprintf("Log not found: %v", err), http.StatusNotFound) 53 return 54 } 55 56 log, err := jc.GetSkipMetrics(realPath) 57 if err != nil { 58 http.Error(w, fmt.Sprintf("Log not found: %v", err), http.StatusNotFound) 59 logrus.WithError(err).Warning(fmt.Sprintf("Cannot get logs from Jenkins (GET %s).", realPath)) 60 return 61 } 62 63 if _, err = w.Write(log); err != nil { 64 logrus.WithError(err).Warning("Error writing log.") 65 } 66 } 67 } 68 69 func getRealJenkinsLogPath(path string) (string, error) { 70 jobMatches := reJenkinsJobURL.FindStringSubmatch(path) 71 if len(jobMatches) != 5 { 72 return "", fmt.Errorf("job URL path not match regexp pattern: ^%s$", reJenkinsJobURL) 73 } 74 75 realPath := fmt.Sprintf("%s/%s/%s/consoleText", 76 jobMatches[1], 77 strings.Join(strings.Split(jobMatches[2], "/"), "/job/"), 78 jobMatches[4], 79 ) 80 81 return realPath, nil 82 }