From 3d4a320eee9f95d38865dfddb8e862940a169388 Mon Sep 17 00:00:00 2001 From: Engin Diri Date: Tue, 7 Dec 2021 22:33:36 +0100 Subject: [PATCH] feat: add .golangci.yaml and fix issues (#63) Signed-off-by: Engin Diri --- .golangci.yaml | 31 ++++++++++ .../main.go | 21 ++++--- main.go | 6 +- pkg/config/config.go | 10 +-- pkg/exporter/exporter.go | 61 +++++++++---------- 5 files changed, 76 insertions(+), 53 deletions(-) create mode 100644 .golangci.yaml rename cmd/{minecraft-exporter => minecraftExporter}/main.go (83%) diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 00000000..968a702c --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,31 @@ +linters: + enable: + - thelper + - gofumpt + - tparallel + - unconvert + - unparam + - wastedassign + - revive + - forbidigo + - tagliatelle + - typecheck + - goconst + - gocritic + - gocyclo + - govet + - errcheck + - gosec + - goimports + - nolintlint + +linters-settings: + forbidigo: + forbid: + - 'ioutil\.*' + tagliatelle: + case: + use-field-name: false + rules: + yaml: goKebab + json: snake diff --git a/cmd/minecraft-exporter/main.go b/cmd/minecraftExporter/main.go similarity index 83% rename from cmd/minecraft-exporter/main.go rename to cmd/minecraftExporter/main.go index a20dd478..20c003b3 100644 --- a/cmd/minecraft-exporter/main.go +++ b/cmd/minecraftExporter/main.go @@ -1,7 +1,10 @@ -package minecraft_exporter +package minecraftExporter import ( - "github.com/go-kit/kit/log/level" + "net/http" + "os" + + "github.com/go-kit/log/level" "github.com/minecraft-exporter/pkg/config" "github.com/minecraft-exporter/pkg/exporter" "github.com/minecraft-exporter/pkg/template" @@ -12,12 +15,9 @@ import ( "github.com/prometheus/common/version" "github.com/prometheus/exporter-toolkit/web" "gopkg.in/alecthomas/kingpin.v2" - "net/http" - "os" ) func Run() { - config := config.NewConfg() promlogConfig := &promlog.Config{ Level: &promlog.AllowedLevel{}, @@ -30,8 +30,8 @@ func Run() { config.LoadFile() - level.Info(logger).Log("msg", "Starting minecraft_exporter", "version", version.Info()) - level.Info(logger).Log("msg", "Build context", "build", version.BuildContext()) + level.Info(logger).Log("msg", "Starting minecraft_exporter", "version", version.Info()) //nolint:errcheck + level.Info(logger).Log("msg", "Build context", "build", version.BuildContext()) //nolint: errcheck prometheus.MustRegister(version.NewCollector("minecraft_exporter")) prometheus.MustRegister(exporter.New(*config.RconAddress, *config.RconPassword, *config.WorldPath, *config.NameSource, config.DisabledMetrics, logger)) @@ -39,10 +39,13 @@ func Run() { http.Handle(*config.MetricsPath, promhttp.Handler()) template := template.NewIndexTemplate() http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - template.Execute(w, config) + err := template.Execute(w, config) + if err != nil { + level.Error(logger).Log("msg", "Error executing template", "err", err) + } }) - level.Info(logger).Log("msg", "Listening on address", "address", *config.ListenAddress) + level.Info(logger).Log("msg", "Listening on address", "address", *config.ListenAddress) //nolint:errcheck srv := &http.Server{Addr: *config.ListenAddress} if err := web.ListenAndServe(srv, *config.WebConfig, logger); err != nil { level.Error(logger).Log("msg", "Error running HTTP server", "err", err) diff --git a/main.go b/main.go index 85b70770..8593308a 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,9 @@ package main -import minecrafexporter "github.com/minecraft-exporter/cmd/minecraft-exporter" +import ( + "github.com/minecraft-exporter/cmd/minecraftExporter" +) func main() { - minecrafexporter.Run() + minecraftExporter.Run() } diff --git a/pkg/config/config.go b/pkg/config/config.go index 92a291f5..d60101e4 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -1,7 +1,6 @@ package config import ( - "io/ioutil" "os" "path/filepath" @@ -51,14 +50,7 @@ func (c *Config) LoadFile() { return } - f, err := os.Open(path) - if err != nil { - return - } - - defer f.Close() - - bytes, err := ioutil.ReadAll(f) + bytes, err := os.ReadFile(path) if err != nil { return } diff --git a/pkg/exporter/exporter.go b/pkg/exporter/exporter.go index 06ede7ce..b72c2e42 100644 --- a/pkg/exporter/exporter.go +++ b/pkg/exporter/exporter.go @@ -3,19 +3,18 @@ package exporter import ( "compress/gzip" "encoding/json" - "errors" "fmt" - "io/ioutil" "net/http" "os" "regexp" "strings" "github.com/Jeffail/gabs/v2" + "github.com/go-kit/log" + "github.com/Tnze/go-mc/nbt" mcnet "github.com/Tnze/go-mc/net" - "github.com/go-kit/kit/log" - "github.com/go-kit/kit/log/level" + "github.com/go-kit/log/level" "github.com/prometheus/client_golang/prometheus" ) @@ -23,7 +22,7 @@ const ( Namespace = "minecraft" ) -//See for all details on the statistics of Minecraft https://minecraft.fandom.com/wiki/Statistics +// See for all details on the statistics of Minecraft https://minecraft.fandom.com/wiki/Statistics type Exporter struct { address string @@ -32,13 +31,13 @@ type Exporter struct { world string source string disabledMetrics map[string]bool - //via advancements - //playerAdvancements *prometheus.Desc + // via advancements + // playerAdvancements *prometheus.Desc - //via RCON + // via RCON playerOnline *prometheus.Desc - //via stats + // via stats playerStat *prometheus.Desc blocksMined *prometheus.Desc @@ -355,7 +354,7 @@ type PlayerData struct { } func (e *Exporter) getPlayerStats(ch chan<- prometheus.Metric) error { - files, err := ioutil.ReadDir(e.world + "/stats") + files, err := os.ReadDir(e.world + "/stats") if err != nil { return err } @@ -389,18 +388,17 @@ func (e *Exporter) getPlayerStats(ch chan<- prometheus.Metric) error { var player Player switch e.source { case "mojang": - URL := "https://api.ashcon.app/mojang/v2/user/" + id - resp, err := http.Get(URL) + resp, err := http.Get(fmt.Sprintf("https://api.ashcon.app/mojang/v2/user/%s", id)) if err != nil { - level.Error(e.logger).Log("msg", "Failed to connect to api.ashcon.app", "err", err) + level.Error(e.logger).Log("msg", "Failed to connect to api.ashcon.app", "err", err) // nolint: errcheck } if resp.StatusCode == 200 { if err := json.NewDecoder(resp.Body).Decode(&player); err != nil { - level.Error(e.logger).Log("msg", "Failed to connect decode response", "err", err) + level.Error(e.logger).Log("msg", "Failed to connect decode response", "err", err) // nolint: errcheck } } else { - return fmt.Errorf("error retrieving player info from api.ashcon.app: %w", errors.New(fmt.Sprintf("Status Code: %d", resp.StatusCode))) + return fmt.Errorf("error retrieving player info from api.ashcon.app: %w", fmt.Errorf(fmt.Sprintf("Status Code: %d", resp.StatusCode))) } err = resp.Body.Close() @@ -429,17 +427,15 @@ func (e *Exporter) getPlayerStats(ch chan<- prometheus.Metric) error { ch <- prometheus.MustNewConstMetric(e.playerStat, prometheus.GaugeValue, float64(data.FoodLevel), player.Name, "food_level") ch <- prometheus.MustNewConstMetric(e.playerStat, prometheus.GaugeValue, float64(data.Health), player.Name, "health") - err2 := e.advancements(id, ch, player.Name) - if err2 != nil { - return err2 + err = e.advancements(id, ch, player.Name) + if err != nil { + return err } - stats, err := os.Open(e.world + "/stats/" + id + ".json") + byteValue, err := os.ReadFile(e.world + "/stats/" + id + ".json") if err != nil { return err } - - byteValue, _ := ioutil.ReadAll(stats) jsonParsed, err := gabs.ParseJSON(byteValue) if err != nil { return err @@ -477,8 +473,10 @@ func (e *Exporter) getPlayerStats(ch chan<- prometheus.Metric) error { e.playerStatsCustomWithType(jsonParsed, e.damageDealt, field, ch, player.Name, damageDealtType) } - movementTypes := []string{"climb", "crouch", "fall", "fly", "sprint", "swim", "walk", "walk_on_water", "walk_under_water", - "boat", "aviate", "horse", "minecart", "pig", "strider"} + movementTypes := []string{ + "climb", "crouch", "fall", "fly", "sprint", "swim", "walk", "walk_on_water", "walk_under_water", + "boat", "aviate", "horse", "minecart", "pig", "strider", + } for _, movementType := range movementTypes { field := fmt.Sprintf("stats.minecraft:custom.minecraft:%s_one_cm", movementType) e.playerStatsCustomMovement(jsonParsed, e.minecraftMovement, field, ch, player.Name, movementType) @@ -494,8 +492,10 @@ func (e *Exporter) getPlayerStats(ch chan<- prometheus.Metric) error { e.playerStatsCustom(jsonParsed, e.fishCaught, "stats.minecraft:custom.minecraft:fish_caught", ch, player.Name) e.playerStatsCustom(jsonParsed, e.leaveGame, "stats.minecraft:custom.minecraft:leave_game", ch, player.Name) - interactionTypes := []string{"anvil", "beacon", "blast_furnace", "brewingstand", "campfire", "cartography_table", - "crafting_table", "furnace", "grindston", "lectern", "loom", "smithing_table", "smoker", "stonecutter"} + interactionTypes := []string{ + "anvil", "beacon", "blast_furnace", "brewingstand", "campfire", "cartography_table", + "crafting_table", "furnace", "grindston", "lectern", "loom", "smithing_table", "smoker", "stonecutter", + } for _, interactionType := range interactionTypes { field := fmt.Sprintf("stats.minecraft:custom.minecraft:interact_with_%s", interactionType) e.playerStatsCustomWithType(jsonParsed, e.interaction, field, ch, player.Name, interactionType) @@ -550,7 +550,7 @@ func (e *Exporter) playerStatsCustomWithType(jsonParsed *gabs.Container, desc *p func (e *Exporter) playerStatsCustomMovement(jsonParsed *gabs.Container, desc *prometheus.Desc, field string, ch chan<- prometheus.Metric, playerName, movementType string) { if e.isEnabled(field) { value, _ := jsonParsed.Path(field).Data().(float64) - value = value / 100 + value /= 100 ch <- prometheus.MustNewConstMetric(desc, prometheus.UntypedValue, value, playerName, movementType) } } @@ -584,12 +584,8 @@ func (e *Exporter) playerStats(jsonParsed *gabs.Container, desc *prometheus.Desc } func (e *Exporter) advancements(id string, ch chan<- prometheus.Metric, playerName string) error { - advancements, err := os.Open(e.world + "/advancements/" + id + ".json") - if err != nil { - return err - } var payload map[string]interface{} - byteValue, err := ioutil.ReadAll(advancements) + byteValue, err := os.ReadFile(e.world + "/advancements/" + id + ".json") if err != nil { return err } @@ -617,13 +613,12 @@ func (e *Exporter) getPlayerList(ch chan<- prometheus.Metric) (retErr error) { conn, err := mcnet.DialRCON(e.address, e.password) if err != nil { return fmt.Errorf("connect rcon error: %w", err) - } defer func() { err := conn.Close() if err != nil { - level.Error(e.logger).Log("msg", "Failed to close rcon endpoint", "err", err) + level.Error(e.logger).Log("msg", "Failed to close rcon endpoint", "err", err) // nolint: errcheck if retErr == nil { retErr = err }