-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathmain.go
More file actions
235 lines (203 loc) · 5.75 KB
/
main.go
File metadata and controls
235 lines (203 loc) · 5.75 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/charmbracelet/log"
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/store"
gocachestore "github.com/eko/gocache/store/go_cache/v4"
"github.com/fsnotify/fsnotify"
"github.com/gosimple/slug"
"github.com/jamesog/iptoasn"
"github.com/mcstatus-io/mcutil/v4/status"
gocache "github.com/patrickmn/go-cache"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gopkg.in/yaml.v3"
)
type Server struct {
Name string `yaml:"name"`
Address string `yaml:"address"`
Disabled bool `yaml:"disabled"`
}
type Config struct {
Java []Server `yaml:"java"`
Bedrock []Server `yaml:"bedrock"`
}
var config Config
var asnLookupCacheClient = gocache.New(1*time.Hour, 10*time.Minute)
var asnLookupCacheStore = gocachestore.NewGoCache(asnLookupCacheClient)
var asnLookupCache = cache.New[iptoasn.IP](asnLookupCacheStore)
var promGauge = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "minecraft_status_players_online_count",
Help: "Minecraft server online player count",
}, []string{"server_edition", "server_name", "server_slug", "server_host", "as_number", "as_name"})
func getEnv(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = fallback
}
return value
}
func index(w http.ResponseWriter) {
_, err := fmt.Fprintf(w, "mcstatus-exporter")
if err != nil {
return
}
}
func query(edition string, name string, queryHostname string) {
executionTimer := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
var resolvedHostname string = queryHostname
var playercount *int64
switch edition {
case "java":
response, err := status.Modern(ctx, queryHostname, 25565)
if err != nil {
log.Error("failed to get response: "+err.Error(), "edition", edition, "hostname", queryHostname)
return
}
playercount = response.Players.Online
if response.SRVRecord != nil {
resolvedHostname = response.SRVRecord.Host
}
case "bedrock":
response, err := status.Bedrock(ctx, queryHostname, 19132)
if err != nil {
log.Error("failed to get response: "+err.Error(), "edition", edition, "hostname", queryHostname)
return
}
playercount = response.OnlinePlayers
// Bedrock doesn't have SRV records so no need to handle those
default:
log.Error(fmt.Errorf("unknown edition: %s", edition))
panic("unknown edition")
}
resolvedIP, err := net.LookupIP(resolvedHostname)
if err != nil {
log.Error(err.Error(), "hostname", resolvedHostname)
return
}
ip, err := asnLookupCache.Get(ctx, resolvedIP[0])
if errors.Is(err, store.NotFound{}) {
log.Info("performing uncached asn lookup", "ip", resolvedIP[0])
ip, err = iptoasn.LookupIP(fmt.Sprint(resolvedIP[0]))
if err != nil {
log.Error("unable to resolve asn: "+err.Error(), "hostname", resolvedHostname)
ip = iptoasn.IP{ASName: "N/A", ASNum: 0, IP: resolvedHostname}
} else {
err = asnLookupCache.Set(ctx, resolvedIP[0], ip)
if err != nil {
panic(err)
}
}
}
log.Debug("resolved", "hostname", resolvedHostname, "ip", ip.IP, "asn", ip.ASNum)
var pc string = "N/A"
if playercount != nil {
pc = strconv.FormatInt(int64(*playercount), 10)
}
log.Info("finished querying server ", "edition", edition, "name", name, "players", pc, "execTimeMs", time.Since(executionTimer).Milliseconds())
if playercount != nil {
promGauge.WithLabelValues(edition, name, slug.Make(name), queryHostname, strconv.Itoa(int(ip.ASNum)), ip.ASName).Set(float64(*playercount))
}
}
func queryServers(servers []Server, serverType string, wg *sync.WaitGroup) {
for _, server := range servers {
if !server.Disabled {
wg.Add(1)
go func(server Server) {
defer wg.Done()
query(serverType, server.Name, server.Address)
}(server)
}
}
}
func promMetrics(w http.ResponseWriter, r *http.Request) {
var wg sync.WaitGroup
promGauge.Reset()
queryServers(config.Java, "java", &wg)
queryServers(config.Bedrock, "bedrock", &wg)
wg.Wait()
promhttp.Handler().ServeHTTP(w, r)
}
func reloadConfig(path string) {
file, err := os.Open(path)
if err != nil {
log.Fatalf("error opening YAML file: %v", err)
panic(err)
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
panic(err)
}
}(file)
decoder := yaml.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
log.Fatalf("error decoding YAML: %v", err)
panic(err)
}
log.Info("loaded config", "java", len(config.Java), "bedrock", len(config.Bedrock))
}
func watchConfig(path string) {
go func() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Error("unable to hot reload configuration: " + err.Error())
return
}
defer func() {
err := watcher.Close()
if err != nil {
log.Error("failed to close watcher: " + err.Error())
}
}()
err = watcher.Add(path)
if err != nil {
log.Error("unable to hot reload configuration: " + err.Error())
return
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Has(fsnotify.Write) {
log.Info("detected config file change, reloading")
reloadConfig(path)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Error("error while watching config file: ", err.Error())
}
}
}()
}
func main() {
log.Info("mcstatus-exporter")
var cfgFile = getEnv("CONFIG_FILE", "servers.yaml")
reloadConfig(cfgFile)
watchConfig(cfgFile)
prometheus.MustRegister(promGauge)
http.HandleFunc("/metrics", promMetrics)
var httpBindAddr = getEnv("BIND", ":8080")
log.Infof("listening on %s", httpBindAddr)
err := http.ListenAndServe(httpBindAddr, nil)
if err != nil {
log.Error(err, "error starting HTTP server")
panic(err)
}
}