|
| 1 | +/* |
| 2 | +Copyright 2019 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package metrics |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "net" |
| 22 | + "net/http" |
| 23 | + |
| 24 | + "github.com/prometheus/client_golang/prometheus/promhttp" |
| 25 | +) |
| 26 | + |
| 27 | +// ServeMetrics serves the metrics until the stop channel is closed. |
| 28 | +// It serves the metrics on `/metrics` on the port configured through the MetricsBindAddress. |
| 29 | +func ServeMetrics(listener net.Listener, stop <-chan struct{}) error { |
| 30 | + handler := promhttp.HandlerFor(Registry, promhttp.HandlerOpts{ |
| 31 | + ErrorHandling: promhttp.HTTPErrorOnError, |
| 32 | + }) |
| 33 | + // TODO(JoelSpeed): Use existing Kubernetes machinery for serving metrics |
| 34 | + mux := http.NewServeMux() |
| 35 | + mux.Handle("/metrics", handler) |
| 36 | + server := http.Server{ |
| 37 | + Handler: mux, |
| 38 | + } |
| 39 | + |
| 40 | + errc := make(chan error, 0) |
| 41 | + // Run the server |
| 42 | + go func() { |
| 43 | + if err := server.Serve(listener); err != nil && err != http.ErrServerClosed { |
| 44 | + errc <- err |
| 45 | + } |
| 46 | + }() |
| 47 | + |
| 48 | + // Shutdown the server when stop is closed and catch any errors. |
| 49 | + select { |
| 50 | + case err := <-errc: |
| 51 | + return err |
| 52 | + case <-stop: |
| 53 | + if err := server.Shutdown(context.Background()); err != nil { |
| 54 | + return err |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return nil |
| 59 | +} |
0 commit comments