Skip to content

Commit

Permalink
Get chaos environments command (#170)
Browse files Browse the repository at this point in the history
* add get/list env commands to docs

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

* modify print for error message

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

* fix:fmt error

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

---------

Signed-off-by: Shivam Purohit <[email protected]>
  • Loading branch information
shivam-Purohit authored Jan 15, 2024
1 parent 486349b commit cf8c33a
Show file tree
Hide file tree
Showing 9 changed files with 338 additions and 14 deletions.
54 changes: 54 additions & 0 deletions Usage_0.23.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,60 @@ Are you sure you want to delete this Chaos Experiment? (y/n): y
🚀 Chaos Experiment successfully deleted.
```

- To get the Chaos Environment, issue the following command.

Using Flag :

```shell
litmusctl get chaos-environment --project-id="" --environment-id=""
```

Using UI :

```shell
litmusctl get chaos-environment
Enter the Project ID: "project-id"
Enter the Environment ID: "chaos-experiment-id"
```

**Output:**

```
CHAOS ENVIRONMENT ID shivamenv
CHAOS ENVIRONMENT NAME shivamenv
CHAOS ENVIRONMENT Type NON_PROD
CREATED AT 55908-04-03 16:42:51 +0530 IST
CREATED BY admin
UPDATED AT 55908-04-03 16:42:51 +0530 IST
UPDATED BY admin
CHAOS INFRA IDs d99c7d14-56ef-4836-8537-423f28ceac4e
```

- To list the Chaos Environments, issue the following command.

Using Flag :

```shell
litmusctl list chaos-environments --project-id=""
```

Using UI :

```shell
litmusctl list chaos-environment
Enter the Project ID: "project-id"
```

**Output:**

```
CHAOS ENVIRONMENT ID CHAOS ENVIRONMENT NAME CREATED AT CREATED BY
testenv testenv 55985-01-15 01:42:33 +0530 IST admin
shivamnewenv shivamnewenv 55962-10-01 15:05:45 +0530 IST admin
newenvironmenttest newenvironmenttest 55912-12-01 10:55:23 +0530 IST admin
shivamenv shivamenv 55908-04-03 16:42:51 +0530 IST admin
```
---

## Flag details
Expand Down
4 changes: 1 addition & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ require (
github.com/mitchellh/go-homedir v1.1.0
github.com/spf13/cobra v1.3.0
github.com/spf13/viper v1.10.1
golang.org/x/term v0.13.0
gopkg.in/yaml.v2 v2.4.0
k8s.io/api v0.23.3
k8s.io/apimachinery v0.23.3
Expand Down Expand Up @@ -68,9 +67,8 @@ require (
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/term v0.5.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/term v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 // indirect
google.golang.org/appengine v1.6.7 // indirect
Expand Down
8 changes: 2 additions & 6 deletions pkg/apis/environment/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ package environment
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"

models "github.com/litmuschaos/litmus/chaoscenter/graphql/server/graph/model"
"github.com/litmuschaos/litmusctl/pkg/apis"
"github.com/litmuschaos/litmusctl/pkg/types"
"github.com/litmuschaos/litmusctl/pkg/utils"
"io/ioutil"
"net/http"
)

// CreateEnvironment connects the Infra with the given details
Expand Down Expand Up @@ -58,7 +57,6 @@ func GetEnvironmentList(pid string, cred types.Credentials) (ListEnvironmentData
if err != nil {
return ListEnvironmentData{}, err
}

resp, err := apis.SendRequest(
apis.SendRequestParams{
Endpoint: cred.ServerEndpoint + utils.GQLAPIPath,
Expand All @@ -67,11 +65,9 @@ func GetEnvironmentList(pid string, cred types.Credentials) (ListEnvironmentData
query,
string(types.Post),
)

if err != nil {
return ListEnvironmentData{}, errors.New("Error in Getting Chaos Environment List: " + err.Error())
}

bodyBytes, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
Expand Down
11 changes: 11 additions & 0 deletions pkg/apis/environment/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ const (
listEnvironments(projectID: $projectID,request: $request){
environments {
environmentID
name
createdAt
updatedAt
createdBy{
username
}
updatedBy{
username
}
infraIDs
type
}
}
}`
Expand Down
114 changes: 114 additions & 0 deletions pkg/cmd/get/environment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
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 get

import (
"fmt"
"github.com/litmuschaos/litmusctl/pkg/apis/environment"
"github.com/litmuschaos/litmusctl/pkg/utils"
"github.com/spf13/cobra"
"os"
"strconv"
"strings"
"text/tabwriter"
"time"
)

var ChaosEnvironmentCmd = &cobra.Command{
Use: "chaos-environment",
Short: "Get Chaos Environment within the project",
Long: `Display the Chaos Environments within the project with the targeted id `,
Run: func(cmd *cobra.Command, args []string) {
credentials, err := utils.GetCredentials(cmd)
utils.PrintError(err)

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

if projectID == "" {
utils.White_B.Print("\nEnter the Project ID: ")
fmt.Scanln(&projectID)

if projectID == "" {
utils.Red.Println("⛔ Project ID can't be empty!!")
os.Exit(1)
}
}

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

if environmentID == "" {
utils.White_B.Print("\nEnter the Environment ID: ")
fmt.Scanln(&environmentID)

if environmentID == "" {
utils.Red.Println("⛔ Environment ID can't be empty!!")
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 access this resource.")
os.Exit(1)
} else {
utils.PrintError(err)
os.Exit(1)
}
}
environmentListData := environmentList.Data.ListEnvironmentDetails.Environments
writer := tabwriter.NewWriter(os.Stdout, 30, 8, 0, '\t', tabwriter.AlignRight)
writer.Flush()
for i := 0; i < len(environmentListData); i++ {
if environmentListData[i].EnvironmentID == environmentID {
intUpdateTime, err := strconv.ParseInt(environmentListData[i].UpdatedAt, 10, 64)
if err != nil {
utils.Red.Println("Error converting UpdatedAt to int64:", err)
continue
}
updatedTime := time.Unix(intUpdateTime, 0).String()
intCreatedTime, err := strconv.ParseInt(environmentListData[i].CreatedAt, 10, 64)
if err != nil {
utils.Red.Println("Error converting CreatedAt to int64:", err)
continue
}
createdTime := time.Unix(intCreatedTime, 0).String()
writer.Flush()
utils.White_B.Fprintln(writer, "CHAOS ENVIRONMENT DETAILS")
utils.White.Fprintln(writer, "CHAOS ENVIRONMENT ID\t", environmentListData[i].EnvironmentID)
utils.White.Fprintln(writer, "CHAOS ENVIRONMENT NAME\t", environmentListData[i].Name)
utils.White.Fprintln(writer, "CHAOS ENVIRONMENT Type\t", environmentListData[i].Type)
utils.White.Fprintln(writer, "CREATED AT\t", createdTime)
utils.White.Fprintln(writer, "CREATED BY\t", environmentListData[i].CreatedBy.Username)
utils.White.Fprintln(writer, "UPDATED AT\t", updatedTime)
utils.White.Fprintln(writer, "UPDATED BY\t", environmentListData[i].UpdatedBy.Username)
utils.White.Fprintln(writer, "CHAOS INFRA IDs\t", strings.Join(environmentListData[i].InfraIDs, ", "))
break
}
}
writer.Flush()

},
}

func init() {
GetCmd.AddCommand(ChaosEnvironmentCmd)
ChaosEnvironmentCmd.Flags().String("project-id", "", "Set the project-id to get Chaos Environment from a particular project.")
ChaosEnvironmentCmd.Flags().String("environment-id", "", "Set the environment-id to get Chaos Environment")
}
8 changes: 3 additions & 5 deletions pkg/cmd/get/projects.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@ limitations under the License.
package get

import (
"os"
"text/tabwriter"
"time"

"github.com/litmuschaos/litmusctl/pkg/apis"
"github.com/litmuschaos/litmusctl/pkg/utils"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"os"
"text/tabwriter"
"time"
)

// projectCmd represents the project command
Expand All @@ -49,7 +48,6 @@ var projectsCmd = &cobra.Command{
utils.PrintInYamlFormat(projects.Data)

case "":

itemsPerPage := 5
page := 1
totalProjects := len(projects.Data)
Expand Down
120 changes: 120 additions & 0 deletions pkg/cmd/list/environment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
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 list

import (
"fmt"
"github.com/litmuschaos/litmusctl/pkg/apis/environment"
"github.com/litmuschaos/litmusctl/pkg/utils"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"os"
"strconv"
"strings"
"text/tabwriter"
"time"
)

var ListChaosEnvironmentCmd = &cobra.Command{
Use: "chaos-environments",
Short: "Get Chaos Environments within the project",
Long: `Display the Chaos Environments within the project with the targeted id `,
Run: func(cmd *cobra.Command, args []string) {
credentials, err := utils.GetCredentials(cmd)
utils.PrintError(err)

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

if projectID == "" {
utils.White_B.Print("\nEnter the Project ID: ")
fmt.Scanln(&projectID)

for projectID == "" {
utils.Red.Println("⛔ Project ID can't be empty!!")
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 access this resource.")
os.Exit(1)
} else {
utils.PrintError(err)
os.Exit(1)
}
}
environmentListData := environmentList.Data.ListEnvironmentDetails.Environments

itemsPerPage := 5
page := 1
totalEnvironments := len(environmentListData)

writer := tabwriter.NewWriter(os.Stdout, 30, 8, 0, '\t', tabwriter.AlignRight)
utils.White_B.Fprintln(writer, "CHAOS ENVIRONMENT ID\tCHAOS ENVIRONMENT NAME\tCREATED AT\tCREATED BY")
for {
writer.Flush()
// calculating the start and end indices for the current page
start := (page - 1) * itemsPerPage
if start >= totalEnvironments {
writer.Flush()
utils.Red.Println("No more environments to display")
break
}
end := start + itemsPerPage
if end > totalEnvironments {
end = totalEnvironments

}
for _, environment := range environmentListData[start:end] {
intTime, err := strconv.ParseInt(environment.CreatedAt, 10, 64)
if err != nil {
fmt.Println("Error converting CreatedAt to int64:", err)
continue
}
humanTime := time.Unix(intTime, 0)
utils.White.Fprintln(
writer,
environment.EnvironmentID+"\t"+environment.Name+"\t"+humanTime.String()+"\t"+environment.CreatedBy.Username,
)
}
writer.Flush()
// Check if it's the last item or if user wants to see more
paginationPrompt := promptui.Prompt{
Label: "Press Enter to show more environments (or type 'q' to quit)",
AllowEdit: true,
Default: "",
}

userInput, err := paginationPrompt.Run()
utils.PrintError(err)

if userInput == "q" {
break
}
// Move to the next page
page++
}
},
}

func init() {
ListCmd.AddCommand(ListChaosEnvironmentCmd)
ListChaosEnvironmentCmd.Flags().String("project-id", "", "Set the project-id to list Chaos Environments from a particular project.")
}
Loading

0 comments on commit cf8c33a

Please sign in to comment.