Skip to content

Commit

Permalink
chore(lint): Enable linting with gosimple
Browse files Browse the repository at this point in the history
This fixes issues found by the gosimple linter and enables it in the
golangci config.

Signed-off-by: Manuel Rüger <[email protected]>
  • Loading branch information
mrueg authored and youngnick committed Jul 28, 2023
1 parent 4d50054 commit 61477fc
Show file tree
Hide file tree
Showing 95 changed files with 202 additions and 353 deletions.
1 change: 1 addition & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ linters:
- goheader
- gosec
- gomodguard
- gosimple

# To enable later if makes sense
# - deadcode
Expand Down
2 changes: 1 addition & 1 deletion bugtool/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ func writeCmdToFile(cmdDir, prompt string, k8sPods []string, enableMarkdown bool
fmt.Fprint(f, string(output))
} else if enableMarkdown && len(output) > 0 {
// Write prompt as header and the output as body, and/or error but delete empty output.
fmt.Fprint(f, fmt.Sprintf("# %s\n\n```\n%s\n```\n", prompt, output))
fmt.Fprintf(f, "# %s\n\n```\n%s\n```\n", prompt, output)
}
}

Expand Down
2 changes: 1 addition & 1 deletion cilium/cmd/bpf_sha_get.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func dumpSha(sha string) {
Fatalf("Error preparing regex for parsing JSON: %s\n", err)
}

jsonEncStr := regex.FindString(fmt.Sprintf("%s", text))
jsonEncStr := regex.FindString(string(text))
if jsonEncStr == "" {
Fatalf("No JSON embedded in the file.")
}
Expand Down
2 changes: 1 addition & 1 deletion cilium/cmd/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ func runCleanup() {
cleanBPF = vp.GetBool(bpfFlagName) || vp.GetBool(cleanBpfEnvVar)

// if no flags are specified then clean all
if (cleanAll || cleanBPF) == false {
if !(cleanAll || cleanBPF) {
cleanAll = true
}

Expand Down
1 change: 0 additions & 1 deletion cilium/cmd/debuginfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,6 @@ func writeJSONPathToOutput(buf bytes.Buffer, path string, suffix string, jsonPat
writeFile([]byte(jsonStr), fileName)

fmt.Printf("%s output at %s\n", jsonpathOutput, fileName)
return
}

func writeToOutput(buf bytes.Buffer, output outputType, path string, suffix string) {
Expand Down
2 changes: 1 addition & 1 deletion cilium/cmd/lrp_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func printLRPList(w *tabwriter.Writer, list []*models.LRPSpec) {
entry := fmt.Sprintf("%s\t%s\t%s\t%s", lrp.Namespace, lrp.Name, lrp.FrontendType, lrp.ServiceID)
fmt.Fprintln(w, entry)
for _, feM := range lrp.FrontendMappings {
fmt.Fprintln(w, fmt.Sprintf("\t|\t%s", getPrintableMapping(feM)))
fmt.Fprintf(w, "\t|\t%s\n", getPrintableMapping(feM))
}
}
w.Flush()
Expand Down
7 changes: 2 additions & 5 deletions cilium/cmd/prefilter_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ func init() {
}

func listFilters(cmd *cobra.Command, args []string) {
var str string
spec, err := client.GetPrefilter()
if err != nil {
Fatalf("Cannot get CIDR list: %s", err)
Expand All @@ -45,11 +44,9 @@ func listFilters(cmd *cobra.Command, args []string) {
Fatalf("Cannot get CIDR list: empty response")
}
w := tabwriter.NewWriter(os.Stdout, 5, 0, 3, ' ', 0)
str = fmt.Sprintf("Revision: %d", spec.Status.Realized.Revision)
fmt.Fprintln(w, str)
fmt.Fprintf(w, "Revision: %d\n", spec.Status.Realized.Revision)
for _, pfx := range spec.Status.Realized.Deny {
str = fmt.Sprintf("%s", pfx)
fmt.Fprintln(w, str)
fmt.Fprintln(w, pfx)
}
w.Flush()
}
1 change: 0 additions & 1 deletion daemon/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ func (c *ConfigModifyEvent) configModify(params PatchConfigParams, resChan chan
}

resChan <- NewPatchConfigOK()
return
}

func patchConfigHandler(d *Daemon, params PatchConfigParams) middleware.Responder {
Expand Down
2 changes: 1 addition & 1 deletion daemon/cmd/debuginfo.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func getDebugInfoHandler(d *Daemon, params restapi.GetDebuginfoParams) middlewar
if kver, err := version.GetKernelVersion(); err != nil {
dr.KernelVersion = fmt.Sprintf("Error: %s\n", err)
} else {
dr.KernelVersion = fmt.Sprintf("%s", kver)
dr.KernelVersion = kver.String()
}

status := d.getStatus(false)
Expand Down
2 changes: 1 addition & 1 deletion daemon/cmd/kube_proxy_replacement.go
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ func finishKubeProxyReplacementInit() error {
default:
if probes.HaveProgramHelper(ebpf.SchedCLS, asm.FnRedirectNeigh) != nil ||
probes.HaveProgramHelper(ebpf.SchedCLS, asm.FnRedirectPeer) != nil {
msg = fmt.Sprintf("BPF host routing requires kernel 5.10 or newer.")
msg = "BPF host routing requires kernel 5.10 or newer."
}
}
if msg != "" {
Expand Down
4 changes: 0 additions & 4 deletions daemon/cmd/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,8 +393,6 @@ func (d *Daemon) policyAdd(sourceRules policyAPI.Rules, opts *policy.AddOptions,
if err != nil {
log.WithError(err).WithField(logfields.PolicyRevision, newRev).Error("enqueue of RuleReactionEvent failed")
}

return
}

// PolicyReactionEvent is an event which needs to be serialized after changes
Expand Down Expand Up @@ -616,8 +614,6 @@ func (d *Daemon) policyDelete(labels labels.LabelArray, opts *policy.DeleteOptio
if err := d.SendNotification(monitorAPI.PolicyDeleteMessage(deleted, labels.GetModel(), rev)); err != nil {
log.WithError(err).WithField(logfields.PolicyRevision, rev).Warn("Failed to send policy update as monitor notification")
}

return
}

func deletePolicyHandler(d *Daemon, params DeletePolicyParams) middleware.Responder {
Expand Down
16 changes: 7 additions & 9 deletions daemon/cmd/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,14 +249,12 @@ func (d *Daemon) restoreOldEndpoints(state *endpointRestoreState, clean bool) er
"failed": failed,
}).Info("Endpoints restored")

if existingEndpoints != nil {
for epIP, info := range existingEndpoints {
if ip := net.ParseIP(epIP); !info.IsHost() && ip != nil {
if err := lxcmap.DeleteEntry(ip); err != nil {
log.WithError(err).Warn("Unable to delete obsolete endpoint from BPF map")
} else {
log.Debugf("Removed outdated endpoint %d from endpoint map", info.LxcID)
}
for epIP, info := range existingEndpoints {
if ip := net.ParseIP(epIP); !info.IsHost() && ip != nil {
if err := lxcmap.DeleteEntry(ip); err != nil {
log.WithError(err).Warn("Unable to delete obsolete endpoint from BPF map")
} else {
log.Debugf("Removed outdated endpoint %d from endpoint map", info.LxcID)
}
}
}
Expand All @@ -265,7 +263,7 @@ func (d *Daemon) restoreOldEndpoints(state *endpointRestoreState, clean bool) er
}

func (d *Daemon) regenerateRestoredEndpoints(state *endpointRestoreState) (restoreComplete chan struct{}) {
restoreComplete = make(chan struct{}, 0)
restoreComplete = make(chan struct{})

log.WithField("numRestored", len(state.restored)).Info("Regenerating restored endpoints")

Expand Down
6 changes: 1 addition & 5 deletions daemon/cmd/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -526,12 +526,10 @@ func (c *clusterNodesClient) NodeNeighDiscoveryEnabled() bool {

func (c *clusterNodesClient) NodeNeighborRefresh(ctx context.Context, node nodeTypes.Node) {
// no-op
return
}

func (c *clusterNodesClient) NodeCleanNeighbors(migrateOnly bool) {
// no-op
return
}

func (c *clusterNodesClient) GetNodeIP(_ uint16) string {
Expand All @@ -546,7 +544,6 @@ func (c *clusterNodesClient) DumpNodeIDs() []*models.NodeID {

func (c *clusterNodesClient) RestoreNodeIDs() {
// no-op
return
}

func (h *getNodes) cleanupClients(d *Daemon) {
Expand Down Expand Up @@ -766,7 +763,7 @@ func (d *Daemon) startStatusCollector(cleaner *daemonCleanup) {
state = models.StatusStateFailure
msg = fmt.Sprintf("Err: %s", status.Err)
case ok:
msg = fmt.Sprintf("%s", info)
msg = info
}

d.statusCollectMutex.Lock()
Expand Down Expand Up @@ -1074,5 +1071,4 @@ func (d *Daemon) startStatusCollector(cleaner *daemonCleanup) {

}
})
return
}
3 changes: 0 additions & 3 deletions operator/pkg/ciliumendpointslice/endpointslice.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,6 @@ func (c *CiliumEndpointSliceController) Run(ces cache.Indexer, stopCh <-chan str
}()

<-stopCh

return
}

// Upon warm boot[restart], Iterate over all CEPs which we got from the api-server
Expand Down Expand Up @@ -274,7 +272,6 @@ func syncCESsInLocalCache(cesStore cache.Store, manager operations) {

}
log.Debug("Successfully synced all CESs locally")
return
}

// worker runs a worker thread that just dequeues items, processes them, and
Expand Down
3 changes: 1 addition & 2 deletions operator/pkg/ciliumendpointslice/endpointslice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,7 @@ func TestHandleErr(t *testing.T) {
updatedCES.Generation = 2
cesController.ciliumEndpointSliceStore.Add(updatedCES)

var err error
err = k8s_errors.NewConflict(
var err error = k8s_errors.NewConflict(
schema.GroupResource{Group: "", Resource: "ciliumendpointslices"},
key,
fmt.Errorf("conflict"))
Expand Down
9 changes: 2 additions & 7 deletions operator/pkg/ciliumendpointslice/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,13 +176,10 @@ func (c *cesMgr) addCEPtoCES(cep *cilium_v2.CoreCiliumEndpoint, ces *cesTracker)
ces.ces.Endpoints = append(ces.ces.Endpoints, *cep)
// If this CEP is re-generated again before previous CEP-DELETE completed.
// remove this from removedCEP list.
if _, ok := ces.removedCEPs[GetCEPNameFromCCEP(cep, ces.ces.Namespace)]; ok {
delete(ces.removedCEPs, GetCEPNameFromCCEP(cep, ces.ces.Namespace))
}
delete(ces.removedCEPs, GetCEPNameFromCCEP(cep, ces.ces.Namespace))
// Increment the cepInsert counter
ces.cepInserted += 1
c.insertCESInWorkQueue(ces, DefaultCESSyncTime)
return
}

// Generate random string for given length of characters.
Expand Down Expand Up @@ -370,8 +367,6 @@ func (c *cesMgr) RemoveCEPFromCache(cepName string, baseDelay time.Duration) {
logfields.CEPName: cepName,
}).Debug("Could not remove CEP from local cache missing CEPName.")
}

return
}

func (c *cesMgr) removeCEPFromCES(cepName string, cesName string, baseDelay time.Duration, identity int64, checkIdentity bool) {
Expand Down Expand Up @@ -584,7 +579,7 @@ func (c *cesManagerIdentity) deleteCESFromCache(cesName string) {
}

c.identityLock.Lock()
identity, _ := c.cesToIdentity[cesName]
identity := c.cesToIdentity[cesName]
for i, ces := range c.identityToCES[identity] {
if cesName == ces.ces.GetName() {
c.identityToCES[identity] = append(c.identityToCES[identity][:i],
Expand Down
3 changes: 1 addition & 2 deletions operator/pkg/ciliumenvoyconfig/envoy_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,7 @@ func (m *Manager) getListenerResource(svc *slim_corev1.Service) (ciliumv2.XDSRes
return ciliumv2.XDSResource{}, nil
}

var filterChains []*envoy_config_listener.FilterChain
filterChains = []*envoy_config_listener.FilterChain{
var filterChains []*envoy_config_listener.FilterChain = []*envoy_config_listener.FilterChain{
{
FilterChainMatch: &envoy_config_listener.FilterChainMatch{
TransportProtocol: "raw_buffer",
Expand Down
2 changes: 1 addition & 1 deletion operator/pkg/gateway-api/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ func Test_success(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := success()
if !tt.wantErr(t, err, fmt.Sprintf("success()")) {
if !tt.wantErr(t, err, "success()") {
return
}
assert.Equalf(t, tt.want, got, "success()")
Expand Down
2 changes: 1 addition & 1 deletion operator/pkg/ingress/ingress_class.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ func (i *ingressClassManager) handleIngressClassDeletedEvent(event ingressClassD
log.WithField(logfields.IngressClass, event.ingressClass).Debug("Handling ingress class delete")

if event.ingressClass.GetName() == ciliumIngressClassName {
i.ingressQueue.Add(ciliumIngressClassDeletedEvent{ingressClass: event.ingressClass})
i.ingressQueue.Add(ciliumIngressClassDeletedEvent(event))
}
return nil
}
Expand Down
12 changes: 2 additions & 10 deletions operator/pkg/lbipam/lbipam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,7 @@ func TestPoolInternalConflict(t *testing.T) {

pool := fixture.PatchedPool(action)

if !isPoolConflicting(pool) {
return false
}

return true
return !isPoolConflicting(pool)
}, time.Second)

go fixture.hive.Start(context.Background())
Expand All @@ -151,11 +147,7 @@ func TestPoolInternalConflict(t *testing.T) {

pool := fixture.PatchedPool(action)

if isPoolConflicting(pool) {
return false
}

return true
return !isPoolConflicting(pool)
}, 2*time.Second)

pool, err := fixture.poolClient.Get(context.Background(), "pool-a", meta_v1.GetOptions{})
Expand Down
6 changes: 2 additions & 4 deletions operator/pkg/model/translation/envoy_virtual_host.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,8 @@ func (s SortableRoute) Less(i, j int) bool {
// Make sure the longest header match always comes first
headerMatch1 := len(s[i].Match.GetHeaders())
headerMatch2 := len(s[j].Match.GetHeaders())
if headerMatch1 > headerMatch2 {
return true
}
return false

return headerMatch1 > headerMatch2
}

func (s SortableRoute) Swap(i, j int) {
Expand Down
2 changes: 1 addition & 1 deletion operator/watchers/k8s_service_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ type ServiceSyncParameters struct {
// will be synchronized. For clustermesh we only need to synchronize shared services, while for
// VM support we need to sync all the services.
func StartSynchronizingServices(ctx context.Context, wg *sync.WaitGroup, cfg ServiceSyncParameters) {
kvstoreReady := make(chan struct{}, 0)
kvstoreReady := make(chan struct{})

wg.Add(1)
go func() {
Expand Down
14 changes: 5 additions & 9 deletions pkg/alibabacloud/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,7 @@ func (c *Client) GetInstanceTypes(ctx context.Context) ([]ecs.InstanceType, erro
return nil, err
}

for _, v := range resp.InstanceTypes.InstanceType {
result = append(result, v)
}
result = append(result, resp.InstanceTypes.InstanceType...)

if resp.NextToken == "" {
break
Expand Down Expand Up @@ -412,9 +410,8 @@ func (c *Client) describeNetworkInterfaces(ctx context.Context) ([]ecs.NetworkIn
return nil, err
}

for _, v := range resp.NetworkInterfaceSets.NetworkInterfaceSet {
result = append(result, v)
}
result = append(result, resp.NetworkInterfaceSets.NetworkInterfaceSet...)

if resp.NextToken == "" {
break
} else {
Expand Down Expand Up @@ -442,9 +439,8 @@ func (c *Client) describeNetworkInterfacesByInstance(ctx context.Context, instan
break
}

for _, v := range resp.NetworkInterfaceSets.NetworkInterfaceSet {
result = append(result, v)
}
result = append(result, resp.NetworkInterfaceSets.NetworkInterfaceSet...)

if resp.TotalCount < resp.PageNumber*resp.PageSize {
break
}
Expand Down
2 changes: 0 additions & 2 deletions pkg/alibabacloud/eni/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,6 @@ func (n *Node) PopulateStatusFields(resource *v2.CiliumNode) {
}
return nil
})

return
}

// CreateInterface creates an additional interface with the instance and
Expand Down
2 changes: 0 additions & 2 deletions pkg/aws/eni/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,6 @@ func (n *Node) PopulateStatusFields(k8sObj *v2.CiliumNode) {
}
return nil
})

return
}

// getLimits returns the interface and IP limits of this node
Expand Down
2 changes: 1 addition & 1 deletion pkg/bgpv1/gobgp/conversions.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func ToAgentPath(p *gobgp.Path) (*types.Path, error) {

// ageNano is time since the Path was created in nanoseconds.
// It is calculated by difference in time from age timestamp till now.
ageNano := int64(time.Now().Sub(p.Age.AsTime()))
ageNano := int64(time.Since(p.Age.AsTime()))

return &types.Path{
NLRI: nlri,
Expand Down
2 changes: 1 addition & 1 deletion pkg/bgpv1/gobgp/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (g *GoBGPServer) GetPeerState(ctx context.Context) (types.GetPeerStateRespo
// Uptime is time since session got established.
// It is calculated by difference in time from uptime timestamp till now.
if peer.State.SessionState == gobgp.PeerState_ESTABLISHED && peer.Timers != nil && peer.Timers.State != nil {
peerState.UptimeNanoseconds = int64(time.Now().Sub(peer.Timers.State.Uptime.AsTime()))
peerState.UptimeNanoseconds = int64(time.Since(peer.Timers.State.Uptime.AsTime()))
}
}

Expand Down
Loading

0 comments on commit 61477fc

Please sign in to comment.