Skip to content

Commit

Permalink
feat:delete environment command (litmuschaos#189)
Browse files Browse the repository at this point in the history
* Feat:delete environment command

Signed-off-by: Shivam Purohit <[email protected]>

* add check for chaos-infras

Signed-off-by: Shivam Purohit <[email protected]>

* fix:fmt

Signed-off-by: Shivam Purohit <[email protected]>

* modify the description messages

Signed-off-by: Shivam Purohit <[email protected]>

* Add command example for delete environment

Signed-off-by: Shivam Purohit <[email protected]>

* Add new command usage in docs

Signed-off-by: Shivam Purohit <[email protected]>

* change example for delete environment

Signed-off-by: Shivam Purohit <[email protected]>

* update: Usage_0.23.0.md

Signed-off-by: Shivam Purohit <[email protected]>

---------

Signed-off-by: Shivam Purohit <[email protected]>
  • Loading branch information
shivam-Purohit authored Feb 23, 2024
1 parent 05634fb commit 9fe2a37
Show file tree
Hide file tree
Showing 6 changed files with 250 additions and 0 deletions.
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 {
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.")
}

0 comments on commit 9fe2a37

Please sign in to comment.