Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
Signed-off-by: Pavel Okhlopkov <pavel.okhlopkov@flant.com>
  • Loading branch information
Pavel Okhlopkov committed Nov 2, 2024
1 parent 67b0557 commit 9daad9f
Show file tree
Hide file tree
Showing 22 changed files with 49 additions and 54 deletions.
11 changes: 3 additions & 8 deletions cmd/shell-operator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ package main

import (
"fmt"
"math/rand"
"os"
"time"

"github.com/deckhouse/deckhouse/pkg/log"
"gopkg.in/alecthomas/kingpin.v2"
Expand All @@ -27,13 +25,13 @@ func main() {
kpApp.UsageTemplate(app.OperatorUsageTemplate(app.AppName))

// Initialize klog wrapper when all values are parsed
kpApp.Action(func(c *kingpin.ParseContext) error {
kpApp.Action(func(_ *kingpin.ParseContext) error {
klogtolog.InitAdapter(app.DebugKubernetesAPI, logger.Named("klog"))
return nil
})

// print version
kpApp.Command("version", "Show version.").Action(func(c *kingpin.ParseContext) error {
kpApp.Command("version", "Show version.").Action(func(_ *kingpin.ParseContext) error {
fmt.Printf("%s %s\n", app.AppName, app.Version)
fmt.Println(jq.FilterInfo())
return nil
Expand All @@ -42,12 +40,9 @@ func main() {
// start main loop
startCmd := kpApp.Command("start", "Start shell-operator.").
Default().
Action(func(c *kingpin.ParseContext) error {
Action(func(_ *kingpin.ParseContext) error {
app.AppStartMessage = fmt.Sprintf("%s %s", app.AppName, app.Version)

// Init rand generator.
rand.Seed(time.Now().UnixNano())

// Init logging and initialize a ShellOperator instance.
operator, err := shell_operator.Init(logger.Named("shell-operator"))
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion pkg/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ Use "%s debug-options" for a list of debug options for start command.

// CommandWithDefaultUsageTemplate is used to workaround an absence of per-command usage templates
func CommandWithDefaultUsageTemplate(kpApp *kingpin.Application, name, help string) *kingpin.CmdClause {
return kpApp.Command(name, help).PreAction(func(context *kingpin.ParseContext) error {
return kpApp.Command(name, help).PreAction(func(_ *kingpin.ParseContext) error {
kpApp.UsageTemplate(kingpin.DefaultUsageTemplate)
return nil
})
Expand Down
6 changes: 3 additions & 3 deletions pkg/app/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ func SetupLogging(runtimeConfig *config.Config, logger *log.Logger) {
runtimeConfig.Register("log.level",
fmt.Sprintf("Global log level. Default duration for debug level is %s", ForcedDurationForDebugLevel),
strings.ToLower(LogLevel),
func(oldValue string, newValue string) error {
log.Infof("Set log level to '%s'", newValue)
func(_ string, newValue string) error {
logger.Infof("Set log level to '%s'", newValue)
log.SetDefaultLevel(log.LogLevelFromStr(newValue))
return nil
}, func(oldValue string, newValue string) time.Duration {
}, func(_ string, newValue string) time.Duration {
if strings.ToLower(newValue) == "debug" {
return ForcedDurationForDebugLevel
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func TestConfig_OnChange(t *testing.T) {
c := NewConfig(log.NewNop())

newValue := ""
c.Register("log.level", "", "info", func(oldValue string, n string) error {
c.Register("log.level", "", "info", func(_ string, n string) error {
newValue = n
return nil
}, nil)
Expand Down Expand Up @@ -69,7 +69,7 @@ func TestConfig_Errors(t *testing.T) {
var err error
c := NewConfig(log.NewNop())

c.Register("log.level", "", "info", func(oldValue string, n string) error {
c.Register("log.level", "", "info", func(_ string, n string) error {
if n == "debug" {
return nil
}
Expand Down
14 changes: 7 additions & 7 deletions pkg/debug/debug-cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func DefineDebugCommands(kpApp *kingpin.Application) {
queueCmd := app.CommandWithDefaultUsageTemplate(kpApp, "queue", "Dump queues.")

queueListCmd := queueCmd.Command("list", "Dump tasks in all queues.").
Action(func(c *kingpin.ParseContext) error {
Action(func(_ *kingpin.ParseContext) error {
out, err := Queue(DefaultClient()).List(outputFormat, showEmpty)
if err != nil {
return err
Expand All @@ -34,7 +34,7 @@ func DefineDebugCommands(kpApp *kingpin.Application) {
app.DefineDebugUnixSocketFlag(queueListCmd)

queueMainCmd := queueCmd.Command("main", "Dump tasks in the main queue.").
Action(func(c *kingpin.ParseContext) error {
Action(func(_ *kingpin.ParseContext) error {
out, err := Queue(DefaultClient()).Main(outputFormat)
if err != nil {
return err
Expand All @@ -49,7 +49,7 @@ func DefineDebugCommands(kpApp *kingpin.Application) {
configCmd := app.CommandWithDefaultUsageTemplate(kpApp, "config", "Manage runtime parameters.")

configListCmd := configCmd.Command("list", "List available runtime parameters.").
Action(func(c *kingpin.ParseContext) error {
Action(func(_ *kingpin.ParseContext) error {
out, err := Config(DefaultClient()).List(outputFormat)
if err != nil {
return err
Expand All @@ -64,7 +64,7 @@ func DefineDebugCommands(kpApp *kingpin.Application) {
var paramValue string
var paramDuration time.Duration
configSetCmd := configCmd.Command("set", "Set runtime parameter.").
Action(func(c *kingpin.ParseContext) error {
Action(func(_ *kingpin.ParseContext) error {
out, err := Config(DefaultClient()).Set(paramName, paramValue, paramDuration)
if err != nil {
return err
Expand All @@ -80,7 +80,7 @@ func DefineDebugCommands(kpApp *kingpin.Application) {
// Raw request command
var rawUrl string
rawCommand := app.CommandWithDefaultUsageTemplate(kpApp, "raw", "Make a raw request to debug endpoint.").
Action(func(c *kingpin.ParseContext) error {
Action(func(_ *kingpin.ParseContext) error {
url := fmt.Sprintf("http://unix%s", rawUrl)
resp, err := DefaultClient().Get(url)
if err != nil {
Expand All @@ -97,7 +97,7 @@ func DefineDebugCommandsSelf(kpApp *kingpin.Application) {
// Get hook names
hookCmd := app.CommandWithDefaultUsageTemplate(kpApp, "hook", "Actions for hooks")
hookListCmd := hookCmd.Command("list", "List all hooks.").
Action(func(c *kingpin.ParseContext) error {
Action(func(_ *kingpin.ParseContext) error {
outBytes, err := Hook(DefaultClient()).List(outputFormat)
if err != nil {
return err
Expand All @@ -111,7 +111,7 @@ func DefineDebugCommandsSelf(kpApp *kingpin.Application) {
// Get hook snapshots
var hookName string
hookSnapshotCmd := hookCmd.Command("snapshot", "Dump hook snapshots.").
Action(func(c *kingpin.ParseContext) error {
Action(func(_ *kingpin.ParseContext) error {
outBytes, err := Hook(DefaultClient()).Name(hookName).Snapshots(outputFormat)
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion pkg/executor/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func (pl *proxyLogger) Write(p []byte) (int, error) {
logLine := string(logLineRaw)

if len(logLine) > 10000 {
logLine = fmt.Sprintf("%s:truncated", string(logLine[:10000]))
logLine = fmt.Sprintf("%s:truncated", logLine[:10000])

logger.Log(context.Background(), log.LevelFatal.Level(), "hook result", slog.Any("hook", map[string]any{
"truncated": logLine,
Expand Down
4 changes: 2 additions & 2 deletions pkg/executor/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package executor
import (
"bytes"
"io"
"math/rand"
"math/rand/v2"
"os"
"os/exec"
"regexp"
Expand Down Expand Up @@ -159,7 +159,7 @@ var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randStringRunes(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
b[i] = letterRunes[rand.IntN(len(letterRunes))]
}
return string(b)
}
6 changes: 3 additions & 3 deletions pkg/hook/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,7 @@ settings:
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Run(test.name, func(_ *testing.T) {
hookConfig = &HookConfig{}
err = hookConfig.LoadAndValidate([]byte(test.jsonConfig))
test.testFn()
Expand Down Expand Up @@ -1045,7 +1045,7 @@ func Test_HookConfig_V1_Kubernetes_Validate(t *testing.T) {
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Run(test.name, func(_ *testing.T) {
hookConfig = &HookConfig{}
err = hookConfig.LoadAndValidate([]byte(test.jsonText))
test.testFn()
Expand Down Expand Up @@ -1083,7 +1083,7 @@ func Test_MergeArrays(t *testing.T) {
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Run(test.name, func(_ *testing.T) {
res := MergeArrays(test.a1, test.a2)
g.Expect(res).To(Equal(test.expect))
})
Expand Down
2 changes: 1 addition & 1 deletion pkg/hook/config/validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func Test_Validate_V1_With_Error(t *testing.T) {
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Run(tt.name, func(_ *testing.T) {
vu = prepareConfigObj(g, tt.configText)
s := GetSchema(vu.Version)
err = ValidateConfig(vu.Obj, s, "root")
Expand Down
2 changes: 1 addition & 1 deletion pkg/hook/config/versioned_untyped_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ schedule:
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Run(tt.name, func(_ *testing.T) {
vu = NewDefaultVersionedUntyped()
err = vu.Load([]byte(tt.input))

Expand Down
2 changes: 1 addition & 1 deletion pkg/hook/controller/conversion_bindings_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (c *ConversionBindingsController) DisableConversionBindings() {
// TODO dynamic enable/disable conversion webhooks.
}

func (c *ConversionBindingsController) CanHandleEvent(crdName string, request *v1.ConversionRequest, rule conversion.Rule) bool {
func (c *ConversionBindingsController) CanHandleEvent(crdName string, _ *v1.ConversionRequest, rule conversion.Rule) bool {
_, has := c.Links[crdName]
if !has {
return false
Expand Down
1 change: 1 addition & 0 deletions pkg/hook/controller/hook_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ func (hc *HookController) InitKubernetesBindings(bindings []OnKubernetesEventCon
bindingCtrl.WithKubernetesBindings(bindings)
hc.KubernetesController = bindingCtrl
hc.kubernetesBindings = bindings
hc.logger = logger
}

func (hc *HookController) InitScheduleBindings(bindings []ScheduleConfig, scheduleMgr schedule_manager.ScheduleManager) {
Expand Down
4 changes: 2 additions & 2 deletions pkg/hook/hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func Test_CreateLimiter(t *testing.T) {
}

for _, c := range cases {
t.Run(c.title, func(t *testing.T) {
t.Run(c.title, func(_ *testing.T) {
cfg := &config.HookConfig{
Settings: c.settings,
}
Expand Down Expand Up @@ -135,7 +135,7 @@ func Test_Hook_WithConfig(t *testing.T) {
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Run(test.name, func(_ *testing.T) {
hook = NewHook("hook-sh", "/hooks/hook.sh", log.NewNop())
_, err = hook.LoadConfig([]byte(test.jsonData))
test.fn()
Expand Down
6 changes: 3 additions & 3 deletions pkg/kube_events_manager/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package kube_events_manager

import (
"fmt"
"math/rand"
"math/rand/v2"
"time"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
Expand Down Expand Up @@ -59,9 +59,9 @@ const (
// randomizedResyncPeriod returns a time.Duration between 2 hours and 4 hours with jitter and granularity
func randomizedResyncPeriod() time.Duration {
spreadCount := ResyncPeriodSpread.Nanoseconds() / ResyncPeriodGranularity.Nanoseconds()
rndSpreadDelta := time.Duration(rand.Int63n(spreadCount)) * ResyncPeriodGranularity
rndSpreadDelta := time.Duration(rand.Int64N(spreadCount)) * ResyncPeriodGranularity
jitterCount := ResyncPeriodGranularity.Nanoseconds() / ResyncPeriodJitterGranularity.Nanoseconds()
rndJitterDelta := time.Duration(rand.Int63n(jitterCount)) * ResyncPeriodJitterGranularity
rndJitterDelta := time.Duration(rand.Int64N(jitterCount)) * ResyncPeriodJitterGranularity

return ResyncPeriodMedian - (ResyncPeriodSpread / 2) + rndSpreadDelta + rndJitterDelta
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/schedule_manager/schedule_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func Test_ScheduleManager_Add(t *testing.T) {
}

for _, expectation := range expectations {
t.Run(expectation.testName, func(t *testing.T) {
t.Run(expectation.testName, func(_ *testing.T) {
sm.Add(types.ScheduleEntry{Crontab: expectation.crontab, Id: expectation.id})

// if expectation.err != "" {
Expand Down
8 changes: 4 additions & 4 deletions pkg/shell-operator/combine_binding_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func Test_CombineBindingContext_MultipleHooks(t *testing.T) {

TaskQueues := queue.NewTaskQueueSet()
TaskQueues.WithContext(context.Background())
TaskQueues.NewNamedQueue("test_multiple_hooks", func(tsk task.Task) queue.TaskResult {
TaskQueues.NewNamedQueue("test_multiple_hooks", func(_ task.Task) queue.TaskResult {
return queue.TaskResult{
Status: "Success",
}
Expand Down Expand Up @@ -114,7 +114,7 @@ func Test_CombineBindingContext_Nil_On_NoCombine(t *testing.T) {

TaskQueues := queue.NewTaskQueueSet()
TaskQueues.WithContext(context.Background())
TaskQueues.NewNamedQueue("test_no_combine", func(tsk task.Task) queue.TaskResult {
TaskQueues.NewNamedQueue("test_no_combine", func(_ task.Task) queue.TaskResult {
return queue.TaskResult{
Status: "Success",
}
Expand Down Expand Up @@ -173,7 +173,7 @@ func Test_CombineBindingContext_Group_Compaction(t *testing.T) {

TaskQueues := queue.NewTaskQueueSet()
TaskQueues.WithContext(context.Background())
TaskQueues.NewNamedQueue("test_multiple_hooks", func(tsk task.Task) queue.TaskResult {
TaskQueues.NewNamedQueue("test_multiple_hooks", func(_ task.Task) queue.TaskResult {
return queue.TaskResult{
Status: "Success",
}
Expand Down Expand Up @@ -275,7 +275,7 @@ func Test_CombineBindingContext_Group_Type(t *testing.T) {

TaskQueues := queue.NewTaskQueueSet()
TaskQueues.WithContext(context.Background())
TaskQueues.NewNamedQueue("test_multiple_hooks", func(tsk task.Task) queue.TaskResult {
TaskQueues.NewNamedQueue("test_multiple_hooks", func(_ task.Task) queue.TaskResult {
return queue.TaskResult{
Status: "Success",
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/shell-operator/http_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ func newBaseHTTPServer(address, port string) *baseHTTPServer {
// inject pprof
router.Mount("/debug", middleware.Profiler())

router.Get("/discovery", func(writer http.ResponseWriter, request *http.Request) {
router.Get("/discovery", func(writer http.ResponseWriter, _ *http.Request) {
buf := bytes.NewBuffer(nil)
walkFn := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
walkFn := func(method string, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
// skip pprof routes
if strings.HasPrefix(route, "/debug/") {
return nil
Expand Down Expand Up @@ -110,7 +110,7 @@ func newBaseHTTPServer(address, port string) *baseHTTPServer {
}

func registerRootRoute(op *ShellOperator) {
op.APIServer.RegisterRoute(http.MethodGet, "/", func(writer http.ResponseWriter, request *http.Request) {
op.APIServer.RegisterRoute(http.MethodGet, "/", func(writer http.ResponseWriter, _ *http.Request) {
_, _ = fmt.Fprintf(writer, `<html>
<head><title>Shell operator</title></head>
<body>
Expand Down
8 changes: 4 additions & 4 deletions pkg/task/dump/dump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func Test_Dump(t *testing.T) {
tqs.WithContext(context.Background())

// Empty set, no queues, dump should not fail.
t.Run("empty set", func(t *testing.T) {
t.Run("empty set", func(_ *testing.T) {
dump := testDumpQueuesWrapper(tqs, "text", true)
g.Expect(dump).To(ContainSubstring("No queues"))
})
Expand All @@ -94,7 +94,7 @@ func Test_Dump(t *testing.T) {
g.Expect(dump).To(MatchJSON(`{"active":[],"summary":{"mainQueueTasks":0,"otherQueues":{"active":0,"empty":0,"tasks":0},"totalTasks":0}}`))
})

t.Run("main queue as active", func(t *testing.T) {
t.Run("main queue as active", func(_ *testing.T) {
fillQueue(tqs.GetMain(), mainTasks)

// Main queue is not counted as active or empty queue.
Expand All @@ -104,7 +104,7 @@ func Test_Dump(t *testing.T) {
})

// Create and fill active queue.
t.Run("fill active queue", func(t *testing.T) {
t.Run("fill active queue", func(_ *testing.T) {
tqs.NewNamedQueue("active-queue", nil)
fillQueue(tqs.GetByName("active-queue"), activeTasks)

Expand All @@ -128,7 +128,7 @@ func Test_Dump(t *testing.T) {
g.Expect(dump).To(MatchJSON(`{"active":[{"name":"main","tasksCount":5,"tasks":[{"index":1,"description":":::test_task_main_0004"},{"index":2,"description":":::test_task_main_0003"},{"index":3,"description":":::test_task_main_0002"},{"index":4,"description":":::test_task_main_0001"},{"index":5,"description":":::test_task_main_0000"}]},{"name":"active-queue","tasksCount":4,"tasks":[{"index":1,"description":":::test_task_active-queue_0003"},{"index":2,"description":":::test_task_active-queue_0002"},{"index":3,"description":":::test_task_active-queue_0001"},{"index":4,"description":":::test_task_active-queue_0000"}]}],"empty":[{"name":"empty","tasksCount":0}],"summary":{"mainQueueTasks":5,"otherQueues":{"active":1,"empty":1,"tasks":4},"totalTasks":9}}`))
})

t.Run("omit empty queue", func(t *testing.T) {
t.Run("omit empty queue", func(_ *testing.T) {
dump := testDumpQueuesWrapper(tqs, "text", false)
g.Expect(dump).To(ContainSubstring("1 active"))
g.Expect(dump).ToNot(ContainSubstring("Empty queues (1):"))
Expand Down
4 changes: 2 additions & 2 deletions pkg/task/queue/task_queue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func Test_ExponentialBackoff(t *testing.T) {
// Set exponential backoff to the constant delay just to wait more than DelayOnQueueIsEmpty.
// It is a test of delaying between task runs, not a test of exponential distribution.
mockExponentialDelay := 30 * time.Millisecond
q.ExponentialBackoffFn = func(failureCount int) time.Duration {
q.ExponentialBackoffFn = func(_ int) time.Duration {
return mockExponentialDelay
}

Expand Down Expand Up @@ -201,7 +201,7 @@ func Test_CancelDelay(t *testing.T) {
// Set exponential backoff to the constant delay just to wait more than DelayOnQueueIsEmpty.
// It is a test of delaying between task runs, not a test of exponential distribution.
mockExponentialDelay := 150 * time.Millisecond
q.ExponentialBackoffFn = func(failureCount int) time.Duration {
q.ExponentialBackoffFn = func(_ int) time.Duration {
return mockExponentialDelay
}

Expand Down
Loading

0 comments on commit 9daad9f

Please sign in to comment.