Skip to content

Commit

Permalink
refectoring: refectoring code
Browse files Browse the repository at this point in the history
- 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 <yj.yoo@okestro.com>
  • Loading branch information
yj-yoo committed Apr 17, 2024
1 parent 53b9161 commit c1f63af
Show file tree
Hide file tree
Showing 13 changed files with 24 additions and 21 deletions.
4 changes: 3 additions & 1 deletion chaoscenter/authentication/pkg/utils/mongo_database.go
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion chaoscenter/graphql/server/pkg/authorization/validate.go
Expand Up @@ -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,
Expand Down
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions chaoscenter/graphql/server/pkg/chaoshub/handler/types.go
Expand Up @@ -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 {
Expand All @@ -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"`
Expand Down
2 changes: 1 addition & 1 deletion chaoscenter/graphql/server/pkg/chaoshub/service.go
Expand Up @@ -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 {
Expand Down
Expand Up @@ -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},
}
Expand Down
4 changes: 2 additions & 2 deletions chaoscenter/graphql/server/pkg/gitops/service.go
Expand Up @@ -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)
Expand Down Expand Up @@ -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())
}
Expand Down
2 changes: 1 addition & 1 deletion chaoscenter/graphql/server/pkg/grpc/auth_grpc_client.go
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion chaoscenter/graphql/server/pkg/probe/handler/handler.go
Expand Up @@ -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{
Expand Down
2 changes: 1 addition & 1 deletion chaoscenter/graphql/server/pkg/projects/project_handler.go
Expand Up @@ -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()) {
Expand Down
5 changes: 4 additions & 1 deletion chaoscenter/subscriber/pkg/events/chaosengine.go
Expand Up @@ -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)
Expand Down Expand Up @@ -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{})
Expand Down
2 changes: 1 addition & 1 deletion chaoscenter/subscriber/pkg/events/util.go
Expand Up @@ -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{}
Expand All @@ -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
}
Expand Down
6 changes: 3 additions & 3 deletions chaoscenter/subscriber/pkg/requests/webhook.go
Expand Up @@ -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,
}
Expand All @@ -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 {
Expand Down

0 comments on commit c1f63af

Please sign in to comment.