gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/runsc/metricserver/metricserver_http.go (about)

     1  // Copyright 2023 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package metricserver
    16  
    17  import (
    18  	"errors"
    19  	"net/http"
    20  	"runtime"
    21  	"strings"
    22  	"time"
    23  
    24  	"gvisor.dev/gvisor/pkg/log"
    25  )
    26  
    27  // httpTimeout is the timeout used for all connect/read/write operations of the HTTP server.
    28  const httpTimeout = 1 * time.Minute
    29  
    30  // httpResult is returned by HTTP handlers.
    31  type httpResult struct {
    32  	code int
    33  	err  error
    34  }
    35  
    36  // httpOK is the "everything went fine" HTTP result.
    37  var httpOK = httpResult{code: http.StatusOK}
    38  
    39  // serveIndex serves the index page.
    40  func (m *metricServer) serveIndex(w *httpResponseWriter, req *http.Request) httpResult {
    41  	if req.URL.Path != "/" {
    42  		if strings.HasPrefix(req.URL.Path, "/metrics?") {
    43  			// Prometheus's scrape_config.metrics_path takes in a query path and automatically encodes
    44  			// all special characters in it to %-form, including the "?" character.
    45  			// This can prevent use of query parameters, and we end up here instead.
    46  			// To address this, rewrite the URL to undo this transformation.
    47  			// This means requesting "/metrics%3Ffoo=bar" is rewritten to "/metrics?foo=bar".
    48  			req.URL.RawQuery = strings.TrimPrefix(req.URL.Path, "/metrics?")
    49  			req.URL.Path = "/metrics"
    50  			return m.serveMetrics(w, req)
    51  		}
    52  		return httpResult{http.StatusNotFound, errors.New("path not found")}
    53  	}
    54  	w.WriteString("<html><head><title>runsc metrics</title></head><body>")
    55  	w.WriteString("<p>You have reached the runsc metrics server page!</p>")
    56  	w.WriteString(`<p>To see actual metric data, head over to <a href="/metrics">/metrics</a>.</p>`)
    57  	w.WriteString("</body></html>")
    58  	return httpOK
    59  }
    60  
    61  // httpResponseWriter is a ResponseWriter that also implements io.StringWriter.
    62  type httpResponseWriter struct {
    63  	resp http.ResponseWriter
    64  }
    65  
    66  // Header implements http.ResponseWriter.Header.
    67  func (w *httpResponseWriter) Header() http.Header {
    68  	return w.resp.Header()
    69  }
    70  
    71  // Write implements http.ResponseWriter.Write.
    72  func (w *httpResponseWriter) Write(b []byte) (int, error) {
    73  	return w.resp.Write(b)
    74  }
    75  
    76  // WriteHeader implements http.ResponseWriter.WriteHeader.
    77  func (w *httpResponseWriter) WriteHeader(code int) {
    78  	w.resp.WriteHeader(code)
    79  }
    80  
    81  // WriteString implements io.StringWriter.WriteString.
    82  func (w *httpResponseWriter) WriteString(s string) (int, error) {
    83  	return w.resp.Write([]byte(s))
    84  }
    85  
    86  // logRequest wraps an HTTP handler and adds logging to it.
    87  func logRequest(f func(w *httpResponseWriter, req *http.Request) httpResult) func(w http.ResponseWriter, req *http.Request) {
    88  	return func(w http.ResponseWriter, req *http.Request) {
    89  		log.Infof("Request: %s %s", req.Method, req.URL.Path)
    90  		defer func() {
    91  			if r := recover(); r != nil {
    92  				log.Warningf("Request: %s %s: Panic:\n%v", req.Method, req.URL.Path, r)
    93  			}
    94  		}()
    95  		result := f(&httpResponseWriter{resp: w}, req)
    96  		if result.err != nil {
    97  			http.Error(w, result.err.Error(), result.code)
    98  			log.Warningf("Request: %s %s: Failed with HTTP code %d: %v", req.Method, req.URL.Path, result.code, result.err)
    99  		}
   100  		// Run GC after every request to keep memory usage as predictable and as flat as possible.
   101  		runtime.GC()
   102  	}
   103  }