...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/metrics/chaos-dashboard.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/metrics

     1  // Copyright 2021 Chaos Mesh 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  
    16  package metrics
    17  
    18  import (
    19  	"strconv"
    20  	"time"
    21  
    22  	"github.com/gin-gonic/gin"
    23  	"github.com/prometheus/client_golang/prometheus"
    24  )
    25  
    26  const chaosDashboardSubsystem = "chaos_dashboard"
    27  
    28  // ChaosDashboardMetricsCollector implements prometheus.Collector interface
    29  type ChaosDashboardMetricsCollector struct {
    30  	httpRequestDuration *prometheus.HistogramVec
    31  }
    32  
    33  // NewChaosDashboardMetricsCollector initializes metrics and collector
    34  func NewChaosDashboardMetricsCollector(engine *gin.Engine, registry *prometheus.Registry) *ChaosDashboardMetricsCollector {
    35  	collector := &ChaosDashboardMetricsCollector{
    36  		httpRequestDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
    37  			Subsystem: chaosDashboardSubsystem,
    38  			Name:      "http_request_duration_seconds",
    39  			Help:      "Time histogram for each HTTP query",
    40  		}, []string{"path", "method", "status"}),
    41  	}
    42  
    43  	engine.Use(collector.ginMetricsCollector())
    44  	registry.MustRegister(collector)
    45  
    46  	return collector
    47  }
    48  
    49  // Describe implements the prometheus.Collector interface.
    50  func (collector *ChaosDashboardMetricsCollector) Describe(ch chan<- *prometheus.Desc) {
    51  	collector.httpRequestDuration.Describe(ch)
    52  }
    53  
    54  // Collect implements the prometheus.Collector interface.
    55  func (collector *ChaosDashboardMetricsCollector) Collect(ch chan<- prometheus.Metric) {
    56  	collector.httpRequestDuration.Collect(ch)
    57  }
    58  
    59  func (collector *ChaosDashboardMetricsCollector) ginMetricsCollector() gin.HandlerFunc {
    60  	return func(ctx *gin.Context) {
    61  		begin := time.Now()
    62  
    63  		ctx.Next()
    64  
    65  		collector.httpRequestDuration.WithLabelValues(ctx.FullPath(), ctx.Request.Method, strconv.Itoa(ctx.Writer.Status())).
    66  			Observe(time.Since(begin).Seconds())
    67  	}
    68  }
    69