github.com/looshlee/beatles@v0.0.0-20220727174639-742810ab631c/pkg/metrics/middleware.go (about)

     1  // Copyright 2017-2019 Authors of Cilium
     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 metrics
    16  
    17  import (
    18  	"net/http"
    19  	"strconv"
    20  	"strings"
    21  
    22  	"github.com/cilium/cilium/pkg/spanstat"
    23  
    24  	"github.com/prometheus/client_golang/prometheus"
    25  )
    26  
    27  // APIEventTSHelper is intended to be a global middleware to track metrics
    28  // around API calls.
    29  // It records the timestamp of an API call in the provided gauge.
    30  type APIEventTSHelper struct {
    31  	Next      http.Handler
    32  	TSGauge   prometheus.Gauge
    33  	Histogram prometheus.ObserverVec
    34  }
    35  
    36  type responderWrapper struct {
    37  	http.ResponseWriter
    38  	code int
    39  }
    40  
    41  func (rw *responderWrapper) WriteHeader(code int) {
    42  	rw.code = code
    43  	rw.ResponseWriter.WriteHeader(code)
    44  }
    45  
    46  // getShortPath returns the API path trimmed after the 3rd slash.
    47  // examples:
    48  //  "/v1/config" -> "/v1/config"
    49  //  "/v1/endpoint/cilium-local:0" -> "/v1/endpoint"
    50  //  "/v1/endpoint/container-id:597.." -> "/v1/endpoint"
    51  func getShortPath(s string) string {
    52  	var idxSum int
    53  	for nThSlash := 0; nThSlash < 3; nThSlash++ {
    54  		idx := strings.IndexByte(s[idxSum:], '/')
    55  		if idx == -1 {
    56  			return s
    57  		}
    58  		idxSum += idx + 1
    59  	}
    60  	return s[:idxSum-1]
    61  }
    62  
    63  // ServeHTTP implements the http.Handler interface. It records the timestamp
    64  // this API call began at, then chains to the next handler.
    65  func (m *APIEventTSHelper) ServeHTTP(r http.ResponseWriter, req *http.Request) {
    66  	m.TSGauge.SetToCurrentTime()
    67  	duration := spanstat.Start()
    68  	rw := &responderWrapper{ResponseWriter: r}
    69  	m.Next.ServeHTTP(rw, req)
    70  	if req != nil && req.URL != nil && req.URL.Path != "" {
    71  		path := getShortPath(req.URL.Path)
    72  		took := float64(duration.End(true).Total().Seconds())
    73  		m.Histogram.WithLabelValues(path, req.Method, strconv.Itoa(rw.code)).Observe(took)
    74  	}
    75  }