Skip to content

Commit 0a65eaf

Browse files
authored
Merge pull request #290 from intelops/kubescore
Kubescore
2 parents 126ab4e + 304f29b commit 0a65eaf

File tree

8 files changed

+70
-30
lines changed

8 files changed

+70
-30
lines changed

agent/kubviz/k8smetrics_agent.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ func main() {
127127
LogErr(err)
128128
err = RakeesOutput(config, js)
129129
LogErr(err)
130-
//getK8sEvents(clientset)
130+
// //getK8sEvents(clientset)
131131
err = runTrivyScans(config, js)
132132
LogErr(err)
133133
err = RunKubeScore(clientset, js)

agent/kubviz/kube_score.go

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"github.com/intelops/kubviz/constants"
1111
"github.com/intelops/kubviz/model"
1212
"github.com/nats-io/nats.go"
13+
"github.com/zegl/kube-score/renderer/json_v2"
1314
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1415
"k8s.io/client-go/kubernetes"
1516
)
@@ -32,34 +33,42 @@ func RunKubeScore(clientset *kubernetes.Clientset, js nats.JetStreamContext) err
3233
}
3334

3435
func publish(ns string, js nats.JetStreamContext) error {
35-
cmd := "kubectl api-resources --verbs=list --namespaced -o name | xargs -n1 -I{} sh -c \"kubectl get {} -n " + ns + " -oyaml && echo ---\" | kube-score score - "
36+
var report []json_v2.ScoredObject
37+
cmd := "kubectl api-resources --verbs=list --namespaced -o name | xargs -n1 -I{} sh -c \"kubectl get {} -n " + ns + " -oyaml && echo ---\" | kube-score score - -o json"
3638
log.Printf("Command: %#v,", cmd)
3739
out, err := executeCommand(cmd)
3840
if err != nil {
3941
log.Println("Error occurred while running kube-score: ", err)
4042
return err
4143
}
42-
err = publishKubescoreMetrics(uuid.New().String(), ns, out, js)
44+
// // Continue with the rest of the code...
45+
err = json.Unmarshal([]byte(out), &report)
46+
if err != nil {
47+
log.Printf("Error occurred while Unmarshalling json: %v", err)
48+
return err
49+
}
50+
51+
publishKubescoreMetrics(report, js)
52+
//err = publishKubescoreMetrics(uuid.New().String(), ns, out, js)
4353
if err != nil {
4454
return err
4555
}
4656
return nil
4757
}
4858

49-
func publishKubescoreMetrics(id string, ns string, recommendations string, js nats.JetStreamContext) error {
59+
func publishKubescoreMetrics(report []json_v2.ScoredObject, js nats.JetStreamContext) error {
5060
metrics := model.KubeScoreRecommendations{
51-
ID: id,
52-
Namespace: ns,
53-
Recommendations: recommendations,
54-
ClusterName: ClusterName,
61+
ID: uuid.New().String(),
62+
ClusterName: ClusterName,
63+
Report: report,
5564
}
5665
metricsJson, _ := json.Marshal(metrics)
5766
_, err := js.Publish(constants.KUBESCORE_SUBJECT, metricsJson)
5867
if err != nil {
5968
return err
6069
}
61-
log.Printf("Recommendations with ID:%s has been published\n", id)
62-
log.Printf("Recommendations :%#v", recommendations)
70+
//log.Printf("Recommendations with ID:%s has been published\n", id)
71+
log.Printf("Recommendations :%#v", report)
6372
return nil
6473
}
6574

client/pkg/clickhouse/db_client.go

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,7 @@ func (c *DBClient) InsertKubeScoreMetrics(metrics model.KubeScoreRecommendations
523523
if err != nil {
524524
log.Fatalf("error beginning transaction, clickhouse connection not available: %v", err)
525525
}
526+
defer tx.Rollback()
526527
stmt, err := tx.Prepare(InsertKubeScore)
527528
if err != nil {
528529
log.Fatalf("error preparing statement: %v", err)
@@ -531,14 +532,31 @@ func (c *DBClient) InsertKubeScoreMetrics(metrics model.KubeScoreRecommendations
531532

532533
currentTime := time.Now().UTC()
533534

534-
if _, err := stmt.Exec(
535-
metrics.ID,
536-
metrics.Namespace,
537-
metrics.ClusterName,
538-
metrics.Recommendations,
539-
currentTime,
540-
); err != nil {
541-
log.Fatal(err)
535+
for _, result := range metrics.Report {
536+
for _, check := range result.Checks {
537+
for _, comments := range check.Comments {
538+
539+
if _, err := stmt.Exec(
540+
metrics.ID,
541+
metrics.ClusterName,
542+
result.ObjectName,
543+
result.TypeMeta.Kind,
544+
result.TypeMeta.APIVersion,
545+
result.ObjectMeta.Name,
546+
result.ObjectMeta.Namespace,
547+
check.Check.TargetType,
548+
comments.Description,
549+
comments.Path,
550+
comments.Summary,
551+
result.FileName,
552+
int64(result.FileRow),
553+
currentTime,
554+
); err != nil {
555+
log.Println("Error while inserting KubeScore metrics:", err)
556+
}
557+
}
558+
559+
}
542560
}
543561
if err := tx.Commit(); err != nil {
544562
log.Fatal(err)

client/pkg/clickhouse/statements.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,7 @@ const InsertDeletedApi DBStatement = "INSERT INTO DeletedAPIs (ClusterName, Obje
237237
const InsertKubvizEvent DBStatement = "INSERT INTO events (ClusterName, Id, EventTime, OpType, Name, Namespace, Kind, Message, Reason, Host, Event, FirstTime, LastTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
238238
const clickhouseExperimental DBStatement = `SET allow_experimental_object_type=1;`
239239
const containerGithubTable DBStatement = `CREATE table IF NOT EXISTS container_github(event JSON) ENGINE = MergeTree ORDER BY tuple();`
240-
const InsertKubeScore string = "INSERT INTO kubescore (id, namespace, cluster_name, recommendations, EventTime) VALUES (?, ?, ?, ?, ?)"
240+
const InsertKubeScore string = "INSERT INTO kubescore(id,clustername,object_name,kind,apiVersion,name,namespace,target_type,description,path,summary,file_name,file_row,EventTime) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
241241
const InsertTrivyVul string = "INSERT INTO trivy_vul (id, cluster_name, namespace, kind, name, vul_id, vul_vendor_ids, vul_pkg_id, vul_pkg_name, vul_pkg_path, vul_installed_version, vul_fixed_version, vul_title, vul_severity, vul_published_date, vul_last_modified_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?. ?)"
242242
const InsertTrivyImage string = "INSERT INTO trivyimage (id, cluster_name, artifact_name, vul_id, vul_pkg_id, vul_pkg_name, vul_installed_version, vul_fixed_version, vul_title, vul_severity, vul_published_date, vul_last_modified_date) VALUES ( ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
243243
const InsertTrivyMisconfig string = "INSERT INTO trivy_misconfig (id, cluster_name, namespace, kind, name, misconfig_id, misconfig_avdid, misconfig_type, misconfig_title, misconfig_desc, misconfig_msg, misconfig_query, misconfig_resolution, misconfig_severity, misconfig_status, EventTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

go.mod

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ require (
2424
github.com/robfig/cron/v3 v3.0.1
2525
github.com/sirupsen/logrus v1.9.3
2626
github.com/spf13/cobra v1.7.0
27+
github.com/zegl/kube-score v1.17.0
2728
golang.org/x/term v0.11.0
2829
k8s.io/api v0.27.3
2930
k8s.io/apimachinery v0.27.3
@@ -53,7 +54,7 @@ require (
5354
github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 // indirect
5455
github.com/emicklei/go-restful/v3 v3.10.1 // indirect
5556
github.com/evanphx/json-patch v5.6.0+incompatible // indirect
56-
github.com/fatih/color v1.14.1 // indirect
57+
github.com/fatih/color v1.15.0 // indirect
5758
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
5859
github.com/gin-contrib/sse v0.1.0 // indirect
5960
github.com/go-errors/errors v1.4.2 // indirect

go.sum

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,8 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7
124124
github.com/evanphx/json-patch v5.6.0+incompatible h1:jBYDEEiFBPxA0v50tFdvOzQQTCvpL6mnFh5mB2/l16U=
125125
github.com/evanphx/json-patch v5.6.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
126126
github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d h1:105gxyaGwCFad8crR9dcMQWvV9Hvulu6hwUh4tWPJnM=
127-
github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w=
128-
github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg=
127+
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
128+
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
129129
github.com/fernet/fernet-go v0.0.0-20180830025343-9eac43b88a5e/go.mod h1:2H9hjfbpSMHwY503FclkV/lZTBh2YlOmLLSda12uL8c=
130130
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
131131
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
@@ -472,6 +472,8 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
472472
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
473473
github.com/zclconf/go-cty v1.10.0 h1:mp9ZXQeIcN8kAwuqorjH+Q+njbJKjLrvB2yIh4q7U+0=
474474
github.com/zclconf/go-cty-yaml v1.0.2 h1:dNyg4QLTrv2IfJpm7Wtxi55ed5gLGOlPrZ6kMd51hY0=
475+
github.com/zegl/kube-score v1.17.0 h1:vedzK0pm5yOb1ocm5gybMNYsJRG8iTAatbo3LFIWbUc=
476+
github.com/zegl/kube-score v1.17.0/go.mod h1:0pt4Lt36uTKPiCQbXQFow29eaAbgMLI9RoESjBoGSq0=
475477
go.etcd.io/bbolt v1.3.7 h1:j+zJOnnEjF/kyHlDDgGnVL/AIqIJPq8UoB2GSNfkUfQ=
476478
go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
477479
go.mongodb.org/mongo-driver v1.11.1/go.mod h1:s7p5vEtfbeR1gYi6pnj3c3/urpbLv2T5Sfd6Rp2HBB8=

model/kubescore.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
package model
22

3+
import "github.com/zegl/kube-score/renderer/json_v2"
4+
35
type KubeScoreRecommendations struct {
4-
ID string
5-
Namespace string
6-
Recommendations string
7-
ClusterName string
6+
ID string
7+
ClusterName string
8+
Report []json_v2.ScoredObject
89
}

sql/000008_kubescore.up.sql

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
11
CREATE TABLE IF NOT EXISTS kubescore (
2-
id UUID,
3-
namespace String,
4-
cluster_name String,
5-
recommendations String,
2+
id UUID,
3+
clustername String,
4+
object_name String,
5+
kind String,
6+
apiVersion String,
7+
name String,
8+
namespace String,
9+
target_type String,
10+
description String,
11+
path String,
12+
summary String,
13+
file_name String,
14+
file_row BIGINT,
615
EventTime DateTime('UTC'),
716
ExpiryDate DateTime DEFAULT now() + INTERVAL {{.TTLValue}} {{.TTLUnit}}
817
) ENGINE = MergeTree()

0 commit comments

Comments
 (0)