Skip to content

Commit

Permalink
chore: fix some small issues detected by golangci-lint
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
vincentbernat committed Aug 10, 2022
1 parent 17eb552 commit 78fb01c
Show file tree
Hide file tree
Showing 17 changed files with 36 additions and 78 deletions.
6 changes: 2 additions & 4 deletions cmd/components.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
22 changes: 10 additions & 12 deletions common/daemon/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 0 additions & 1 deletion common/daemon/tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,4 @@ func (c *MockComponent) Stop() error {

// Track does nothing
func (c *MockComponent) Track(t *tomb.Tomb, who string) {
return
}
36 changes: 7 additions & 29 deletions common/http/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
}
Expand Down
6 changes: 2 additions & 4 deletions common/reporter/healthcheck_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
8 changes: 2 additions & 6 deletions console/authentication/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
5 changes: 0 additions & 5 deletions console/clickhouse.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 == "" {
Expand Down
2 changes: 1 addition & 1 deletion console/docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion console/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions console/graph.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
3 changes: 3 additions & 0 deletions console/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
4 changes: 0 additions & 4 deletions console/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"path/filepath"
"runtime"
"sync"
"text/template"
"time"

"github.com/benbjohnson/clock"
Expand All @@ -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

Expand Down
6 changes: 2 additions & 4 deletions demoexporter/snmp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
})

Expand Down
2 changes: 1 addition & 1 deletion inlet/flow/decoder/netflow/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion inlet/flow/decoder/sflow/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions inlet/snmp/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion orchestrator/clickhouse/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit 78fb01c

Please sign in to comment.