Skip to content

Commit

Permalink
add environment details flag
Browse files Browse the repository at this point in the history
Signed-off-by: Shivam Purohit <[email protected]>
  • Loading branch information
shivam-Purohit committed Mar 8, 2024
1 parent 1f421ed commit 50d7630
Show file tree
Hide file tree
Showing 8 changed files with 174 additions and 55 deletions.
44 changes: 43 additions & 1 deletion pkg/apis/environment/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func CreateEnvironment(pid string, request models.CreateEnvironmentRequest, cred
}
}

func GetEnvironmentList(pid string, cred types.Credentials) (ListEnvironmentData, error) {
func ListChaosEnvironments(pid string, cred types.Credentials) (ListEnvironmentData, error) {
var err error
var gqlReq CreateEnvironmentListGQLRequest
gqlReq.Query = ListEnvironmentQuery
Expand Down Expand Up @@ -93,6 +93,48 @@ func GetEnvironmentList(pid string, cred types.Credentials) (ListEnvironmentData
return ListEnvironmentData{}, err
}
}
func GetChaosEnvironment(pid string, envid string, cred types.Credentials) (GetEnvironmentData, error) {
var err error
var gqlReq CreateEnvironmentGetGQLRequest
gqlReq.Query = GetEnvironmentQuery

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

if resp.StatusCode == http.StatusOK {
var getEnvironment GetEnvironmentData
err = json.Unmarshal(bodyBytes, &getEnvironment)
if err != nil {
return GetEnvironmentData{}, errors.New("Error in Getting Chaos Environment: " + err.Error())
}
if len(getEnvironment.Errors) > 0 {
return GetEnvironmentData{}, errors.New(getEnvironment.Errors[0].Message)
}
return getEnvironment, nil
} else {
return GetEnvironmentData{}, err
}
}

func DeleteEnvironment(pid string, envid string, cred types.Credentials) (DeleteChaosEnvironmentData, error) {
var err error
Expand Down
18 changes: 18 additions & 0 deletions pkg/apis/environment/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,24 @@ const (
}
}
`
GetEnvironmentQuery = `query getEnvironment($projectID: ID!, $environmentID : ID!) {
getEnvironment(projectID: $projectID,environmentID: $environmentID){
environmentID
name
createdAt
updatedAt
createdBy{
username
}
updatedBy{
username
}
infraIDs
type
tags
}
}`

ListEnvironmentQuery = `query listEnvironments($projectID: ID!, $request: ListEnvironmentRequest) {
listEnvironments(projectID: $projectID,request: $request){
environments {
Expand Down
20 changes: 20 additions & 0 deletions pkg/apis/environment/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,26 @@ type CreateEnvironmentData struct {
EnvironmentDetails model.Environment `json:"createEnvironment"`
}

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

type GetEnvironment struct {
EnvironmentDetails model.Environment `json:"getEnvironment"`
}

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

type ListEnvironmentData struct {
Errors []struct {
Message string `json:"message"`
Expand Down
2 changes: 1 addition & 1 deletion pkg/cmd/connect/infra.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ var infraCmd = &cobra.Command{
infra_ops.PrintExistingInfra(infraList)
os.Exit(1)
}
envIDs, err := environment.GetEnvironmentList(newInfra.ProjectId, credentials)
envIDs, err := environment.ListChaosEnvironments(newInfra.ProjectId, credentials)
utils.PrintError(err)

// Check if Environment exists
Expand Down
2 changes: 1 addition & 1 deletion pkg/cmd/create/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ var environmentCmd = &cobra.Command{
}
newEnvironment.Type = models.EnvironmentType(envType)

envs, err := environment.GetEnvironmentList(pid, credentials)
envs, err := environment.ListChaosEnvironments(pid, credentials)
if err != nil {
utils.PrintError(err)
}
Expand Down
16 changes: 6 additions & 10 deletions pkg/cmd/delete/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Note: The default location of the config file is $HOME/.litmusconfig, and can be
os.Exit(1)
}

environmentList, err := environment.GetEnvironmentList(projectID, credentials)
environmentGet, err := environment.GetChaosEnvironment(projectID, environmentID, credentials)
if err != nil {
if strings.Contains(err.Error(), "permission_denied") {
utils.Red.Println("❌ You don't have enough permissions to delete an environment.")
Expand All @@ -112,15 +112,11 @@ Note: The default location of the config file is $HOME/.litmusconfig, and can be
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)
}
}
environmentGetData := environmentGet.Data.EnvironmentDetails
if len(environmentGetData.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
Expand Down
125 changes: 84 additions & 41 deletions pkg/cmd/get/environments.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ var GetChaosEnvironmentsCmd = &cobra.Command{
}
}

environmentList, err := environment.GetEnvironmentList(projectID, credentials)
environmentList, err := environment.ListChaosEnvironments(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.")
Expand All @@ -61,61 +61,104 @@ var GetChaosEnvironmentsCmd = &cobra.Command{
os.Exit(1)
}
}
environmentListData := environmentList.Data.ListEnvironmentDetails.Environments
environmentID, err := cmd.Flags().GetString("environment-id")
utils.PrintError(err)

itemsPerPage := 5
page := 1
totalEnvironments := len(environmentListData)
if environmentID == "" {
environmentListData := environmentList.Data.ListEnvironmentDetails.Environments

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 {
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()
utils.Red.Println("No more environments to display")
break
}
end := start + itemsPerPage
if end > totalEnvironments {
end = totalEnvironments
// 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++
}
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
} else {
environmentGet, err := environment.GetChaosEnvironment(projectID, environmentID, 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)
}
humanTime := time.Unix(intTime, 0)
utils.White.Fprintln(
writer,
environment.EnvironmentID+"\t"+environment.Name+"\t"+humanTime.String()+"\t"+environment.CreatedBy.Username,
)
}
environmentGetData := environmentGet.Data.EnvironmentDetails
writer := tabwriter.NewWriter(os.Stdout, 30, 8, 0, '\t', tabwriter.AlignRight)
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: "",
intUpdateTime, err := strconv.ParseInt(environmentGetData.UpdatedAt, 10, 64)
if err != nil {
utils.Red.Println("Error converting UpdatedAt to int64:", err)
}

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

if userInput == "q" {
break
updatedTime := time.Unix(intUpdateTime, 0).String()
intCreatedTime, err := strconv.ParseInt(environmentGetData.CreatedAt, 10, 64)
if err != nil {
utils.Red.Println("Error converting CreatedAt to int64:", err)
}
// Move to the next page
page++
createdTime := time.Unix(intCreatedTime, 0).String()
writer.Flush()
utils.White_B.Fprintln(writer, "CHAOS ENVIRONMENT DETAILS")
utils.White.Fprintln(writer, "CHAOS ENVIRONMENT ID\t", environmentGetData.EnvironmentID)
utils.White.Fprintln(writer, "CHAOS ENVIRONMENT NAME\t", environmentGetData.Name)
utils.White.Fprintln(writer, "CHAOS ENVIRONMENT Type\t", environmentGetData.Type)
utils.White.Fprintln(writer, "CREATED AT\t", createdTime)
utils.White.Fprintln(writer, "CREATED BY\t", environmentGetData.CreatedBy.Username)
utils.White.Fprintln(writer, "UPDATED AT\t", updatedTime)
utils.White.Fprintln(writer, "UPDATED BY\t", environmentGetData.UpdatedBy.Username)
utils.White.Fprintln(writer, "CHAOS INFRA IDs\t", strings.Join(environmentGetData.InfraIDs, ", "))
utils.White.Fprintln(writer, "TAGS\t", strings.Join(environmentGetData.Tags, ", "))
writer.Flush()
}

},
}

func init() {
GetCmd.AddCommand(GetChaosEnvironmentsCmd)
GetChaosEnvironmentsCmd.Flags().String("project-id", "", "Set the project-id to list Chaos Environments from a particular project.")
GetChaosEnvironmentsCmd.Flags().String("environment-id", "", "Set the environment-id to get details about a Chaos Environment.")
}
2 changes: 1 addition & 1 deletion pkg/infra_ops/ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ ENVIRONMENT:
}

// Check if Chaos Environment with the given name exists
Env, err := environment.GetEnvironmentList(pid, c)
Env, err := environment.ListChaosEnvironments(pid, c)
if err != nil {
return types.Infra{}, err
}
Expand Down

0 comments on commit 50d7630

Please sign in to comment.