github.com/cs3org/reva/v2@v2.27.7/internal/http/interceptors/prometheus/prometheus.go (about)

     1  // Copyright 2018-2021 CERN
     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  // In applying this license, CERN does not waive the privileges and immunities
    16  // granted to it by virtue of its status as an Intergovernmental Organization
    17  // or submit itself to any jurisdiction.
    18  
    19  package prometheus
    20  
    21  import (
    22  	"net/http"
    23  
    24  	"github.com/cs3org/reva/v2/pkg/rhttp/global"
    25  	"github.com/prometheus/client_golang/prometheus"
    26  	"github.com/prometheus/client_golang/prometheus/promauto"
    27  )
    28  
    29  const (
    30  	defaultPriority = 100
    31  )
    32  
    33  func init() {
    34  	global.RegisterMiddleware("prometheus", New)
    35  }
    36  
    37  // New returns a new HTTP middleware that counts requests for prometheus metrics
    38  func New(m map[string]interface{}) (global.Middleware, int, error) {
    39  	namespace := m["namespace"].(string)
    40  	if namespace == "" {
    41  		namespace = "reva"
    42  	}
    43  	subsystem := m["subsystem"].(string)
    44  	ph := prometheusHandler{
    45  		counter: promauto.NewCounter(prometheus.CounterOpts{
    46  			Namespace: namespace,
    47  			Subsystem: m["subsystem"].(string),
    48  			Name:      "http_requests_total",
    49  			Help:      "The total number of processed " + subsystem + " HTTP requests for " + namespace,
    50  		}),
    51  	}
    52  	return ph.handler, defaultPriority, nil
    53  }
    54  
    55  type prometheusHandler struct {
    56  	h       http.Handler
    57  	counter prometheus.Counter
    58  }
    59  
    60  // handler is a logging middleware
    61  func (ph prometheusHandler) handler(h http.Handler) http.Handler {
    62  	ph.h = h
    63  	return ph
    64  }
    65  
    66  func (ph prometheusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    67  	ph.h.ServeHTTP(w, r)
    68  	ph.counter.Inc()
    69  }