Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable gocritic and gocyclo linters #2236

Merged
merged 8 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ linters:
- whitespace
- gocognit
- unparam
- gocyclo
- gocritic

run:
timeout: 10m # golangci-lint run's timeout.
Expand All @@ -29,3 +31,7 @@ issues:
- text: "`ctx` is unused" # Context might not be in use in places, but for consistency, we pass it.
linters:
- unparam

linters-settings:
gocyclo:
min-complexity: 20
2 changes: 1 addition & 1 deletion cmd/kanctl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (

func init() {
// We silence all non-fatal log messages.
//logrus.SetLevel(logrus.ErrorLevel)
// logrus.SetLevel(logrus.ErrorLevel)
}

func main() {
Expand Down
2 changes: 1 addition & 1 deletion pkg/blockstorage/awsefs/awsefs.go
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,7 @@ func (e *Efs) SnapshotsListWLimit(ctx context.Context, tags map[string]string, l
req := &backup.ListRecoveryPointsByBackupVaultInput{}
req.SetBackupVaultName(e.backupVaultName)
req.SetMaxResults(limit)
resp, err := e.ListRecoveryPointsByBackupVaultWithContext(ctx, req) //backup API
resp, err := e.ListRecoveryPointsByBackupVaultWithContext(ctx, req) // backup API
if err != nil {
return nil, errors.Wrap(err, "Failed to list recovery points by vault")
}
Expand Down
87 changes: 53 additions & 34 deletions pkg/blockstorage/azure/azuredisk.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,47 +199,20 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage.
blob := container.GetBlobReference(blobName)
defer deleteBlob(blob, blobName)

var copyOptions *storage.CopyOptions
if t, ok := ctx.Deadline(); ok {
time := time.Until(t).Seconds()
if time <= 0 {
return nil, errors.New("Context deadline exceeded, cannot copy snapshot")
}
copyOptions = &storage.CopyOptions{
Timeout: uint(time),
}
copyOptions, err := getCopyOptions(ctx)
if err != nil {
return nil, err
}
err = blob.Copy(*accessURI.AccessSAS, copyOptions)
if err != nil {
return nil, errors.Wrapf(err, "Failed to copy disk to blob")
}
blobURI := blob.GetURL()

snapId, err := uuid.NewV1()
if err != nil {
return nil, errors.Wrap(err, "Failed to create UUID")
}
snapName := fmt.Sprintf(snapshotNameFmt, snapId.String())
var tags = make(map[string]string)
for _, tag := range from.Volume.Tags {
if _, found := tags[tag.Key]; !found {
tags[tag.Key] = tag.Value
}
}
tags = blockstorage.SanitizeTags(ktags.GetTags(tags))

createSnap := azcompute.Snapshot{
Name: azto.StringPtr(snapName),
Location: azto.StringPtr(to.Region),
Tags: *azto.StringMapPtr(tags),
SnapshotProperties: &azcompute.SnapshotProperties{
CreationData: &azcompute.CreationData{
CreateOption: azcompute.Import,
StorageAccountID: azto.StringPtr(storageAccountID),
SourceURI: azto.StringPtr(blobURI),
},
},
}
createSnap := getSnapshotObject(blob, from, to, snapName, storageAccountID)

migrateResourceGroup := s.azCli.ResourceGroup
if val, ok := args[blockstorage.AzureMigrateResourceGroup]; ok && val != "" {
Expand All @@ -266,14 +239,60 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage.
return snap, nil
}

func getCopyOptions(ctx context.Context) (*storage.CopyOptions, error) {
var copyOptions *storage.CopyOptions
if t, ok := ctx.Deadline(); ok {
time := time.Until(t).Seconds()
if time <= 0 {
return nil, errors.New("Context deadline exceeded, cannot copy snapshot")
}
copyOptions = &storage.CopyOptions{
Timeout: uint(time),
}
}
return copyOptions, nil
}

func getSnapshotObject(
blob *storage.Blob,
from,
to blockstorage.Snapshot,
snapName,
storageAccountID string,
) azcompute.Snapshot {
blobURI := blob.GetURL()

var tags = make(map[string]string)
for _, tag := range from.Volume.Tags {
if _, found := tags[tag.Key]; !found {
tags[tag.Key] = tag.Value
}
}
tags = blockstorage.SanitizeTags(ktags.GetTags(tags))

createSnap := azcompute.Snapshot{
Name: azto.StringPtr(snapName),
Location: azto.StringPtr(to.Region),
Tags: *azto.StringMapPtr(tags),
SnapshotProperties: &azcompute.SnapshotProperties{
CreationData: &azcompute.CreationData{
CreateOption: azcompute.Import,
StorageAccountID: azto.StringPtr(storageAccountID),
SourceURI: azto.StringPtr(blobURI),
},
},
}
return createSnap
}

func isMigrateStorageAccountorKey(migrateStorageAccount, migrateStorageKey string) bool {
return migrateStorageAccount == "" || migrateStorageKey == ""
}

func (s *AdStorage) revokeAccess(ctx context.Context, rg, name, ID string) {
func (s *AdStorage) revokeAccess(ctx context.Context, rg, name, id string) {
_, err := s.azCli.SnapshotsClient.RevokeAccess(ctx, rg, name)
if err != nil {
log.Print("Failed to revoke access from snapshot", field.M{"snapshot": ID})
log.Print("Failed to revoke access from snapshot", field.M{"snapshot": id})
}
}

Expand Down Expand Up @@ -545,7 +564,7 @@ func (s *AdStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot block
}

func (s *AdStorage) getRegionAndZoneID(ctx context.Context, sourceRegion, volAz string) (string, string, error) {
//check if current node region is zoned or not
// check if current node region is zoned or not
kubeCli, err := kube.NewClient()
if err != nil {
return "", "", err
Expand Down
10 changes: 5 additions & 5 deletions pkg/blockstorage/tags/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,14 @@ func IsSubset(set map[string]string, subset map[string]string) bool {
return true
}

// Union returns union of A and B as a new map.
// B's values have priority if a key from A and B collides.
func Union(A map[string]string, B map[string]string) map[string]string {
// Union returns union of first and second as a new map.
// second's values have priority if a key from first and second collides.
func Union(first map[string]string, second map[string]string) map[string]string {
result := make(map[string]string)
for k, v := range A {
for k, v := range first {
result[k] = v
}
for k, v := range B {
for k, v := range second {
result[k] = v
}
return result
Expand Down
7 changes: 4 additions & 3 deletions pkg/blockstorage/vmware/vmware.go
Original file line number Diff line number Diff line change
Expand Up @@ -811,11 +811,12 @@ func (ge govmomiError) ExtractMessages() []string {
case govmomitask.Error:
foundHandledErrorType = true
default:
if soap.IsSoapFault(err) {
switch {
case soap.IsSoapFault(err):
foundHandledErrorType = true
} else if soap.IsVimFault(err) {
case soap.IsVimFault(err):
foundHandledErrorType = true
} else {
default:
err = errors.Unwrap(err)
}
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/blockstorage/zone/zone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (

"github.com/kanisterio/kanister/pkg/kube"
. "gopkg.in/check.v1"
"k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/fake"
Expand Down Expand Up @@ -543,14 +543,14 @@ func (s ZoneSuite) TestFromSourceRegionZone(c *C) {
outZones []string
outErr error
}{
{ //success case
{ // success case
inRegion: "us-west-2",
inZones: []string{"us-west-2a"},
inCli: cli,
outZones: []string{"us-west-2a"},
outErr: nil,
},
{ //success case gce multi region
{ // success case gce multi region
inRegion: "us-west1",
inZones: []string{"us-west1-a"},
inCli: cligce,
Expand Down
5 changes: 3 additions & 2 deletions pkg/blueprint/validate/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,10 @@ func Do(bp *crv1alpha1.Blueprint, funcVersion string) error {
func validatePhaseNames(bp *crv1alpha1.Blueprint) error {
phasesCount := make(map[string]int)
for _, action := range bp.Actions {
allPhases := action.Phases
allPhases := []crv1alpha1.BlueprintPhase{}
allPhases = append(allPhases, action.Phases...)
if action.DeferPhase != nil {
allPhases = append(action.Phases, *action.DeferPhase)
allPhases = append(allPhases, *action.DeferPhase)
}

for _, phase := range allPhases {
Expand Down
7 changes: 4 additions & 3 deletions pkg/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,11 +232,12 @@ func (c *Controller) onUpdateActionSet(oldAS, newAS *crv1alpha1.ActionSet) error
return err
}
if newAS.Status == nil || newAS.Status.State != crv1alpha1.StateRunning {
if newAS.Status == nil {
switch {
case newAS.Status == nil:
log.WithContext(ctx).Print("Updated ActionSet", field.M{"Status": "nil"})
} else if newAS.Status.State == crv1alpha1.StateComplete {
case newAS.Status.State == crv1alpha1.StateComplete:
c.logAndSuccessEvent(ctx, fmt.Sprintf("Updated ActionSet '%s' Status->%s", newAS.Name, newAS.Status.State), "Update Complete", newAS)
} else {
default:
log.WithContext(ctx).Print("Updated ActionSet", field.M{"Status": newAS.Status.State})
}
return nil
Expand Down
10 changes: 5 additions & 5 deletions pkg/controller/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -664,15 +664,15 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *C) {
msg := "Unit testing event logs"
reason := "Test Logs"

//Create nil ActionSet
// Create nil ActionSet
var nilAs = (*crv1alpha1.ActionSet)(nil)

// Create Blueprint
bp := testutil.NewTestBlueprint("StatefulSet", testutil.WaitFuncName)
bp, err = s.crCli.Blueprints(s.namespace).Create(ctx, bp, metav1.CreateOptions{})
c.Assert(err, IsNil)

//Test the logAndErrorEvent function
// Test the logAndErrorEvent function
ctx = field.Context(ctx, consts.ActionsetNameKey, as.GetName())
config, err := kube.LoadConfig()
c.Assert(err, IsNil)
Expand All @@ -686,19 +686,19 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *C) {
c.Assert(len(events.Items) > 0, Equals, true)
c.Assert(events.Items[0].Message, Equals, msg)

//Testing nil ActionSet error event logging
// Testing nil ActionSet error event logging
events, err = s.cli.CoreV1().Events(as.Namespace).Search(scheme.Scheme, nilAs)
c.Assert(err, NotNil)
c.Assert(len(events.Items), Equals, 0)

//Testing Blueprint error event logging
// Testing Blueprint error event logging
events, err = s.cli.CoreV1().Events(bp.Namespace).Search(scheme.Scheme, bp)
c.Assert(err, IsNil)
c.Assert(events, NotNil)
c.Assert(len(events.Items) > 0, Equals, true)
c.Assert(events.Items[0].Message, Equals, msg)

//Testing empty Blueprint
// Testing empty Blueprint
testbp := &crv1alpha1.Blueprint{}
ctlr.logAndErrorEvent(ctx, msg, reason, errors.New("Testing Event Logs"), testbp)
events, err = s.cli.CoreV1().Events(bp.Namespace).Search(scheme.Scheme, testbp)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ func (s *RepoServerControllerSuite) TestRepositoryServerStatusIsServerReady(c *C
err = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name)
c.Assert(err, IsNil)

//Get repository server CR with the updated server information
// Get repository server CR with the updated server information
repoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{})
c.Assert(err, IsNil)

Expand Down Expand Up @@ -294,7 +294,7 @@ func (s *RepoServerControllerSuite) TestCreationOfOwnedResources(c *C) {
err = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name)
c.Assert(err, IsNil)

//Get repository server CR with the updated server information
// Get repository server CR with the updated server information
repoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{})
c.Assert(err, IsNil)

Expand Down Expand Up @@ -401,7 +401,7 @@ func (s *RepoServerControllerSuite) TestFilestoreLocationVolumeMountOnRepoServer
err = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name)
c.Assert(err, IsNil)

//Get repository server CR with the updated server information
// Get repository server CR with the updated server information
repoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{})
c.Assert(err, IsNil)

Expand Down
2 changes: 1 addition & 1 deletion pkg/datamover/profile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (ps *ProfileSuite) TestLocationOperationsForProfileDataMover(c *C) {
err = locationDelete(ps.ctx, p, path)
c.Assert(err, IsNil)

//test deleting dir with multiple artifacts
// test deleting dir with multiple artifacts
source = bytes.NewBufferString(testContent)
err = locationPush(ps.ctx, p, path, source)
c.Assert(err, IsNil)
Expand Down
2 changes: 1 addition & 1 deletion pkg/filter/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ type ResourceRequirement struct {
// DeepCopyInto provides explicit deep copy implementation to avoid
func (r ResourceRequirement) DeepCopyInto(out *ResourceRequirement) {
r.LocalObjectReference.DeepCopyInto(&out.LocalObjectReference)
(*out).ResourceTypeRequirement = r.ResourceTypeRequirement
out.ResourceTypeRequirement = r.ResourceTypeRequirement
r.LabelSelector.DeepCopyInto(&out.LabelSelector)
}

Expand Down
3 changes: 1 addition & 2 deletions pkg/function/export_rds_snapshot_location.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,7 @@ func prepareCommand(ctx context.Context, dbEngine RDSDBEngine, action RDSAction,
dbList = filterRestrictedDB(dbList)
}

switch dbEngine {
case PostgrSQLEngine:
if dbEngine == PostgrSQLEngine {
switch action {
case BackupAction:
command, err := postgresBackupCommand(dbEndpoint, username, password, dbList, backupPrefix, backupID, profileJson)
Expand Down
6 changes: 2 additions & 4 deletions pkg/kanctl/actionset.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,7 @@ func newActionSetCmd() *cobra.Command {
Use: "actionset",
Short: "Create a new ActionSet or override a <parent> ActionSet",
Args: cobra.ExactArgs(0),
RunE: func(c *cobra.Command, args []string) error {
return initializeAndPerform(c, args)
},
RunE: initializeAndPerform,
}
cmd.Flags().StringP(sourceFlagName, "f", "", "specify name of the action set")

Expand Down Expand Up @@ -503,7 +501,7 @@ func parseGenericObjectReference(s string) (crv1alpha1.ObjectReference, error) {
}, nil
}

func parseObjectsFromSelector(selector, kind, sns string, cli kubernetes.Interface, osCli osversioned.Interface, parsed map[string]bool) ([]crv1alpha1.ObjectReference, error) {
func parseObjectsFromSelector(selector, kind, sns string, cli kubernetes.Interface, osCli osversioned.Interface, parsed map[string]bool) ([]crv1alpha1.ObjectReference, error) { //nolint:gocyclo
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this fail even with 30 cyclo limit?

Copy link
Contributor Author

@ankitjain235 ankitjain235 Oct 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are setting the limit to 20, that's where it's failing. It has complexity of 21.

ctx := context.Background()
var objects []crv1alpha1.ObjectReference
appendObj := func(kind, namespace, name string) {
Expand Down
Loading