From c1f63af489455c6df0b3e74b566129fe57704711 Mon Sep 17 00:00:00 2001 From: Youngjun Date: Tue, 16 Apr 2024 11:45:52 +0900 Subject: [PATCH] refectoring: refectoring code - Remove unnecessary initial value settings - Remove unused variables - Added missing error handling - Remove unnecessary string nil check - Remove unnecessary fmt.Sprintf() - Add cancel to context.WithTimeout() Signed-off-by: Youngjun --- chaoscenter/authentication/pkg/utils/mongo_database.go | 4 +++- chaoscenter/graphql/server/pkg/authorization/validate.go | 2 +- .../graphql/server/pkg/chaos_infrastructure/infra_utils.go | 4 ++-- chaoscenter/graphql/server/pkg/chaoshub/handler/types.go | 6 +++--- chaoscenter/graphql/server/pkg/chaoshub/service.go | 2 +- .../pkg/database/mongodb/chaos_infrastructure/operations.go | 4 +--- chaoscenter/graphql/server/pkg/gitops/service.go | 4 ++-- chaoscenter/graphql/server/pkg/grpc/auth_grpc_client.go | 2 +- chaoscenter/graphql/server/pkg/probe/handler/handler.go | 2 +- chaoscenter/graphql/server/pkg/projects/project_handler.go | 2 +- chaoscenter/subscriber/pkg/events/chaosengine.go | 5 ++++- chaoscenter/subscriber/pkg/events/util.go | 2 +- chaoscenter/subscriber/pkg/requests/webhook.go | 6 +++--- 13 files changed, 24 insertions(+), 21 deletions(-) diff --git a/chaoscenter/authentication/pkg/utils/mongo_database.go b/chaoscenter/authentication/pkg/utils/mongo_database.go index f01aab42113..764e1ee459a 100644 --- a/chaoscenter/authentication/pkg/utils/mongo_database.go +++ b/chaoscenter/authentication/pkg/utils/mongo_database.go @@ -13,7 +13,9 @@ import ( // MongoConnection creates a connection to the mongo func MongoConnection() (*mongo.Client, error) { - ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + mongoCredentials := options.Credential{ Username: DBUser, Password: DBPassword, diff --git a/chaoscenter/graphql/server/pkg/authorization/validate.go b/chaoscenter/graphql/server/pkg/authorization/validate.go index a7b5e77329d..d6712909f70 100644 --- a/chaoscenter/graphql/server/pkg/authorization/validate.go +++ b/chaoscenter/graphql/server/pkg/authorization/validate.go @@ -14,7 +14,7 @@ func ValidateRole(ctx context.Context, projectID string, requiredRoles []string, invitation string) error { jwt := ctx.Value(AuthKey).(string) var conn *grpc2.ClientConn - client, conn := grpc.GetAuthGRPCSvcClient(conn) + client, conn := grpc.GetAuthGRPCSvcClient() defer conn.Close() err := grpc.ValidatorGRPCRequest(client, jwt, projectID, requiredRoles, diff --git a/chaoscenter/graphql/server/pkg/chaos_infrastructure/infra_utils.go b/chaoscenter/graphql/server/pkg/chaos_infrastructure/infra_utils.go index d28acc65ac9..009419bd131 100644 --- a/chaoscenter/graphql/server/pkg/chaos_infrastructure/infra_utils.go +++ b/chaoscenter/graphql/server/pkg/chaos_infrastructure/infra_utils.go @@ -116,11 +116,11 @@ func ManifestParser(infra dbChaosInfra.ChaosInfra, rootPath string, config *Subs // Checking if the agent namespace does not exist and its scope of installation is not namespaced if *infra.InfraNsExists == false && infra.InfraScope != "namespace" { - generatedYAML = append(generatedYAML, fmt.Sprintf(namespaceConfig)) + generatedYAML = append(generatedYAML, namespaceConfig) } if *infra.InfraSaExists == false { - generatedYAML = append(generatedYAML, fmt.Sprintf(serviceAccountStr)) + generatedYAML = append(generatedYAML, serviceAccountStr) } // File operations diff --git a/chaoscenter/graphql/server/pkg/chaoshub/handler/types.go b/chaoscenter/graphql/server/pkg/chaoshub/handler/types.go index f44a4ccfc51..8bc5ccd4545 100644 --- a/chaoscenter/graphql/server/pkg/chaoshub/handler/types.go +++ b/chaoscenter/graphql/server/pkg/chaoshub/handler/types.go @@ -20,9 +20,9 @@ type Link struct { type Faults struct { Name string `yaml:"name" json:"name"` - DisplayName string `json:"displayName" json:"displayName"` + DisplayName string `yaml:"displayName" json:"displayName"` Description string `yaml:"description" json:"description"` - Plan []string `json:"plan" json:"plan"` + Plan []string `yaml:"plan" json:"plan"` } type Metadata struct { @@ -43,7 +43,7 @@ type Annotation struct { type Spec struct { DisplayName string `yaml:"displayName" json:"displayName"` CategoryDescription string `yaml:"categoryDescription" json:"categoryDescription"` - Plan []string `json:"plan" json:"plan"` + Plan []string `yaml:"plan" json:"plan"` Keywords []string `yaml:"keywords" json:"keywords"` Maturity string `yaml:"maturity" json:"maturity,omitempty"` Maintainers []Maintainer `yaml:"maintainers" json:"maintainers,omitempty"` diff --git a/chaoscenter/graphql/server/pkg/chaoshub/service.go b/chaoscenter/graphql/server/pkg/chaoshub/service.go index d2dcc2b994e..aaffbe7542e 100644 --- a/chaoscenter/graphql/server/pkg/chaoshub/service.go +++ b/chaoscenter/graphql/server/pkg/chaoshub/service.go @@ -930,7 +930,7 @@ func (c *chaosHubService) GetAllHubs(ctx context.Context) ([]*model.ChaosHub, er func (c *chaosHubService) RecurringHubSync() { for { // Started Syncing of hubs - chaosHubs, _ := c.GetAllHubs(nil) + chaosHubs, _ := c.GetAllHubs(context.TODO()) for _, chaosHub := range chaosHubs { if !chaosHub.IsRemoved { diff --git a/chaoscenter/graphql/server/pkg/database/mongodb/chaos_infrastructure/operations.go b/chaoscenter/graphql/server/pkg/database/mongodb/chaos_infrastructure/operations.go index 19fce69b492..e0bef4b8a82 100644 --- a/chaoscenter/graphql/server/pkg/database/mongodb/chaos_infrastructure/operations.go +++ b/chaoscenter/graphql/server/pkg/database/mongodb/chaos_infrastructure/operations.go @@ -82,9 +82,7 @@ func (c *Operator) UpdateInfra(ctx context.Context, query bson.D, update bson.D) // GetInfraWithProjectID takes projectID parameters to retrieve the chaos_infra details func (c *Operator) GetInfraWithProjectID(projectID string) ([]*ChaosInfra, error) { - var query bson.D - query = bson.D{ - + var query = bson.D{ {"project_id", projectID}, {"is_removed", false}, } diff --git a/chaoscenter/graphql/server/pkg/gitops/service.go b/chaoscenter/graphql/server/pkg/gitops/service.go index 9fbb662fecd..e066369ecc2 100644 --- a/chaoscenter/graphql/server/pkg/gitops/service.go +++ b/chaoscenter/graphql/server/pkg/gitops/service.go @@ -116,7 +116,7 @@ func (g *gitOpsService) EnableGitOpsHandler(ctx context.Context, projectID strin defer gitLock.Unlock(config.RepoURL, &config.Branch) var conn *grpc2.ClientConn - client, conn := grpc.GetAuthGRPCSvcClient(conn) + client, conn := grpc.GetAuthGRPCSvcClient() defer conn.Close() _, err := grpc.GetProjectById(client, projectID) @@ -378,7 +378,7 @@ func (g *gitOpsService) gitSyncHelper(config gitops.GitConfigDB, wg *sync.WaitGr gitConfig := GetGitOpsConfig(*conf) - err = g.SyncDBToGit(nil, gitConfig) + err = g.SyncDBToGit(context.TODO(), gitConfig) if err != nil { logrus.Error("Repo Sync ERROR: ", conf.ProjectID, err.Error()) } diff --git a/chaoscenter/graphql/server/pkg/grpc/auth_grpc_client.go b/chaoscenter/graphql/server/pkg/grpc/auth_grpc_client.go index 96c9c73ee72..cea9b97324e 100644 --- a/chaoscenter/graphql/server/pkg/grpc/auth_grpc_client.go +++ b/chaoscenter/graphql/server/pkg/grpc/auth_grpc_client.go @@ -12,7 +12,7 @@ import ( ) // GetAuthGRPCSvcClient returns an RPC client for Authentication service -func GetAuthGRPCSvcClient(conn *grpc.ClientConn) (protos.AuthRpcServiceClient, *grpc.ClientConn) { +func GetAuthGRPCSvcClient() (protos.AuthRpcServiceClient, *grpc.ClientConn) { conn, err := grpc.Dial(utils.Config.LitmusAuthGrpcEndpoint+utils.Config.LitmusAuthGrpcPort, grpc.WithBlock(), grpc.WithInsecure()) if err != nil { logrus.Fatalf("did not connect: %s", err) diff --git a/chaoscenter/graphql/server/pkg/probe/handler/handler.go b/chaoscenter/graphql/server/pkg/probe/handler/handler.go index 680a1053e40..120a3738d02 100644 --- a/chaoscenter/graphql/server/pkg/probe/handler/handler.go +++ b/chaoscenter/graphql/server/pkg/probe/handler/handler.go @@ -237,7 +237,7 @@ func (p *probe) ListProbes(ctx context.Context, probeNames []string, infrastruct var pipeline mongo.Pipeline // Match the Probe Names from the input array - if probeNames != nil && len(probeNames) != 0 { + if len(probeNames) != 0 { matchProbeName := bson.D{ { Key: "$match", Value: bson.D{ diff --git a/chaoscenter/graphql/server/pkg/projects/project_handler.go b/chaoscenter/graphql/server/pkg/projects/project_handler.go index 900782583e0..f25ca019845 100644 --- a/chaoscenter/graphql/server/pkg/projects/project_handler.go +++ b/chaoscenter/graphql/server/pkg/projects/project_handler.go @@ -60,7 +60,7 @@ func ProjectEvents(projectEventChannel chan string, mongoClient *mongo.Client, m log.Error(err.Error()) } var conn *grpc2.ClientConn - client, conn := grpc.GetAuthGRPCSvcClient(conn) + client, conn := grpc.GetAuthGRPCSvcClient() defer conn.Close() for projectDetails.Next(context.Background()) { diff --git a/chaoscenter/subscriber/pkg/events/chaosengine.go b/chaoscenter/subscriber/pkg/events/chaosengine.go index d985ed857ae..a345b418c13 100644 --- a/chaoscenter/subscriber/pkg/events/chaosengine.go +++ b/chaoscenter/subscriber/pkg/events/chaosengine.go @@ -100,7 +100,7 @@ func (ev *subscriberEvents) chaosEventHandler(obj interface{}, eventType string, nodes := make(map[string]types.Node) logrus.Print("STANDALONE CHAOSENGINE EVENT ", workflowObj.UID, " ", eventType) - var cd *types.ChaosData = nil + var cd *types.ChaosData //extracts chaos data cd, err = ev.getChaosData(v1alpha1.NodeStatus{StartedAt: workflowObj.ObjectMeta.CreationTimestamp}, workflowObj.Name, workflowObj.Namespace, chaosClient) @@ -202,6 +202,9 @@ func (ev *subscriberEvents) StopChaosEngineState(namespace string, workflowRunID func (ev *subscriberEvents) StopWorkflow(wfName string, namespace string) error { conf, err := ev.subscriberK8s.GetKubeConfig() + if err != nil { + return fmt.Errorf("error in getting kube config: %w", err) + } wfClient := wfclientset.NewForConfigOrDie(conf).ArgoprojV1alpha1().Workflows(namespace) patch := []byte(`{"spec":{"shutdown":"Stop"}}`) wf, err := wfClient.Patch(context.TODO(), wfName, mergeType.MergePatchType, patch, v1.PatchOptions{}) diff --git a/chaoscenter/subscriber/pkg/events/util.go b/chaoscenter/subscriber/pkg/events/util.go index 996882c01fb..f7457d9e958 100644 --- a/chaoscenter/subscriber/pkg/events/util.go +++ b/chaoscenter/subscriber/pkg/events/util.go @@ -80,7 +80,6 @@ func (ev *subscriberEvents) getChaosData(nodeStatus v1alpha13.NodeStatus, engine // CheckChaosData util function, checks if event is a chaos-exp event, if so - extract the chaos data func (ev *subscriberEvents) CheckChaosData(nodeStatus v1alpha13.NodeStatus, workflowNS string, chaosClient *v1alpha12.LitmuschaosV1alpha1Client) (string, *types.ChaosData, error) { nodeType := string(nodeStatus.Type) - var cd *types.ChaosData = nil // considering chaos events has only 1 artifact with manifest as raw data data := nodeStatus.Inputs.Artifacts[0].Raw.Data obj := &unstructured.Unstructured{} @@ -100,6 +99,7 @@ func (ev *subscriberEvents) CheckChaosData(nodeStatus v1alpha13.NodeStatus, work return nodeType, nil, errors.New("Chaos-Engine Generated Name couldn't be retrieved") } } + var cd *types.ChaosData cd, err = ev.getChaosData(nodeStatus, name, obj.GetNamespace(), chaosClient) return nodeType, cd, err } diff --git a/chaoscenter/subscriber/pkg/requests/webhook.go b/chaoscenter/subscriber/pkg/requests/webhook.go index e0ee2f0e900..0851cecf3fa 100644 --- a/chaoscenter/subscriber/pkg/requests/webhook.go +++ b/chaoscenter/subscriber/pkg/requests/webhook.go @@ -98,7 +98,7 @@ func (req *subscriberRequests) AgentConnect(infraData map[string]string) { } func (req *subscriberRequests) RequestProcessor(infraData map[string]string, r types.RawData) error { - if strings.Index("kubeobject kubeobjects", strings.ToLower(r.Payload.Data.InfraConnect.Action.RequestType)) >= 0 { + if strings.Contains("kubeobject kubeobjects", strings.ToLower(r.Payload.Data.InfraConnect.Action.RequestType)) { KubeObjRequest := types.KubeObjRequest{ RequestID: r.Payload.Data.InfraConnect.Action.RequestID, } @@ -124,12 +124,12 @@ func (req *subscriberRequests) RequestProcessor(infraData map[string]string, r t logrus.Print("Log Request: ", r.Payload.Data.InfraConnect.Action.ExternalData) req.subscriberK8s.SendPodLogs(infraData, podRequest) - } else if strings.Index("create update delete get", strings.ToLower(r.Payload.Data.InfraConnect.Action.RequestType)) >= 0 { + } else if strings.Contains("create update delete get", strings.ToLower(r.Payload.Data.InfraConnect.Action.RequestType)) { _, err := req.subscriberK8s.AgentOperations(r.Payload.Data.InfraConnect.Action) if err != nil { return errors.New("error performing infra operation: " + err.Error()) } - } else if strings.Index("workflow_delete workflow_run_delete workflow_run_stop ", strings.ToLower(r.Payload.Data.InfraConnect.Action.RequestType)) >= 0 { + } else if strings.Contains("workflow_delete workflow_run_delete workflow_run_stop ", strings.ToLower(r.Payload.Data.InfraConnect.Action.RequestType)) { err := req.subscriberUtils.WorkflowRequest(infraData, r.Payload.Data.InfraConnect.Action.RequestType, r.Payload.Data.InfraConnect.Action.ExternalData, r.Payload.Data.InfraConnect.Action.Username) if err != nil {