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

Add history list subcommand to CLI #3867

Merged
merged 3 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
111 changes: 111 additions & 0 deletions cmd/cli/app/common/table_render.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Copyright 2024 Stacklok, Inc.
//
// 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 common contains logic shared between multiple subcommands
package common

import (
"strings"

"github.com/stacklok/minder/internal/util/cli/table/layouts"
)

const (
successStatus = "success"
failureStatus = "failure"
errorStatus = "error"
skippedStatus = "skipped"
pendingStatus = "pending"
notAvailableStatus = "not_available"
onStatus = "on"
offStatus = "off"
)

// GetEvalStatusColor maps the alert status to coloured text
func GetEvalStatusColor(status string) layouts.ColoredColumn {
txt := getStatusText(status)
// eval statuses can be 'success', 'failure', 'error', 'skipped', 'pending'
switch strings.ToLower(status) {
case successStatus:
return layouts.GreenColumn(txt)
case failureStatus:
return layouts.RedColumn(txt)
case errorStatus:
return layouts.RedColumn(txt)
case skippedStatus:
return layouts.YellowColumn(txt)
default:
return layouts.NoColor(txt)
}
}

// GetRemediateStatusColor maps the alert status to coloured text
func GetRemediateStatusColor(status string) layouts.ColoredColumn {
txt := getStatusText(status)
// remediation statuses can be 'success', 'failure', 'error', 'skipped', 'not supported'
switch strings.ToLower(status) {
case successStatus:
return layouts.GreenColumn(txt)
case failureStatus:
return layouts.RedColumn(txt)
case errorStatus:
return layouts.RedColumn(txt)
case notAvailableStatus, skippedStatus:
return layouts.YellowColumn(txt)
default:
return layouts.NoColor(txt)
}
}

// GetAlertStatusColor maps the alert status to coloured text
func GetAlertStatusColor(status string) layouts.ColoredColumn {
txt := getStatusText(status)
// alert statuses can be 'on', 'off', 'error', 'skipped', 'not available'
switch strings.ToLower(status) {
case onStatus:
return layouts.GreenColumn(txt)
case offStatus:
return layouts.YellowColumn(txt)
case errorStatus:
return layouts.RedColumn(txt)
case notAvailableStatus, skippedStatus:
return layouts.YellowColumn(txt)
default:
return layouts.NoColor(txt)
}
}

func getStatusText(status string) string {
// remediation statuses can be 'success', 'failure', 'error', 'skipped', 'pending' or 'not supported'
switch strings.ToLower(status) {
case onStatus:
return "Success"
case offStatus:
return "Failure"
case successStatus:
return "Success"
case failureStatus:
return "Failure"
case errorStatus:
return "Error"
case skippedStatus:
return "Skipped" // visually empty as we didn't have to remediate
case pendingStatus:
return "Pending"
case notAvailableStatus:
return "Not Available"
default:
return "Unknown"
}
}
42 changes: 42 additions & 0 deletions cmd/cli/app/history/history.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2024 Stacklok, Inc.
//
// 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 history provides the CLI subcommand for managing profile statuses
package history

import (
"fmt"
"strings"

"github.com/spf13/cobra"

"github.com/stacklok/minder/cmd/cli/app"
)

// historyCmd is the root command for the profile_status subcommands
var historyCmd = &cobra.Command{
Use: "history",
Short: "View evaluation history",
Long: `The history subcommands allows evaluation history to be viewed.`,
RunE: func(cmd *cobra.Command, _ []string) error {
return cmd.Usage()
},
}

func init() {
app.RootCmd.AddCommand(historyCmd)
historyCmd.PersistentFlags().StringP("project", "j", "", "ID of the project")
historyCmd.PersistentFlags().StringP("output", "o", app.Table,
fmt.Sprintf("Output format (one of %s)", strings.Join(app.SupportedOutputFormats(), ",")))
}
209 changes: 209 additions & 0 deletions cmd/cli/app/history/history_list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
// Copyright 2024 Stacklok, Inc.
//
// 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 history

import (
"context"
"fmt"
"slices"
"strings"
"time"

"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/grpc"

"github.com/stacklok/minder/cmd/cli/app"
"github.com/stacklok/minder/cmd/cli/app/common"
"github.com/stacklok/minder/internal/db"
"github.com/stacklok/minder/internal/util"
"github.com/stacklok/minder/internal/util/cli"
"github.com/stacklok/minder/internal/util/cli/table"
"github.com/stacklok/minder/internal/util/cli/table/layouts"
minderv1 "github.com/stacklok/minder/pkg/api/protobuf/go/minder/v1"
)

var listCmd = &cobra.Command{
Use: "list",
Short: "List history",
Long: `The history list subcommand lets you list history within Minder.`,
RunE: cli.GRPCClientWrapRunE(listCommand),
}

// listCommand is the profile "list" subcommand
func listCommand(ctx context.Context, cmd *cobra.Command, _ []string, conn *grpc.ClientConn) error {
client := minderv1.NewEvalResultsServiceClient(conn)
//client := minderv1.NewProfileServiceClient(conn)

project := viper.GetString("project")
profileName := viper.GetString("profileName")
entityName := viper.GetString("entityName")
entityType := viper.GetString("entityType")
evalStatus := viper.GetString("evalStatus")
remediationStatus := viper.GetString("remediationStatus")
alertStatus := viper.GetString("alertStatus")
dmjb marked this conversation as resolved.
Show resolved Hide resolved
format := viper.GetString("output")

// Ensure the output format is supported
if !app.IsOutputFormatSupported(format) {
return cli.MessageAndError(fmt.Sprintf("Output format %s not supported", format), fmt.Errorf("invalid argument"))
}

// validate the filters which need validation
evalStatusFilter, err := valitedFilter(evalStatus, evalStatuses)
if err != nil {
return err
}

remediationStatusFilter, err := valitedFilter(remediationStatus, remediationStatuses)
if err != nil {
return err
}

alertStatusFilter, err := valitedFilter(alertStatus, alertStatuses)
if err != nil {
return err
}

entityTypeFilter, err := valitedFilter(entityType, entityTypes)
if err != nil {
return err
}

// list all the things
resp, err := client.ListEvaluationHistory(ctx, &minderv1.ListEvaluationHistoryRequest{
Context: &minderv1.Context{Project: &project},
EntityType: entityTypeFilter,
EntityName: asFilter(entityName),
ProfileName: asFilter(profileName),
Status: evalStatusFilter,
Remediation: remediationStatusFilter,
Alert: alertStatusFilter,
From: nil,
To: nil,
Cursor: nil,
blkt marked this conversation as resolved.
Show resolved Hide resolved
})
if err != nil {
return cli.MessageAndError("Error getting profile status", err)
}

switch format {
case app.JSON:
out, err := util.GetJsonFromProto(resp)
if err != nil {
return cli.MessageAndError("Error getting json from proto", err)
}
cmd.Println(out)
case app.YAML:
out, err := util.GetYamlFromProto(resp)
if err != nil {
return cli.MessageAndError("Error getting yaml from proto", err)
}
cmd.Println(out)
case app.Table:
historyTable := table.New(table.Simple, layouts.EvaluationHistory, nil)
renderRuleEvaluationStatusTable(resp.Data, historyTable)
historyTable.Render()
}

return nil
}

func asFilter(filter string) []string {
if filter == "" {
return nil
}
return []string{filter}
}

func valitedFilter(filter string, acceptedValues []string) ([]string, error) {
if filter == "" {
return nil, nil
}
// since the CLI uses capitalized statuses, lowercase to be safe
filter = strings.ToLower(filter)
if !slices.Contains(acceptedValues, filter) {
return nil, fmt.Errorf("unexpected filter value %s expected one of %s", filter, strings.Join(acceptedValues, ", "))
}
return []string{filter}, nil
}

func renderRuleEvaluationStatusTable(
statuses []*minderv1.EvaluationHistory,
t table.Table,
) {
for _, eval := range statuses {
t.AddRowWithColor(
layouts.NoColor(eval.EvaluatedAt.AsTime().Format(time.DateTime)),
layouts.NoColor(eval.Rule.Name),
layouts.NoColor(eval.Entity.Name),
common.GetEvalStatusColor(eval.Status.Status),
common.GetRemediateStatusColor(eval.Remediation.Status),
common.GetAlertStatusColor(eval.Alert.Status),
)
}
}

func init() {
historyCmd.AddCommand(listCmd)

basicMsg := "Filter evaluation history list by %s - one of %s"
evalFilterMsg := fmt.Sprintf(basicMsg, "evaluation status", strings.Join(evalStatuses, ", "))
remediationFilterMsg := fmt.Sprintf(basicMsg, "remediation status", strings.Join(remediationStatuses, ", "))
alertFilterMsg := fmt.Sprintf(basicMsg, "alert status", strings.Join(alertStatuses, ", "))
entityTypesMsg := fmt.Sprintf(basicMsg, "entity type", strings.Join(entityTypes, ", "))

// Flags
listCmd.Flags().String("ruleName", "", "Filter evaluation history list by rule name")
listCmd.Flags().String("profileName", "", "Filter evaluation history list by profile name")
listCmd.Flags().String("entityName", "", "Filter evaluation history list by entity name")
listCmd.Flags().String("entityType", "", entityTypesMsg)
listCmd.Flags().String("evalStatus", "", evalFilterMsg)
listCmd.Flags().String("remediationStatus", "", remediationFilterMsg)
listCmd.Flags().String("alertStatus", "", alertFilterMsg)
}

// TODO: we should have a common set of enums and validators in `internal`

var evalStatuses = []string{
string(db.EvalStatusTypesPending),
string(db.EvalStatusTypesFailure),
string(db.EvalStatusTypesError),
string(db.EvalStatusTypesSuccess),
string(db.EvalStatusTypesSkipped),
}

var remediationStatuses = []string{
string(db.RemediationStatusTypesFailure),
string(db.RemediationStatusTypesFailure),
string(db.RemediationStatusTypesError),
string(db.RemediationStatusTypesSuccess),
string(db.RemediationStatusTypesSkipped),
string(db.RemediationStatusTypesNotAvailable),
}

var alertStatuses = []string{
string(db.AlertStatusTypesOff),
string(db.AlertStatusTypesOn),
string(db.AlertStatusTypesError),
string(db.AlertStatusTypesSkipped),
string(db.AlertStatusTypesNotAvailable),
}

var entityTypes = []string{
string(db.EntitiesRepository),
string(db.EntitiesArtifact),
string(db.EntitiesPullRequest),
}
Loading