Skip to content

Commit

Permalink
Add history list subcommand to CLI
Browse files Browse the repository at this point in the history
List the most recent entries in the evaluation history log, and allow
for filtering of the results.

Note that this does not support fetching results beyond the first page
at this time, or applying multiple values to the same filter. That is
left as future work.

Fixes #3814
  • Loading branch information
dmjb committed Jul 11, 2024
1 parent df6cf1c commit a189cb1
Show file tree
Hide file tree
Showing 8 changed files with 305 additions and 89 deletions.
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(), ",")))
}
133 changes: 133 additions & 0 deletions cmd/cli/app/history/history_list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// 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"
"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/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")
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"))
}

// list all the things
resp, err := client.ListEvaluationHistory(ctx, &minderv1.ListEvaluationHistoryRequest{
Context: &minderv1.Context{Project: &project},
EntityType: asFilter(entityType),
EntityName: asFilter(entityName),
ProfileName: asFilter(profileName),
Status: asFilter(evalStatus),
Remediation: asFilter(remediationStatus),
Alert: asFilter(alertStatus),
From: nil,
To: nil,
Cursor: nil,
})
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 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)
// 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", "", "Filter evaluation history list by entity type")
listCmd.Flags().String("evalStatus", "", "Filter evaluation history list by evaluation status")
listCmd.Flags().String("remediationStatus", "", "Filter evaluation history list by remediation status")
listCmd.Flags().String("alertStatus", "", "Filter evaluation history list by alert status")
}
Loading

0 comments on commit a189cb1

Please sign in to comment.