-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathcascading.go
More file actions
87 lines (70 loc) · 2.18 KB
/
cascading.go
File metadata and controls
87 lines (70 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// SPDX-FileCopyrightText: the secureCodeBox authors
//
// SPDX-License-Identifier: Apache-2.0
package cmd
import (
"fmt"
"github.com/ddddddO/gtree"
v1 "github.com/secureCodeBox/secureCodeBox/operator/apis/execution/v1"
"github.com/spf13/cobra"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func NewCascadeCommand() *cobra.Command {
cascadeCmd := &cobra.Command{
Use: "cascade",
Short: "Visualize cascading scans",
Long: `Visualize the relationships between scans based on their cascading relationships`,
RunE: func(cmd *cobra.Command, args []string) error {
kubeclient, namespace, err := clientProvider.GetClient(kubeconfigArgs)
if err != nil {
return fmt.Errorf("error initializing kubernetes client: %w", err)
}
if namespaceFlag, err := cmd.Flags().GetString("namespace"); err == nil && namespaceFlag != "" {
namespace = namespaceFlag
}
var scans v1.ScanList
if err := kubeclient.List(cmd.Context(), &scans, client.InNamespace(namespace)); err != nil {
return fmt.Errorf("error listing Scans: %w", err)
}
root := buildTree(scans.Items)
return gtree.OutputProgrammably(cmd.OutOrStdout(), root)
},
}
return cascadeCmd
}
const (
ParentScanAnnotation = "cascading.securecodebox.io/parent-scan"
)
func buildTree(scans []v1.Scan) *gtree.Node {
root := gtree.NewRoot("Scans")
uniq := make(map[string]struct{})
uniqScans := []*v1.Scan{}
for _, scan := range scans {
if _, ok := uniq[scan.Name]; ok {
continue
}
uniqScans = append(uniqScans, &scan)
uniq[scan.Name] = struct{}{}
}
for _, scan := range scans {
if isInitialScan(&scan) {
scanNode := root.Add(scan.Name)
buildScanSubtree(scanNode, &scan, uniqScans)
}
}
return root
}
func isInitialScan(scan *v1.Scan) bool {
return scan.Annotations[ParentScanAnnotation] == ""
}
func buildScanSubtree(node *gtree.Node, scan *v1.Scan, uniqScans []*v1.Scan) {
for _, childScan := range uniqScans {
if isCascadedFrom(childScan, scan) {
childNode := node.Add(childScan.Name)
buildScanSubtree(childNode, childScan, uniqScans)
}
}
}
func isCascadedFrom(childScan *v1.Scan, parentScan *v1.Scan) bool {
return childScan.Annotations[ParentScanAnnotation] == parentScan.Name
}