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).
Msg("akvorado has started")
select {
case <-daemonComponent.Terminated():
r.Info().Msg("stopping all components")
}
<-daemonComponent.Terminated()
r.Info().Msg("stopping all components")
return nil
}

View File

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

View File

@@ -40,5 +40,4 @@ func (c *MockComponent) Stop() error {
// Track does nothing
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
}
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
func (c *Component) AddHandler(location string, handler http.Handler) {
l := c.r.With().Str("handler", location).Logger()
@@ -175,16 +155,14 @@ func (c *Component) Start() error {
// Gracefully stop when asked to
c.t.Go(func() error {
select {
case <-c.t.Dying():
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
c.r.Err(err).Msg("unable to shutdown HTTP server")
return fmt.Errorf("unable to shutdown HTTP server: %w", err)
}
return nil
<-c.t.Dying()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
c.r.Err(err).Msg("unable to shutdown HTTP server")
return fmt.Errorf("unable to shutdown HTTP server: %w", err)
}
return nil
})
return nil
}

View File

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

View File

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

View File

@@ -120,11 +120,6 @@ func templateEscape(input string) string {
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
func templateWhere(qf queryFilter) string {
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) {
case *ast.Image:
path := string(node.Destination)
if strings.Index(path, "/") != -1 || !strings.HasSuffix(path, ".svg") {
if strings.Contains(path, "/") || !strings.HasSuffix(path, ".svg") {
break
}
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})
return
}
func (c *Component) filterSavedListHandlerFunc(gc *gin.Context) {

View File

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

View File

@@ -79,6 +79,9 @@ func (qf *queryFilter) UnmarshalText(input []byte) error {
}
meta = &filter.Meta{ReverseDirection: true}
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{
Filter: direct.(string),
ReverseFilter: reverse.(string),

View File

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

View File

@@ -69,10 +69,8 @@ func (c *Component) startSNMPServer() error {
return fmt.Errorf("unable to bind SNMP server: %w", err)
}
c.t.Go(func() error {
select {
case <-c.t.Dying():
server.Shutdown()
}
<-c.t.Dying()
server.Shutdown()
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 {
fmsg.TimeReceived = ts
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 {
fmsg.TimeReceived = ts
fmsg.TimeFlowStart = ts

View File

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

View File

@@ -74,7 +74,7 @@ func (c *Component) registerHTTPHandlers() error {
f, err := data.Open("data/asns.csv")
if err != nil {
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)
return
}