Skip to content

Commit

Permalink
feat: add .golangci.yaml and fix issues (#63)
Browse files Browse the repository at this point in the history
Signed-off-by: Engin Diri <engin.diri@mail.schwarz>
  • Loading branch information
Engin Diri authored Dec 7, 2021
1 parent 2800258 commit 3d4a320
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 53 deletions.
31 changes: 31 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -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
21 changes: 12 additions & 9 deletions cmd/minecraft-exporter/main.go → cmd/minecraftExporter/main.go
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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{},
Expand All @@ -30,19 +30,22 @@ 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))

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)
Expand Down
6 changes: 4 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
@@ -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()
}
10 changes: 1 addition & 9 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package config

import (
"io/ioutil"
"os"
"path/filepath"

Expand Down Expand Up @@ -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
}
Expand Down
61 changes: 28 additions & 33 deletions pkg/exporter/exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,26 @@ 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"
)

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
Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down

0 comments on commit 3d4a320

Please sign in to comment.