forked from itzg/mc-monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prom_cmd.go
81 lines (65 loc) · 2.2 KB
/
prom_cmd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"context"
"flag"
"github.com/google/subcommands"
"github.com/itzg/go-flagsfiller"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
"log"
"net/http"
"strconv"
"time"
)
const promExportPath = "/metrics"
type exportPrometheusCmd struct {
Servers []string `usage:"one or more [host:port] addresses of Java servers to monitor, when port is omitted 25565 is used"`
BedrockServers []string `usage:"one or more [host:port] addresses of Bedrock servers to monitor, when port is omitted 19132 is used"`
Port int `usage:"HTTP port where Prometheus metrics are exported" default:"8080"`
Timeout time.Duration `usage:"timeout when checking each servers" default:"60s" env:"TIMEOUT"`
logger *zap.Logger
}
func (c *exportPrometheusCmd) Name() string {
return "export-for-prometheus"
}
func (c *exportPrometheusCmd) Synopsis() string {
return "Registers an HTTP metrics endpoints for Prometheus export"
}
func (c *exportPrometheusCmd) Usage() string {
return ""
}
func (c *exportPrometheusCmd) SetFlags(f *flag.FlagSet) {
filler := flagsfiller.New(flagsfiller.WithEnv("Export"))
err := filler.Fill(f, c)
if err != nil {
log.Fatal(err)
}
}
func (c *exportPrometheusCmd) Execute(_ context.Context, _ *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {
if (len(c.Servers) + len(c.BedrockServers)) == 0 {
printUsageError("requires at least one server")
return subcommands.ExitUsageError
}
logger := args[0].(*zap.Logger)
collectors, err := newPromCollectors(c.Servers, c.BedrockServers, logger)
if err != nil {
log.Fatal(err)
}
for i := range collectors {
collectors[i].SetTimeout(c.Timeout)
}
err = prometheus.Register(collectors)
if err != nil {
log.Fatal(err)
}
exportAddress := ":" + strconv.Itoa(c.Port)
logger.Info("exporting metrics for prometheus",
zap.String("address", exportAddress),
zap.String("path", promExportPath),
)
http.Handle(promExportPath, promhttp.Handler())
log.Fatal(http.ListenAndServe(exportAddress, nil))
// never actually returns from ListenAndServe, so just satisfy return value
return subcommands.ExitFailure
}