|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "net" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "strconv" |
| 11 | + "sync" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/charmbracelet/log" |
| 15 | + "github.com/eko/gocache/lib/v4/cache" |
| 16 | + "github.com/eko/gocache/lib/v4/store" |
| 17 | + gocachestore "github.com/eko/gocache/store/go_cache/v4" |
| 18 | + "github.com/gosimple/slug" |
| 19 | + "github.com/jamesog/iptoasn" |
| 20 | + "github.com/mcstatus-io/mcutil/v4/status" |
| 21 | + gocache "github.com/patrickmn/go-cache" |
| 22 | + "github.com/prometheus/client_golang/prometheus" |
| 23 | + "github.com/prometheus/client_golang/prometheus/promhttp" |
| 24 | + "gopkg.in/yaml.v3" |
| 25 | +) |
| 26 | + |
| 27 | +type Server struct { |
| 28 | + Name string `yaml:"name"` |
| 29 | + Address string `yaml:"address"` |
| 30 | + Disabled bool `yaml:"disabled"` |
| 31 | +} |
| 32 | + |
| 33 | +type Config struct { |
| 34 | + Java []Server `yaml:"java"` |
| 35 | + Bedrock []Server `yaml:"bedrock"` |
| 36 | +} |
| 37 | + |
| 38 | +var config Config |
| 39 | + |
| 40 | +var asnLookupCacheClient = gocache.New(1*time.Hour, 10*time.Minute) |
| 41 | +var asnLookupCacheStore = gocachestore.NewGoCache(asnLookupCacheClient) |
| 42 | +var asnLookupCache = cache.New[iptoasn.IP](asnLookupCacheStore) |
| 43 | + |
| 44 | +var promGauge = prometheus.NewGaugeVec(prometheus.GaugeOpts{ |
| 45 | + Name: "minecraft_status_players_online_count", |
| 46 | + Help: "Minecraft server online player count", |
| 47 | +}, []string{"server_edition", "server_name", "server_slug", "server_host", "as_number", "as_name"}) |
| 48 | + |
| 49 | +func getEnv(key, fallback string) string { |
| 50 | + value, exists := os.LookupEnv(key) |
| 51 | + if !exists { |
| 52 | + value = fallback |
| 53 | + } |
| 54 | + return value |
| 55 | +} |
| 56 | + |
| 57 | +func index(w http.ResponseWriter, r *http.Request) { |
| 58 | + _, err := fmt.Fprintf(w, "mcstatus-exporter") |
| 59 | + if err != nil { |
| 60 | + return |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +func query(edition string, name string, queryHostname string) { |
| 65 | + executionTimer := time.Now() |
| 66 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) |
| 67 | + defer cancel() |
| 68 | + |
| 69 | + var resolvedHostname string = queryHostname |
| 70 | + var playercount *int64 |
| 71 | + |
| 72 | + switch edition { |
| 73 | + case "java": |
| 74 | + response, err := status.Modern(ctx, queryHostname, 25565) |
| 75 | + if err != nil { |
| 76 | + log.Error("failed to get response: "+err.Error(), "edition", edition, "hostname", queryHostname) |
| 77 | + return |
| 78 | + } |
| 79 | + playercount = response.Players.Online |
| 80 | + if response.SRVRecord != nil { |
| 81 | + resolvedHostname = response.SRVRecord.Host |
| 82 | + } |
| 83 | + case "bedrock": |
| 84 | + response, err := status.Bedrock(ctx, queryHostname, 19132) |
| 85 | + if err != nil { |
| 86 | + log.Error("failed to get response: "+err.Error(), "edition", edition, "hostname", queryHostname) |
| 87 | + return |
| 88 | + } |
| 89 | + playercount = response.OnlinePlayers |
| 90 | + // Bedrock doesn't have SRV records so no need to handle those |
| 91 | + default: |
| 92 | + log.Error(fmt.Errorf("unknown edition: %s", edition)) |
| 93 | + panic("unknown edition") |
| 94 | + } |
| 95 | + |
| 96 | + resolvedIP, err := net.LookupIP(resolvedHostname) |
| 97 | + if err != nil { |
| 98 | + log.Error(err.Error(), "hostname", resolvedHostname) |
| 99 | + return |
| 100 | + } |
| 101 | + |
| 102 | + ip, err := asnLookupCache.Get(ctx, resolvedIP[0]) |
| 103 | + if errors.Is(err, store.NotFound{}) { |
| 104 | + log.Info("performing uncached asn lookup", "ip", resolvedIP[0]) |
| 105 | + ip, err = iptoasn.LookupIP(fmt.Sprint(resolvedIP[0])) |
| 106 | + // TODO: probably want to continue with fallback N/A AS values if this fails |
| 107 | + if err != nil { |
| 108 | + panic(err) |
| 109 | + } |
| 110 | + |
| 111 | + err = asnLookupCache.Set(ctx, resolvedIP[0], ip) |
| 112 | + if err != nil { |
| 113 | + panic(err) |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + log.Debug("resolved", "hostname", resolvedHostname, "ip", ip.IP, "asn", ip.ASNum) |
| 118 | + |
| 119 | + log.Info("finished querying server ", "edition", edition, "name", name, "players", strconv.FormatInt(*playercount, 10), "execTimeMs", time.Since(executionTimer).Milliseconds()) |
| 120 | + |
| 121 | + promGauge.WithLabelValues(edition, name, slug.Make(name), queryHostname, strconv.Itoa(int(ip.ASNum)), ip.ASName).Set(float64(*playercount)) |
| 122 | +} |
| 123 | + |
| 124 | +func queryServers(servers []Server, serverType string, wg *sync.WaitGroup) { |
| 125 | + for _, server := range servers { |
| 126 | + if !server.Disabled { |
| 127 | + wg.Add(1) |
| 128 | + go func(server Server) { |
| 129 | + defer wg.Done() |
| 130 | + query(serverType, server.Name, server.Address) |
| 131 | + }(server) |
| 132 | + } |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +func promMetrics(w http.ResponseWriter, r *http.Request) { |
| 137 | + var wg sync.WaitGroup |
| 138 | + |
| 139 | + queryServers(config.Java, "java", &wg) |
| 140 | + queryServers(config.Bedrock, "bedrock", &wg) |
| 141 | + |
| 142 | + wg.Wait() |
| 143 | + |
| 144 | + promhttp.Handler().ServeHTTP(w, r) |
| 145 | +} |
| 146 | + |
| 147 | +func updateConfig() { |
| 148 | + file, err := os.Open(getenv("CONFIG_FILE", "servers.yaml")) |
| 149 | + if err != nil { |
| 150 | + log.Fatalf("error opening YAML file: %v", err) |
| 151 | + panic(err) |
| 152 | + } |
| 153 | + defer file.Close() |
| 154 | + |
| 155 | + decoder := yaml.NewDecoder(file) |
| 156 | + err = decoder.Decode(&config) |
| 157 | + if err != nil { |
| 158 | + log.Fatalf("error decoding YAML: %v", err) |
| 159 | + panic(err) |
| 160 | + } |
| 161 | + |
| 162 | + log.Info("loaded config", "java", len(config.Java), "bedrock", len(config.Bedrock)) |
| 163 | +} |
| 164 | + |
| 165 | +func main() { |
| 166 | + log.Info("mcstatus-exporter") |
| 167 | + updateConfig() |
| 168 | + |
| 169 | + http.HandleFunc("/", index) |
| 170 | + prometheus.MustRegister(promGauge) |
| 171 | + http.HandleFunc("/metrics", promMetrics) |
| 172 | + |
| 173 | + var httpBindAddr string = getEnv("BIND", ":8080") |
| 174 | + log.Infof("listening on %s", httpBindAddr) |
| 175 | + err := http.ListenAndServe(httpBindAddr, nil) |
| 176 | + if err != nil { |
| 177 | + log.Error(err, "error starting HTTP server") |
| 178 | + panic(err) |
| 179 | + } |
| 180 | +} |
0 commit comments