Code refactoring for bpa operator
[icn.git] / cmd / bpa-operator / vendor / github.com / operator-framework / operator-sdk / pkg / kube-metrics / server.go
1 // Copyright 2019 The Operator-SDK 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 kubemetrics
16
17 import (
18         "fmt"
19         "net"
20         "net/http"
21
22         kcollector "k8s.io/kube-state-metrics/pkg/collector"
23 )
24
25 const (
26         metricsPath = "/metrics"
27         healthzPath = "/healthz"
28 )
29
30 func ServeMetrics(collectors [][]kcollector.Collector, host string, port int32) {
31         listenAddress := net.JoinHostPort(host, fmt.Sprint(port))
32         mux := http.NewServeMux()
33         // Add metricsPath
34         mux.Handle(metricsPath, &metricHandler{collectors})
35         // Add healthzPath
36         mux.HandleFunc(healthzPath, func(w http.ResponseWriter, r *http.Request) {
37                 w.WriteHeader(200)
38                 w.Write([]byte("ok"))
39         })
40         // Add index
41         mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
42                 w.Write([]byte(`<html>
43              <head><title>Operator SDK Metrics</title></head>
44              <body>
45              <h1>kube-metrics</h1>
46                          <ul>
47              <li><a href='` + metricsPath + `'>metrics</a></li>
48              <li><a href='` + healthzPath + `'>healthz</a></li>
49                          </ul>
50              </body>
51              </html>`))
52         })
53         err := http.ListenAndServe(listenAddress, mux)
54         log.Error(err, "Failed to serve custom metrics")
55 }
56
57 type metricHandler struct {
58         collectors [][]kcollector.Collector
59 }
60
61 func (m *metricHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
62         resHeader := w.Header()
63         // 0.0.4 is the exposition format version of prometheus
64         // https://prometheus.io/docs/instrumenting/exposition_formats/#text-based-format
65         resHeader.Set("Content-Type", `text/plain; version=`+"0.0.4")
66         for _, collectors := range m.collectors {
67                 for _, c := range collectors {
68                         c.Collect(w)
69                 }
70         }
71 }