...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/http.go

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

     1  // Copyright 2020 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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package chaosdaemon
    15  
    16  import (
    17  	"net/http"
    18  	"net/http/pprof"
    19  
    20  	"github.com/prometheus/client_golang/prometheus"
    21  	"github.com/prometheus/client_golang/prometheus/promhttp"
    22  )
    23  
    24  type httpServerBuilder struct {
    25  	mux       *http.ServeMux
    26  	addr      string
    27  	profiling bool
    28  	reg       prometheus.Gatherer
    29  }
    30  
    31  func newHTTPServerBuilder() *httpServerBuilder {
    32  	return &httpServerBuilder{
    33  		mux: http.NewServeMux(),
    34  	}
    35  }
    36  
    37  // Addr sets the addr of http server
    38  func (b *httpServerBuilder) Addr(addr string) *httpServerBuilder {
    39  	b.addr = addr
    40  
    41  	return b
    42  }
    43  
    44  // Metrics sets the prometheus gatherer for http server
    45  func (b *httpServerBuilder) Metrics(reg prometheus.Gatherer) *httpServerBuilder {
    46  	b.reg = reg
    47  
    48  	return b
    49  }
    50  
    51  // Profiling turns on or off profiling server of http server
    52  func (b *httpServerBuilder) Profiling(profiling bool) *httpServerBuilder {
    53  	b.profiling = profiling
    54  
    55  	return b
    56  }
    57  
    58  // Build builds an http server
    59  func (b *httpServerBuilder) Build() *http.Server {
    60  	registerMetrics(b.mux, b.reg)
    61  
    62  	if b.profiling {
    63  		registerProfiler(b.mux)
    64  	}
    65  
    66  	return &http.Server{
    67  		Addr:    b.addr,
    68  		Handler: b.mux,
    69  	}
    70  }
    71  
    72  func registerMetrics(mux *http.ServeMux, g prometheus.Gatherer) {
    73  	if g != nil {
    74  		mux.Handle("/metrics", promhttp.HandlerFor(g, promhttp.HandlerOpts{}))
    75  	}
    76  }
    77  
    78  func registerProfiler(mux *http.ServeMux) {
    79  	mux.HandleFunc("/debug/pprof/", pprof.Index)
    80  	mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
    81  	mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
    82  	mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
    83  	mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
    84  }
    85