chore: fix some small issues detected by golangci-lint

But not using it as some linters are either plain incorrect (the one
suggesting to not use nil for `c.t.Context()`) or just
debatable (checking for err value is a good practice, but there are
good reasons to opt out in some cases).
This commit is contained in:
Vincent Bernat
2022-08-10 17:44:32 +02:00
parent 17eb5529cf
commit 78fb01c223
17 changed files with 36 additions and 78 deletions

View File

@@ -36,10 +36,8 @@ func StartStopComponents(r *reporter.Reporter, daemonComponent daemon.Component,
Str("version", Version).Str("build-date", BuildDate). Str("version", Version).Str("build-date", BuildDate).
Msg("akvorado has started") Msg("akvorado has started")
select { <-daemonComponent.Terminated()
case <-daemonComponent.Terminated(): r.Info().Msg("stopping all components")
r.Info().Msg("stopping all components")
}
return nil return nil
} }

View File

@@ -57,19 +57,17 @@ func (c *realComponent) Start() error {
// Listen for tombs // Listen for tombs
for _, t := range c.tombs { for _, t := range c.tombs {
go func(t tombWithOrigin) { go func(t tombWithOrigin) {
select { <-t.tomb.Dying()
case <-t.tomb.Dying(): if t.tomb.Err() == nil {
if t.tomb.Err() == nil { c.r.Debug().
c.r.Debug(). Str("component", t.origin).
Str("component", t.origin). Msg("component shutting down, quitting")
Msg("component shutting down, quitting") } else {
} else { c.r.Err(t.tomb.Err()).
c.r.Err(t.tomb.Err()). Str("component", t.origin).
Str("component", t.origin). Msg("component error, quitting")
Msg("component error, quitting")
}
c.Terminate()
} }
c.Terminate()
}(t) }(t)
} }
// On signal, terminate // On signal, terminate

View File

@@ -40,5 +40,4 @@ func (c *MockComponent) Stop() error {
// Track does nothing // Track does nothing
func (c *MockComponent) Track(t *tomb.Tomb, who string) { func (c *MockComponent) Track(t *tomb.Tomb, who string) {
return
} }

View File

@@ -100,26 +100,6 @@ func New(r *reporter.Reporter, configuration Configuration, dependencies Depende
return &c, nil return &c, nil
} }
type responseWriter struct {
http.ResponseWriter
status int
wroteHeader bool
}
func (rw *responseWriter) Status() int {
return rw.status
}
func (rw *responseWriter) WriteHeader(code int) {
if rw.wroteHeader {
return
}
rw.status = code
rw.ResponseWriter.WriteHeader(code)
rw.wroteHeader = true
return
}
// AddHandler registers a new handler for the web server // AddHandler registers a new handler for the web server
func (c *Component) AddHandler(location string, handler http.Handler) { func (c *Component) AddHandler(location string, handler http.Handler) {
l := c.r.With().Str("handler", location).Logger() l := c.r.With().Str("handler", location).Logger()
@@ -175,16 +155,14 @@ func (c *Component) Start() error {
// Gracefully stop when asked to // Gracefully stop when asked to
c.t.Go(func() error { c.t.Go(func() error {
select { <-c.t.Dying()
case <-c.t.Dying(): ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel()
defer cancel() if err := server.Shutdown(ctx); err != nil {
if err := server.Shutdown(ctx); err != nil { c.r.Err(err).Msg("unable to shutdown HTTP server")
c.r.Err(err).Msg("unable to shutdown HTTP server") return fmt.Errorf("unable to shutdown HTTP server: %w", err)
return fmt.Errorf("unable to shutdown HTTP server: %w", err)
}
return nil
} }
return nil
}) })
return nil return nil
} }

View File

@@ -73,10 +73,8 @@ func TestHealthcheckCancelContext(t *testing.T) {
return reporter.HealthcheckResult{reporter.HealthcheckOK, "all well"} return reporter.HealthcheckResult{reporter.HealthcheckOK, "all well"}
}) })
r.RegisterHealthcheck("hc2", func(ctx context.Context) reporter.HealthcheckResult { r.RegisterHealthcheck("hc2", func(ctx context.Context) reporter.HealthcheckResult {
select { <-ctx.Done()
case <-ctx.Done(): return reporter.HealthcheckResult{reporter.HealthcheckError, "I am late, sorry"}
return reporter.HealthcheckResult{reporter.HealthcheckError, "I am late, sorry"}
}
}) })
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
go func() { go func() {

View File

@@ -14,16 +14,12 @@ import (
"io/fs" "io/fs"
"math/rand" "math/rand"
"net/http" "net/http"
"regexp"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
var ( //go:embed data/avatars
//go:embed data/avatars var avatarParts embed.FS
avatarParts embed.FS
avatarRegexp = regexp.MustCompile(`^([a-z]+)_([0-9]+)\.png$`)
)
// UserInfoHandlerFunc returns the information about the currently logged user. // UserInfoHandlerFunc returns the information about the currently logged user.
func (c *Component) UserInfoHandlerFunc(gc *gin.Context) { func (c *Component) UserInfoHandlerFunc(gc *gin.Context) {

View File

@@ -120,11 +120,6 @@ func templateEscape(input string) string {
return strings.ReplaceAll(input, `{{`, `{{"{{"}}`) return strings.ReplaceAll(input, `{{`, `{{"{{"}}`)
} }
// templateDate turns a date into an UTC string compatible with ClickHouse.
func templateDate(input time.Time) string {
return input.UTC().Format("2006-01-02 15:04:05")
}
// templateWhere transforms a filter to a WHERE clause // templateWhere transforms a filter to a WHERE clause
func templateWhere(qf queryFilter) string { func templateWhere(qf queryFilter) string {
if qf.Filter == "" { if qf.Filter == "" {

View File

@@ -168,7 +168,7 @@ func (r *imageEmbedder) Transform(node *ast.Document, reader text.Reader, pc par
switch node := n.(type) { switch node := n.(type) {
case *ast.Image: case *ast.Image:
path := string(node.Destination) path := string(node.Destination)
if strings.Index(path, "/") != -1 || !strings.HasSuffix(path, ".svg") { if strings.Contains(path, "/") || !strings.HasSuffix(path, ".svg") {
break break
} }
f, err := r.root.Open(path) f, err := r.root.Open(path)

View File

@@ -273,7 +273,6 @@ LIMIT 20`, column, column, column, column, column)
} }
} }
gc.JSON(http.StatusOK, filterCompleteHandlerOutput{filteredCompletions}) gc.JSON(http.StatusOK, filterCompleteHandlerOutput{filteredCompletions})
return
} }
func (c *Component) filterSavedListHandlerFunc(gc *gin.Context) { func (c *Component) filterSavedListHandlerFunc(gc *gin.Context) {

View File

@@ -277,11 +277,11 @@ func (c *Component) graphHandlerFunc(gc *gin.Context) {
lastTimeForAxis[axis] = result.Time lastTimeForAxis[axis] = result.Time
} }
rowKey := fmt.Sprintf("%d-%s", axis, result.Dimensions) rowKey := fmt.Sprintf("%d-%s", axis, result.Dimensions)
row, ok := points[axis][rowKey] _, ok = points[axis][rowKey]
if !ok { if !ok {
// Not points for this row yet, create it // Not points for this row yet, create it
rows[axis][rowKey] = result.Dimensions rows[axis][rowKey] = result.Dimensions
row = make([]int, len(output.Time)) row := make([]int, len(output.Time))
points[axis][rowKey] = row points[axis][rowKey] = row
sums[axis][rowKey] = 0 sums[axis][rowKey] = 0
} }

View File

@@ -79,6 +79,9 @@ func (qf *queryFilter) UnmarshalText(input []byte) error {
} }
meta = &filter.Meta{ReverseDirection: true} meta = &filter.Meta{ReverseDirection: true}
reverse, err := filter.Parse("", input, filter.GlobalStore("meta", meta)) reverse, err := filter.Parse("", input, filter.GlobalStore("meta", meta))
if err != nil {
return fmt.Errorf("cannot parse reverse filter: %s", filter.HumanError(err))
}
*qf = queryFilter{ *qf = queryFilter{
Filter: direct.(string), Filter: direct.(string),
ReverseFilter: reverse.(string), ReverseFilter: reverse.(string),

View File

@@ -12,7 +12,6 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"sync" "sync"
"text/template"
"time" "time"
"github.com/benbjohnson/clock" "github.com/benbjohnson/clock"
@@ -33,9 +32,6 @@ type Component struct {
t tomb.Tomb t tomb.Tomb
config Configuration config Configuration
templates map[string]*template.Template
templatesLock sync.RWMutex
flowsTables []flowsTable flowsTables []flowsTable
flowsTablesLock sync.RWMutex flowsTablesLock sync.RWMutex

View File

@@ -69,10 +69,8 @@ func (c *Component) startSNMPServer() error {
return fmt.Errorf("unable to bind SNMP server: %w", err) return fmt.Errorf("unable to bind SNMP server: %w", err)
} }
c.t.Go(func() error { c.t.Go(func() error {
select { <-c.t.Dying()
case <-c.t.Dying(): server.Shutdown()
server.Shutdown()
}
return nil return nil
}) })

View File

@@ -218,7 +218,7 @@ func (nd *Decoder) Decode(in decoder.RawFlow) []*decoder.FlowMessage {
} }
} }
flowMessageSet, err := producer.ProcessMessageNetFlow(msgDec, sampling) flowMessageSet, _ := producer.ProcessMessageNetFlow(msgDec, sampling)
for _, fmsg := range flowMessageSet { for _, fmsg := range flowMessageSet {
fmsg.TimeReceived = ts fmsg.TimeReceived = ts
fmsg.SamplerAddress = in.Source fmsg.SamplerAddress = in.Source

View File

@@ -117,7 +117,7 @@ func (nd *Decoder) Decode(in decoder.RawFlow) []*decoder.FlowMessage {
} }
} }
flowMessageSet, err := producer.ProcessMessageSFlow(msgDec) flowMessageSet, _ := producer.ProcessMessageSFlow(msgDec)
for _, fmsg := range flowMessageSet { for _, fmsg := range flowMessageSet {
fmsg.TimeReceived = ts fmsg.TimeReceived = ts
fmsg.TimeFlowStart = ts fmsg.TimeFlowStart = ts

View File

@@ -195,9 +195,9 @@ func (sc *snmpCache) entriesOlderThan(older time.Duration, lastAccessed bool) ma
what = &iface.LastUpdated what = &iface.LastUpdated
} }
if atomic.LoadInt64(what) < threshold { if atomic.LoadInt64(what) < threshold {
rifaces, ok := result[ip] _, ok := result[ip]
if !ok { if !ok {
rifaces = make(map[uint]Interface) rifaces := make(map[uint]Interface)
result[ip] = rifaces result[ip] = rifaces
} }
result[ip][ifindex] = iface.Interface result[ip][ifindex] = iface.Interface

View File

@@ -74,7 +74,7 @@ func (c *Component) registerHTTPHandlers() error {
f, err := data.Open("data/asns.csv") f, err := data.Open("data/asns.csv")
if err != nil { if err != nil {
c.r.Err(err).Msg("unable to open data/asns.csv") c.r.Err(err).Msg("unable to open data/asns.csv")
http.Error(w, fmt.Sprintf("Unable to open ASN file."), http.Error(w, "Unable to open ASN file.",
http.StatusInternalServerError) http.StatusInternalServerError)
return return
} }