|
| 1 | +// Copyright 2023 The Prometheus Authors |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | +package toolkit |
| 14 | + |
| 15 | +import ( |
| 16 | + "errors" |
| 17 | + "net/http" |
| 18 | + "os" |
| 19 | + |
| 20 | + "github.com/go-kit/log" |
| 21 | + "github.com/go-kit/log/level" |
| 22 | + "github.com/prometheus/exporter-toolkit/web" |
| 23 | +) |
| 24 | + |
| 25 | +var ( |
| 26 | + ErrNoFlagConfig = errors.New("Missing FlagConfig") |
| 27 | + ErrNoHandler = errors.New("Missing one of MetricsHandler or MetricsHandlerFunc") |
| 28 | + ErrOneHandler = errors.New("Only one of MetricsHandler or MetricsHandlerFunc allowed") |
| 29 | +) |
| 30 | + |
| 31 | +type Config struct { |
| 32 | + MetricsHandler http.Handler |
| 33 | + MetricsHandlerFunc *func(http.ResponseWriter, *http.Request) |
| 34 | + FlagConfig *web.FlagConfig |
| 35 | + LandingConfig web.LandingConfig |
| 36 | + Logger log.Logger |
| 37 | +} |
| 38 | + |
| 39 | +func Run(c Config) error { |
| 40 | + if c.FlagConfig == nil { |
| 41 | + return ErrNoFlagConfig |
| 42 | + } |
| 43 | + err := c.FlagConfig.CheckFlags() |
| 44 | + if err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + if c.MetricsHandler == nil && c.MetricsHandlerFunc == nil { |
| 48 | + return ErrNoHandler |
| 49 | + } |
| 50 | + if c.MetricsHandler != nil && c.MetricsHandlerFunc != nil { |
| 51 | + return ErrOneHandler |
| 52 | + } |
| 53 | + if *c.FlagConfig.MetricsPath != "" && c.MetricsHandler != nil { |
| 54 | + http.Handle(*c.FlagConfig.MetricsPath, c.MetricsHandler) |
| 55 | + } |
| 56 | + if *c.FlagConfig.MetricsPath != "" && c.MetricsHandlerFunc != nil { |
| 57 | + http.HandleFunc(*c.FlagConfig.MetricsPath, *c.MetricsHandlerFunc) |
| 58 | + } |
| 59 | + if *c.FlagConfig.MetricsPath != "/" && *c.FlagConfig.MetricsPath != "" { |
| 60 | + c.LandingConfig.Links = append(c.LandingConfig.Links, |
| 61 | + web.LandingLinks{ |
| 62 | + Address: *c.FlagConfig.MetricsPath, |
| 63 | + Text: "Metrics", |
| 64 | + }, |
| 65 | + ) |
| 66 | + landingPage, err := web.NewLandingPage(c.LandingConfig) |
| 67 | + if err != nil { |
| 68 | + level.Error(c.Logger).Log("err", err) |
| 69 | + os.Exit(1) |
| 70 | + } |
| 71 | + http.Handle("/", landingPage) |
| 72 | + } |
| 73 | + |
| 74 | + srv := &http.Server{} |
| 75 | + return web.ListenAndServe(srv, c.FlagConfig, c.Logger) |
| 76 | +} |
0 commit comments