Skip to content

Commit

Permalink
Add gosimple linter (#9590)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kris Hicks authored Dec 9, 2020
1 parent 8333ab9 commit 85ed8dd
Show file tree
Hide file tree
Showing 77 changed files with 111 additions and 186 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ linters:
- structcheck
- unconvert
- gofmt
- gosimple
# Stretch Goal
#- maligned
fast: false
Expand Down
5 changes: 1 addition & 4 deletions client/agent_endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,7 @@ func (a *Agent) monitor(conn io.ReadWriteCloser) {
cancel()
return
}
select {
case <-ctx.Done():
return
}
<-ctx.Done()
}()

logCh := monitor.Start()
Expand Down
3 changes: 1 addition & 2 deletions client/allocdir/fs_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ func createSecretDir(dir string) error {
return nil
}

var flags uintptr
flags = syscall.MS_NOEXEC
flags := uintptr(syscall.MS_NOEXEC)
options := fmt.Sprintf("size=%dm", secretDirTmpfsSize)
if err := syscall.Mount("tmpfs", dir, "tmpfs", flags, options); err != nil {
return os.NewSyscallError("mount", err)
Expand Down
2 changes: 1 addition & 1 deletion client/allocrunner/health_hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ func (h *allocHealthWatcherHook) watchHealth(ctx context.Context, deadline time.
// Allocation has stopped so no need to set health
return

case <-time.After(deadline.Sub(time.Now())):
case <-time.After(time.Until(deadline)):
// Time is up! Fallthrough to set unhealthy.
h.logger.Trace("deadline reached; setting unhealthy", "deadline", deadline)

Expand Down
2 changes: 1 addition & 1 deletion client/allocrunner/taskrunner/plugin_supervisor_hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func (h *csiPluginSupervisorHook) Poststart(_ context.Context, _ *interfaces.Tas
// Deeper fingerprinting of the plugin is implemented by the csimanager.
func (h *csiPluginSupervisorHook) ensureSupervisorLoop(ctx context.Context) {
h.runningLock.Lock()
if h.running == true {
if h.running {
h.runningLock.Unlock()
return
}
Expand Down
2 changes: 1 addition & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -1613,7 +1613,7 @@ func (c *Client) getHeartbeatRetryIntv(err error) time.Duration {
}

// Determine how much time we have left to heartbeat
left := last.Add(ttl).Sub(time.Now())
left := time.Until(last.Add(ttl))

// Logic for retrying is:
// * Do not retry faster than once a second
Expand Down
2 changes: 0 additions & 2 deletions client/devicemanager/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,8 +406,6 @@ func (i *instanceManager) handleFingerprintError() {

// Cancel the context so we cleanup all goroutines
i.cancel()

return
}

// handleFingerprint stores the new devices and triggers the fingerprint output
Expand Down
4 changes: 1 addition & 3 deletions client/dynamicplugins/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -373,9 +373,7 @@ func (p *pluginEventBroadcaster) run() {
case msg := <-p.publishCh:
p.subscriptionsLock.RLock()
for msgCh := range p.subscriptions {
select {
case msgCh <- msg:
}
msgCh <- msg
}
p.subscriptionsLock.RUnlock()
}
Expand Down
4 changes: 1 addition & 3 deletions client/enterprise_client_oss.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,4 @@ func newEnterpriseClient(logger hclog.Logger) *EnterpriseClient {
}

// SetFeatures is used for enterprise builds to configure enterprise features
func (ec *EnterpriseClient) SetFeatures(features uint64) {
return
}
func (ec *EnterpriseClient) SetFeatures(features uint64) {}
8 changes: 4 additions & 4 deletions client/fingerprint/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type FingerprintResponse struct {
func (f *FingerprintResponse) AddAttribute(name, value string) {
// initialize Attributes if it has not been already
if f.Attributes == nil {
f.Attributes = make(map[string]string, 0)
f.Attributes = make(map[string]string)
}

f.Attributes[name] = value
Expand All @@ -41,7 +41,7 @@ func (f *FingerprintResponse) AddAttribute(name, value string) {
func (f *FingerprintResponse) RemoveAttribute(name string) {
// initialize Attributes if it has not been already
if f.Attributes == nil {
f.Attributes = make(map[string]string, 0)
f.Attributes = make(map[string]string)
}

f.Attributes[name] = ""
Expand All @@ -51,7 +51,7 @@ func (f *FingerprintResponse) RemoveAttribute(name string) {
func (f *FingerprintResponse) AddLink(name, value string) {
// initialize Links if it has not been already
if f.Links == nil {
f.Links = make(map[string]string, 0)
f.Links = make(map[string]string)
}

f.Links[name] = value
Expand All @@ -62,7 +62,7 @@ func (f *FingerprintResponse) AddLink(name, value string) {
func (f *FingerprintResponse) RemoveLink(name string) {
// initialize Links if it has not been already
if f.Links == nil {
f.Links = make(map[string]string, 0)
f.Links = make(map[string]string)
}

f.Links[name] = ""
Expand Down
2 changes: 1 addition & 1 deletion client/logmon/logging/rotator.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ func (f *FileRotator) purgeOldFiles() {

// Sorting the file indexes so that we can purge the older files and keep
// only the number of files as configured by the user
sort.Sort(sort.IntSlice(fIndexes))
sort.Ints(fIndexes)
toDelete := fIndexes[0 : len(fIndexes)-f.MaxFiles]
for _, fIndex := range toDelete {
fname := filepath.Join(f.path, fmt.Sprintf("%s.%d", f.baseFileName, fIndex))
Expand Down
1 change: 0 additions & 1 deletion client/logmon/logmon.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,6 @@ func (l *logRotatorWrapper) start(openFn func() (io.ReadCloser, error)) {
reader.Close()
}
}()
return
}

// Close closes the rotator and the process writer to ensure that the Wait
Expand Down
12 changes: 5 additions & 7 deletions client/pluginmanager/group.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,12 @@ func (m *PluginGroup) WaitForFirstFingerprint(ctx context.Context) (<-chan struc
go func() {
defer wg.Done()
logger.Debug("waiting on plugin manager initial fingerprint")
<-manager.WaitForFirstFingerprint(ctx)
select {
case <-manager.WaitForFirstFingerprint(ctx):
select {
case <-ctx.Done():
logger.Warn("timeout waiting for plugin manager to be ready")
default:
logger.Debug("finished plugin manager initial fingerprint")
}
case <-ctx.Done():
logger.Warn("timeout waiting for plugin manager to be ready")
default:
logger.Debug("finished plugin manager initial fingerprint")
}
}()
}
Expand Down
2 changes: 1 addition & 1 deletion client/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ TRY:
case <-time.After(lib.RandomStagger(c.config.RPCHoldTimeout / structs.JitterFraction)):
// If we are going to retry a blocking query we need to update the time to block so it finishes by our deadline.
if info, ok := args.(structs.RPCInfo); ok && info.TimeToBlock() > 0 {
newBlockTime := deadline.Sub(time.Now())
newBlockTime := time.Until(deadline)
// We can get below 0 here on slow computers because we slept for jitter so at least try to get an immediate response
if newBlockTime < 0 {
newBlockTime = 0
Expand Down
5 changes: 1 addition & 4 deletions client/state/08types.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,7 @@ func (t *taskRunnerState08) Upgrade(allocID, taskName string) (*state.LocalState

// The docker driver prefixed the handle with 'DOCKER:'
// Strip so that it can be unmarshalled
data := t.HandleID
if strings.HasPrefix(data, "DOCKER:") {
data = data[7:]
}
data := strings.TrimPrefix(t.HandleID, "DOCKER:")

// The pre09 driver handle ID is given to the driver. It is unmarshalled
// here to check for errors
Expand Down
2 changes: 1 addition & 1 deletion client/structs/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ type HealthCheckIntervalResponse struct {
func (h *HealthCheckResponse) AddDriverInfo(name string, driverInfo *structs.DriverInfo) {
// initialize Drivers if it has not been already
if h.Drivers == nil {
h.Drivers = make(map[string]*structs.DriverInfo, 0)
h.Drivers = make(map[string]*structs.DriverInfo)
}

h.Drivers[name] = driverInfo
Expand Down
2 changes: 1 addition & 1 deletion client/vaultclient/vaultclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ func (c *vaultClient) run() {
// Compute the duration after which the item
// needs renewal and set the renewalCh to fire
// at that time.
renewalDuration := renewalTime.Sub(time.Now())
renewalDuration := time.Until(renewalTime)
renewalCh = time.After(renewalDuration)
} else {
// If the renewals of multiple items are too
Expand Down
2 changes: 1 addition & 1 deletion command/acl_policy_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func formatPolicies(policies []*api.ACLPolicyListStub) string {
}

output := make([]string, 0, len(policies)+1)
output = append(output, fmt.Sprintf("Name|Description"))
output = append(output, "Name|Description")
for _, p := range policies {
output = append(output, fmt.Sprintf("%s|%s", p.Name, p.Description))
}
Expand Down
2 changes: 1 addition & 1 deletion command/acl_token_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func formatTokens(tokens []*api.ACLTokenListStub) string {
}

output := make([]string, 0, len(tokens)+1)
output = append(output, fmt.Sprintf("Name|Type|Global|Accessor ID"))
output = append(output, "Name|Type|Global|Accessor ID")
for _, p := range tokens {
output = append(output, fmt.Sprintf("%s|%s|%t|%s", p.Name, p.Type, p.Global, p.AccessorID))
}
Expand Down
2 changes: 1 addition & 1 deletion command/agent/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,7 @@ func (c *Command) handleReload() {
c.Ui.Output("Reloading configuration...")
newConf := c.readConfig()
if newConf == nil {
c.Ui.Error(fmt.Sprintf("Failed to reload configs"))
c.Ui.Error("Failed to reload configs")
return
}

Expand Down
7 changes: 3 additions & 4 deletions command/agent/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,6 @@ func (s *HTTPServer) handleUI(h http.Handler) http.Handler {
header := w.Header()
header.Add("Content-Security-Policy", "default-src 'none'; connect-src *; img-src 'self' data:; script-src 'self'; style-src 'self' 'unsafe-inline'; form-action 'none'; frame-ancestors 'none'")
h.ServeHTTP(w, req)
return
})
}

Expand Down Expand Up @@ -448,7 +447,7 @@ func (s *HTTPServer) wrap(handler func(resp http.ResponseWriter, req *http.Reque
reqURL := req.URL.String()
start := time.Now()
defer func() {
s.logger.Debug("request complete", "method", req.Method, "path", reqURL, "duration", time.Now().Sub(start))
s.logger.Debug("request complete", "method", req.Method, "path", reqURL, "duration", time.Since(start))
}()
obj, err := s.auditHandler(handler)(resp, req)

Expand Down Expand Up @@ -524,7 +523,7 @@ func (s *HTTPServer) wrapNonJSON(handler func(resp http.ResponseWriter, req *htt
reqURL := req.URL.String()
start := time.Now()
defer func() {
s.logger.Debug("request complete", "method", req.Method, "path", reqURL, "duration", time.Now().Sub(start))
s.logger.Debug("request complete", "method", req.Method, "path", reqURL, "duration", time.Since(start))
}()
obj, err := s.auditNonJSONHandler(handler)(resp, req)

Expand Down Expand Up @@ -595,7 +594,7 @@ func setMeta(resp http.ResponseWriter, m *structs.QueryMeta) {
// setHeaders is used to set canonical response header fields
func setHeaders(resp http.ResponseWriter, headers map[string]string) {
for field, value := range headers {
resp.Header().Set(http.CanonicalHeaderKey(field), value)
resp.Header().Set(field, value)
}
}

Expand Down
2 changes: 1 addition & 1 deletion command/agent_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (c *AgentInfoCommand) Run(args []string) int {

for _, key := range statsKeys {
c.Ui.Output(key)
statsData, _ := info.Stats[key]
statsData := info.Stats[key]
statsDataKeys := make([]string, len(statsData))
i := 0
for key := range statsData {
Expand Down
2 changes: 1 addition & 1 deletion command/agent_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (c *MonitorCommand) Run(args []string) int {

// Query the node info and lookup prefix
if len(nodeID) == 1 {
c.Ui.Error(fmt.Sprintf("Node identifier must contain at least two characters."))
c.Ui.Error("Node identifier must contain at least two characters.")
return 1
}

Expand Down
2 changes: 1 addition & 1 deletion command/alloc_exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ func (l *AllocExecCommand) Run(args []string) int {

// Query the allocation info
if len(allocID) == 1 {
l.Ui.Error(fmt.Sprintf("Alloc ID must contain at least two characters."))
l.Ui.Error("Alloc ID must contain at least two characters.")
return 1
}

Expand Down
2 changes: 1 addition & 1 deletion command/alloc_fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ func (f *AllocFSCommand) Run(args []string) int {
}
// Query the allocation info
if len(allocID) == 1 {
f.Ui.Error(fmt.Sprintf("Alloc ID must contain at least two characters."))
f.Ui.Error("Alloc ID must contain at least two characters.")
return 1
}

Expand Down
2 changes: 1 addition & 1 deletion command/alloc_logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func (l *AllocLogsCommand) Run(args []string) int {
}
// Query the allocation info
if len(allocID) == 1 {
l.Ui.Error(fmt.Sprintf("Alloc ID must contain at least two characters."))
l.Ui.Error("Alloc ID must contain at least two characters.")
return 1
}

Expand Down
2 changes: 1 addition & 1 deletion command/alloc_restart.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (c *AllocRestartCommand) Run(args []string) int {

// Query the allocation info
if len(allocID) == 1 {
c.Ui.Error(fmt.Sprintf("Alloc ID must contain at least two characters."))
c.Ui.Error("Alloc ID must contain at least two characters.")
return 1
}

Expand Down
2 changes: 1 addition & 1 deletion command/alloc_signal.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func (c *AllocSignalCommand) Run(args []string) int {

// Query the allocation info
if len(allocID) == 1 {
c.Ui.Error(fmt.Sprintf("Alloc ID must contain at least two characters."))
c.Ui.Error("Alloc ID must contain at least two characters.")
return 1
}

Expand Down
2 changes: 1 addition & 1 deletion command/alloc_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ func (c *AllocStatusCommand) Run(args []string) int {

// Query the allocation info
if len(allocID) == 1 {
c.Ui.Error(fmt.Sprintf("Identifier must contain at least two characters."))
c.Ui.Error("Identifier must contain at least two characters.")
return 1
}

Expand Down
2 changes: 1 addition & 1 deletion command/alloc_stop.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (c *AllocStopCommand) Run(args []string) int {

// Query the allocation info
if len(allocID) == 1 {
c.Ui.Error(fmt.Sprintf("Alloc ID must contain at least two characters."))
c.Ui.Error("Alloc ID must contain at least two characters.")
return 1
}

Expand Down
2 changes: 1 addition & 1 deletion command/eval_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ func (c *EvalStatusCommand) Run(args []string) int {

// Query the allocation info
if len(evalID) == 1 {
c.Ui.Error(fmt.Sprintf("Identifier must contain at least two characters."))
c.Ui.Error("Identifier must contain at least two characters.")
return 1
}

Expand Down
6 changes: 3 additions & 3 deletions command/job_plan.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ func (c *JobPlanCommand) addPreemptions(resp *api.JobPlanResponse) {
c.Ui.Output(c.Colorize().Color("[bold][yellow]Preemptions:\n[reset]"))
if len(resp.Annotations.PreemptedAllocs) < preemptionDisplayThreshold {
var allocs []string
allocs = append(allocs, fmt.Sprintf("Alloc ID|Job ID|Task Group"))
allocs = append(allocs, "Alloc ID|Job ID|Task Group")
for _, alloc := range resp.Annotations.PreemptedAllocs {
allocs = append(allocs, fmt.Sprintf("%s|%s|%s", alloc.ID, alloc.JobID, alloc.TaskGroup))
}
Expand Down Expand Up @@ -284,15 +284,15 @@ func (c *JobPlanCommand) addPreemptions(resp *api.JobPlanResponse) {
// Show counts grouped by job ID if its less than a threshold
var output []string
if numJobs < preemptionDisplayThreshold {
output = append(output, fmt.Sprintf("Job ID|Namespace|Job Type|Preemptions"))
output = append(output, "Job ID|Namespace|Job Type|Preemptions")
for jobType, jobCounts := range allocDetails {
for jobId, count := range jobCounts {
output = append(output, fmt.Sprintf("%s|%s|%s|%d", jobId.id, jobId.namespace, jobType, count))
}
}
} else {
// Show counts grouped by job type
output = append(output, fmt.Sprintf("Job Type|Preemptions"))
output = append(output, "Job Type|Preemptions")
for jobType, jobCounts := range allocDetails {
total := 0
for _, count := range jobCounts {
Expand Down
2 changes: 1 addition & 1 deletion command/job_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func (c *JobStatusCommand) Run(args []string) int {

if periodic && !parameterized {
if *job.Stop {
basic = append(basic, fmt.Sprintf("Next Periodic Launch|none (job stopped)"))
basic = append(basic, "Next Periodic Launch|none (job stopped)")
} else {
location, err := job.Periodic.GetLocation()
if err == nil {
Expand Down
2 changes: 1 addition & 1 deletion command/node_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (c *NodeConfigCommand) Run(args []string) int {
c.Ui.Error(fmt.Sprintf("Error updating server list: %s", err))
return 1
}
c.Ui.Output(fmt.Sprint("Updated server list"))
c.Ui.Output("Updated server list")
return 0
}

Expand Down
Loading

0 comments on commit 85ed8dd

Please sign in to comment.