Skip to content

Commit

Permalink
Misc/cleanup (#34)
Browse files Browse the repository at this point in the history
* build(docker): remove as it doesn't make sense for this

* chore(lefthook): remove unused

* style(golangci-lint): add config

* refactor: rewire password handling

* style: fix lint issues

* fix: more lint issues

* style(golangci-lint): update config re: deprecated linters
  • Loading branch information
jlucktay authored Aug 21, 2021
1 parent 3b45fa6 commit d5c0f7f
Show file tree
Hide file tree
Showing 11 changed files with 186 additions and 32 deletions.
130 changes: 130 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,132 @@
issues:
exclude-use-default: false
exclude:
- ^exported var `Err[A-Za-z]+` should have comment or be unexported$
- ^should have a package comment, unless it's in another file for this package$
max-issues-per-linter: 0
max-same-issues: 0

linters-settings:
dogsled:
max-blank-identifiers: 2

dupl:
threshold: 50

errcheck:
check-type-assertions: true
check-blank: true

errorlint:
errorf: true

gci:
local-prefixes: go.jlucktay.dev/factorio-server-kit/goppuku

goconst:
min-len: 3
min-occurrences: 3

godot:
capital: true
scope: toplevel

gofmt:
simplify: true

gofumpt:
extra-rules: true

govet:
check-shadowing: true
enable-all: true

lll:
line-length: 120
tab-width: 2

nakedret:
max-func-lines: 25

nestif:
min-complexity: 4

nolintlint:
# Exclude following linters from requiring an explanation. Default is [].
allow-no-explanation: []

allow-unused: false
allow-leading-space: false
require-explanation: true
require-specific: true

revive:
min-confidence: 0

unparam:
check-exported: true

whitespace:
multi-if: false
multi-func: false

wsl:
strict-append: true
allow-assign-and-call: true
allow-multiline-assign: true
allow-cuddle-declarations: false
allow-trailing-comment: false
force-case-trailing-whitespace: 0
force-err-cuddling: true
allow-separated-leading-comment: false

linters:
enable:
- asciicheck
- bodyclose
- deadcode
- dogsled
- dupl
- errcheck
- errorlint
- gci
- goconst
- gocritic
- godot
- godox
- goerr113
- gofmt
- gofumpt
- gosec
- gosimple
- govet
- ineffassign
- lll
- nakedret
- nestif
- nlreturn
- noctx
- nolintlint
- revive
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace
- wrapcheck
- wsl

output:
format: tab
print-issued-lines: true
print-linter-name: true
uniq-by-line: true
sort-results: true

run:
modules-download-mode: readonly
timeout: 1m
5 changes: 0 additions & 5 deletions Dockerfile

This file was deleted.

2 changes: 2 additions & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Package cmd holds pretty much everything, and needs a good refactoring.
package cmd
9 changes: 6 additions & 3 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ type config struct {
}

type configRcon struct {
BackoffMin time.Duration `env:"GOPPUKU_BACKOFF_MIN_DURATION" env-default:"10s"`
BackoffMax time.Duration `env:"GOPPUKU_BACKOFF_MAX_DURATION" env-default:"5m"`
BackoffFactor float64 `env:"GOPPUKU_BACKOFF_FACTOR" env-default:"1.2"`
Password string `env:"GOPPUKU_RCON_PASSWORD"`

BackoffMin time.Duration `env:"GOPPUKU_BACKOFF_MIN_DURATION" env-default:"10s"`
BackoffMax time.Duration `env:"GOPPUKU_BACKOFF_MAX_DURATION" env-default:"5m"`

BackoffFactor float64 `env:"GOPPUKU_BACKOFF_FACTOR" env-default:"1.2"`
}

type configMonitor struct {
Expand Down
7 changes: 6 additions & 1 deletion cmd/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ func monitor(logger *logging.Logger, cfg config) {
continue
}

r.Close()
if errClose := r.Close(); errClose != nil {
logger.Log(logging.Entry{
Payload: fmt.Errorf("error closing RCON: %w", errClose),
Severity: logging.Error,
})
}

logger.Log(logging.Entry{
Payload: fmt.Sprintf("%+v", players),
Expand Down
6 changes: 5 additions & 1 deletion cmd/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ func mustGetPassword(l *logging.Logger) string {
Payload: fmt.Errorf("error reading password file: %w", errRF),
Severity: logging.Critical,
})
l.Flush()

if err := l.Flush(); err != nil {
fmt.Fprintf(os.Stderr, "could not flush logger: %v", err)
}

os.Exit(1)
}

Expand Down
11 changes: 9 additions & 2 deletions cmd/rcon.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,20 @@ func dialAndAuth(logger *logging.Logger, cfg configRcon) *rcon.RCON {
continue
}

errAuth = r.Authenticate(mustGetPassword(logger))
errAuth = r.Authenticate(cfg.Password)
if errAuth != nil {
logger.Log(logging.Entry{
Payload: fmt.Errorf("error authenticating to address '%s': %w", rconAddress, errAuth),
Severity: logging.Error,
})
r.Close()

if errClose := r.Close(); errClose != nil {
logger.Log(logging.Entry{
Payload: fmt.Errorf("error closing RCON: %w", errClose),
Severity: logging.Error,
})
}

time.Sleep(b.Duration())
}
}
Expand Down
35 changes: 25 additions & 10 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ const logName = "goppuku"
// Address of RCON server.
const rconAddress = "127.0.0.1:27015"

func Run(_ []string, _ io.Writer) error {
// Run is the core of goppuku's logic/flow.
func Run(_ []string, stderr io.Writer) error {
// GCP project to send Stackdriver logs to.
projectID, err := metadata.ProjectID()
if err != nil {
Expand All @@ -35,31 +36,37 @@ func Run(_ []string, _ io.Writer) error {
if err != nil {
return fmt.Errorf("failed to create logging client: %w", err)
}
defer client.Close()
defer client.Close() //nolint:errcheck // Don't let the door hit you on the way out
logger := client.Logger(logName)

// Handle incoming signals
cleanup := make(chan os.Signal)
cleanup := make(chan os.Signal, 1)
signal.Notify(cleanup, os.Interrupt, syscall.SIGTERM)

go func(l *logging.Logger) {
<-cleanup
l.Flush()

if err := l.Flush(); err != nil {
fmt.Fprintf(stderr, "could not flush logger: %v", err)
}

os.Exit(1)
}(logger)

// Finish setting up logger
notice := logger.StandardLogger(logging.Notice)
notice.SetPrefix(fmt.Sprintf("%s[%d]: ", logName, os.Getpid()))
notice.Print(versionDetails())

notice.Printf("Loading configuration from environment...")
notice.Print("Loading configuration from environment...")

var cfg config

errReadConf := cleanenv.ReadEnv(&cfg)
if errReadConf != nil {
envDesc, _ := cleanenv.GetDescription(&cfg, nil)
envDesc, errGetDesc := cleanenv.GetDescription(&cfg, nil)
if errGetDesc != nil {
return fmt.Errorf("could not get description of environment variables: %w", errGetDesc)
}

logger.Log(logging.Entry{
Payload: envDesc,
Expand All @@ -76,15 +83,23 @@ func Run(_ []string, _ io.Writer) error {

notice.Printf("Configuration loaded:\n%s", spew.Sdump(cfg))

// Store password in config struct _after_ spewing out all of the other settings
cfg.RCON.Password = mustGetPassword(logger)

// Main loop
monitor(logger, cfg)

// Server seppuku
cmd := exec.Command("shutdown", "--poweroff", "now")
notice.Printf("Calling shutdown command: '%+v'", cmd)
logger.Flush()
notice.Printf("Calling shutdown command: '%s'", cmd)

_ = cmd.Start()
if err := logger.Flush(); err != nil {
return fmt.Errorf("could not flush logger: %w", err)
}

if err := cmd.Start(); err != nil {
return fmt.Errorf("error starting '%s' command: %w", cmd, err)
}

return nil
}
2 changes: 1 addition & 1 deletion cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
)

// Take ldflags from GoReleaser.
var version, commit, date, builtBy string //nolint:gochecknoglobals
var version, commit, date, builtBy string //nolint:gochecknoglobals // Symbols used by goreleaser via ldflags

func versionDetails() string {
return fmt.Sprintf("goppuku %s built from commit %s with %s on %s by %s.",
Expand Down
4 changes: 2 additions & 2 deletions goppuku.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import (
)

func main() {
if err := cmd.Run(os.Args, os.Stdout); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
if err := cmd.Run(os.Args, os.Stderr); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)

return
}
Expand Down
7 changes: 0 additions & 7 deletions lefthook.yml

This file was deleted.

0 comments on commit d5c0f7f

Please sign in to comment.