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

feat:delete environment command #189

Merged
merged 8 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
14 changes: 14 additions & 0 deletions Usage_0.23.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,20 @@ Enter the Environment Name: test2
🚀 New Chaos Environment creation successful!! 🎉
```

- To delete an Environment, apply the following command :

```shell
litmusctl delete chaos-environment

Enter the Project ID: eb7fc0a0-5878-4454-a9db-b67d283713bc

Enter the Environment ID: testenv

Are you sure you want to delete this Chaos Environment? (y/n):y

🚀 Chaos Environment deleted successfully.
```

- To view all the projects with the user, use the `get projects` command.

```shell
Expand Down
46 changes: 46 additions & 0 deletions pkg/apis/environment/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,49 @@ func GetEnvironmentList(pid string, cred types.Credentials) (ListEnvironmentData
return ListEnvironmentData{}, err
}
}

func DeleteEnvironment(pid string, envid string, cred types.Credentials) (DeleteChaosEnvironmentData, error) {
var err error
var gqlReq CreateEnvironmentDeleteGQLRequest
gqlReq.Query = DeleteEnvironmentQuery

gqlReq.Variables.EnvironmentID = envid
gqlReq.Variables.ProjectID = pid
query, err := json.Marshal(gqlReq)
if err != nil {
return DeleteChaosEnvironmentData{}, err
}
resp, err := apis.SendRequest(
apis.SendRequestParams{
Endpoint: cred.ServerEndpoint + utils.GQLAPIPath,
Token: cred.Token,
},
query,
string(types.Post),
)
if err != nil {
return DeleteChaosEnvironmentData{}, errors.New("Error in Deleting Chaos Environment: " + err.Error())
}

bodyBytes, err := io.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return DeleteChaosEnvironmentData{}, errors.New("Error in Deleting Chaos Environment: " + err.Error())
}

if resp.StatusCode == http.StatusOK {
var deletedEnvironment DeleteChaosEnvironmentData
err = json.Unmarshal(bodyBytes, &deletedEnvironment)
if err != nil {
return DeleteChaosEnvironmentData{}, err
}

if len(deletedEnvironment.Errors) > 0 {
return DeleteChaosEnvironmentData{}, errors.New(deletedEnvironment.Errors[0].Message)
}

return deletedEnvironment, nil
} else {
return DeleteChaosEnvironmentData{}, errors.New("Error while deleting the Chaos Environment")
}
}
7 changes: 7 additions & 0 deletions pkg/apis/environment/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,11 @@ const (
}
}
}`

DeleteEnvironmentQuery = `mutation deleteEnvironment($projectID: ID!, $environmentID: ID!) {
deleteEnvironment(
projectID: $projectID
environmentID: $environmentID
)
}`
)
20 changes: 20 additions & 0 deletions pkg/apis/environment/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,23 @@ type CreateEnvironmentListGQLRequest struct {
Request model.ListEnvironmentRequest `json:"request"`
}
}

type CreateEnvironmentDeleteGQLRequest struct {
Query string `json:"query"`
Variables struct {
ProjectID string `json:"projectID"`
EnvironmentID string `json:"environmentID"`
}
}

type DeleteChaosEnvironmentData struct {
Errors []struct {
Message string `json:"message"`
Path []string `json:"path"`
} `json:"errors"`
Data DeleteChaosEnvironmentDetails `json:"data"`
}

type DeleteChaosEnvironmentDetails struct {
DeleteChaosEnvironment string `json:"deleteChaosExperiment"`
}
3 changes: 3 additions & 0 deletions pkg/cmd/delete/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ var DeleteCmd = &cobra.Command{
#delete a Chaos Experiment
litmusctl delete chaos-experiment c520650e-7cb6-474c-b0f0-4df07b2b025b --project-id=c520650e-7cb6-474c-b0f0-4df07b2b025b

#delete a Chaos Environment
litmusctl delete chaos-environment --project-id=8adf62d5-64f8-4c66-ab53-63729db9dd9a --environment-id=environmentexample

Note: The default location of the config file is $HOME/.litmusconfig, and can be overridden by a --config flag
`,
}
160 changes: 160 additions & 0 deletions pkg/cmd/delete/environment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
Copyright © 2021 The LitmusChaos Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package delete

import (
"os"

"github.com/litmuschaos/litmusctl/pkg/apis/environment"

"github.com/litmuschaos/litmusctl/pkg/apis"
"github.com/litmuschaos/litmusctl/pkg/utils"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"strings"
)

// experimentCmd represents the Chaos Experiment command
var environmentCmd = &cobra.Command{
Use: "chaos-environment",
Short: `Delete a Chaos environment
Example:
#delete a Chaos Environment
litmusctl delete chaos-environment --project-id=8adf62d5-64f8-4c66-ab53-63729db9dd9a --environment-id=environmentexample

Note: The default location of the config file is $HOME/.litmusconfig, and can be overridden by a --config flag
`,

Run: func(cmd *cobra.Command, args []string) {

// Fetch user credentials
credentials, err := utils.GetCredentials(cmd)
utils.PrintError(err)

projectID, err := cmd.Flags().GetString("project-id")
utils.PrintError(err)

environmentID, err := cmd.Flags().GetString("environment-id")
utils.PrintError(err)

// Handle blank input for project ID

if projectID == "" {
prompt := promptui.Prompt{
Label: "Enter the Project ID",
}
result, err := prompt.Run()
if err != nil {
utils.Red.Println("⛔ Error:", err)
os.Exit(1)
}
projectID = result
}

if environmentID == "" {
prompt := promptui.Prompt{
Label: "Enter the Environment ID",
}
result, err := prompt.Run()
if err != nil {
utils.Red.Println("⛔ Error:", err)
os.Exit(1)
}
environmentID = result
}

// Handle blank input for Chaos Environment ID
if environmentID == "" {
utils.Red.Println("⛔ Chaos Environment ID can't be empty!!")
os.Exit(1)
}

// Perform authorization
userDetails, err := apis.GetProjectDetails(credentials)
utils.PrintError(err)
var editAccess = false
var project apis.Project
for _, p := range userDetails.Data.Projects {
if p.ID == projectID {
project = p
}
}
for _, member := range project.Members {
if (member.UserID == userDetails.Data.ID) && (member.Role == "Owner" || member.Role == "Editor") {
editAccess = true
}
}
if !editAccess {
utils.Red.Println("⛔ User doesn't have edit access to the project!!")
os.Exit(1)
}

environmentList, err := environment.GetEnvironmentList(projectID, credentials)
if err != nil {
if strings.Contains(err.Error(), "permission_denied") {
utils.Red.Println("❌ You don't have enough permissions to delete an environment.")
os.Exit(1)
} else {
utils.PrintError(err)
os.Exit(1)
}
}
environmentListData := environmentList.Data.ListEnvironmentDetails.Environments
for i := 0; i < len(environmentListData); i++ {
if environmentListData[i].EnvironmentID == environmentID {
if len(environmentListData[i].InfraIDs) > 0 {
SarthakJain26 marked this conversation as resolved.
Show resolved Hide resolved
utils.Red.Println("Chaos Infras present in the Chaos Environment" +
"delete the Chaos Infras first to delete the Environment")
os.Exit(1)
}
}
}

// confirm before deletion
prompt := promptui.Prompt{
Label: "Are you sure you want to delete this Chaos Environment? (y/n)",
AllowEdit: true,
}

result, err := prompt.Run()
if err != nil {
utils.Red.Println("⛔ Error:", err)
os.Exit(1)
}

if result != "y" {
utils.White_B.Println("\n❌ Chaos Environment was not deleted.")
os.Exit(0)
}

// Make API call
_, err = environment.DeleteEnvironment(projectID, environmentID, credentials)
if err != nil {
utils.Red.Println("\n❌ Error in deleting Chaos Environment: ", err.Error())
os.Exit(1)
}

utils.White_B.Println("\n🚀 Chaos Environment successfully deleted.")

},
}

func init() {
DeleteCmd.AddCommand(environmentCmd)

environmentCmd.Flags().String("project-id", "", "Set the project-id to delete Chaos Environment for the particular project. To see the projects, apply litmusctl get projects")
environmentCmd.Flags().String("environment-id", "", "Set the environment-id to delete the particular Chaos Environment.")
}
Loading