1 // Copyright 2019 The Operator-SDK Authors
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
22 kcollector "k8s.io/kube-state-metrics/pkg/collector"
26 metricsPath = "/metrics"
27 healthzPath = "/healthz"
30 func ServeMetrics(collectors [][]kcollector.Collector, host string, port int32) {
31 listenAddress := net.JoinHostPort(host, fmt.Sprint(port))
32 mux := http.NewServeMux()
34 mux.Handle(metricsPath, &metricHandler{collectors})
36 mux.HandleFunc(healthzPath, func(w http.ResponseWriter, r *http.Request) {
41 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
42 w.Write([]byte(`<html>
43 <head><title>Operator SDK Metrics</title></head>
47 <li><a href='` + metricsPath + `'>metrics</a></li>
48 <li><a href='` + healthzPath + `'>healthz</a></li>
53 err := http.ListenAndServe(listenAddress, mux)
54 log.Error(err, "Failed to serve custom metrics")
57 type metricHandler struct {
58 collectors [][]kcollector.Collector
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 {