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

feat: add unified logger interface to allow end-users to choose preferred logger #223

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
74 changes: 54 additions & 20 deletions examples/trivy.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,41 @@
package main

import (
"context"
"encoding/json"
"fmt"
"log"

"github.com/aquasecurity/trivy-kubernetes/pkg/artifacts"
"github.com/aquasecurity/trivy-kubernetes/pkg/k8s"
"github.com/aquasecurity/trivy-kubernetes/pkg/trivyk8s"
tk "github.com/aquasecurity/trivy-kubernetes/pkg/trivyk8s"

"github.com/go-logr/logr"
"github.com/go-logr/logr/funcr"
"github.com/sirupsen/logrus"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"k8s.io/utils/pointer"

"context"
)

func newStdoutLogger() logr.Logger {
return funcr.New(func(prefix, args string) {
if prefix != "" {
fmt.Printf("%s: %s\n", prefix, args)
} else {
fmt.Println(args)
}
}, funcr.Options{})
}

func main() {
// create a new sink that will write to stdout
// and use it to create a new logger
logrusInterface := logrus.New()

logger, _ := zap.NewProduction()
logr := newStdoutLogger()

logger, _ := zap.NewDevelopment()
defer logger.Sync()

ctx := context.Background()
Expand All @@ -30,58 +47,75 @@ func main() {

fmt.Println("Current namespace:", cluster.GetCurrentNamespace())

trivyk8s := tk.New(cluster, logger.Sugar(), tk.WithExcludeOwned(true))
fmt.Println("Scanning cluster")
trivyk8sGoLogr := trivyk8s.New(cluster, logr, trivyk8s.WithExcludeOwned(true))
trivyk8sLogrus := trivyk8s.New(cluster, logrusInterface, trivyk8s.WithExcludeOwned(true))
trivyk8sZapSugar := trivyk8s.New(cluster, logger.Sugar(), trivyk8s.WithExcludeOwned(true))

fmt.Println("Scanning cluster with zap logger")

// trivy k8s #cluster
artifacts, err := trivyk8sZapSugar.ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
// printArtifacts(artifacts)

fmt.Println("Scanning cluster with logrus logger")
artifacts, err = trivyk8sLogrus.ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
// printArtifacts(artifacts)

//trivy k8s #cluster
artifacts, err := trivyk8s.ListArtifacts(ctx)
fmt.Println("Scanning cluster with go-logr logger")
artifacts, err = trivyk8sGoLogr.ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
printArtifacts(artifacts)

fmt.Println("Scanning kind 'pods' with exclude-owned=true")
artifacts, err = trivyk8s.Resources("pod").AllNamespaces().ListArtifacts(ctx)
artifacts, err = trivyk8sZapSugar.Resources("pod").AllNamespaces().ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
printArtifacts(artifacts)

fmt.Println("Scanning namespace 'default'")
//trivy k8s --namespace default
artifacts, err = trivyk8s.Namespace("default").ListArtifacts(ctx)
// trivy k8s --namespace default
artifacts, err = trivyk8sGoLogr.Namespace("default").ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
printArtifacts(artifacts)
fmt.Println("Scanning all namespaces ")
artifacts, err = trivyk8s.AllNamespaces().ListArtifacts(ctx)
artifacts, err = trivyk8sGoLogr.AllNamespaces().ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
printArtifacts(artifacts)

fmt.Println("Scanning namespace 'default', resource 'deployment/orion'")

//trivy k8s --namespace default deployment/orion
artifact, err := trivyk8s.Namespace("default").GetArtifact(ctx, "deploy", "orion")
// trivy k8s --namespace default deployment/orion
artifact, err := trivyk8sGoLogr.Namespace("default").GetArtifact(ctx, "deploy", "orion")
if err != nil {
log.Fatal(err)
}
printArtifact(artifact)

fmt.Println("Scanning 'deployments'")

//trivy k8s deployment
artifacts, err = trivyk8s.Namespace("default").Resources("deployment").ListArtifacts(ctx)
// trivy k8s deployment
artifacts, err = trivyk8sGoLogr.Namespace("default").Resources("deployment").ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
printArtifacts(artifacts)

fmt.Println("Scanning 'cm,pods'")
//trivy k8s clusterroles,pods
artifacts, err = trivyk8s.Namespace("default").Resources("cm,pods").ListArtifacts(ctx)
// trivy k8s clusterroles,pods
artifacts, err = trivyk8sGoLogr.Namespace("default").Resources("cm,pods").ListArtifacts(ctx)
if err != nil {
log.Fatal(err)
}
Expand Down Expand Up @@ -111,7 +145,7 @@ func main() {
}

// collect node info
ar, err := trivyk8s.ListArtifactAndNodeInfo(ctx, []tk.NodeCollectorOption{
ar, err := trivyk8sGoLogr.ListArtifactAndNodeInfo(ctx, []tk.NodeCollectorOption{
tk.WithScanJobNamespace("trivy-temp"),
tk.WithIgnoreLabels(map[string]string{"chen": "test"}),
tk.WithTolerations(tolerations)}...)
Expand All @@ -125,7 +159,7 @@ func main() {
fmt.Println(a.RawResource)
}

bi, err := trivyk8s.ListClusterBomInfo(ctx)
bi, err := trivyk8sZapSugar.ListClusterBomInfo(ctx)
if err != nil {
log.Fatal(err)
}
Expand Down
8 changes: 6 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
github.com/aws/aws-sdk-go v1.48.4
github.com/davecgh/go-spew v1.1.1
github.com/google/go-containerregistry v0.16.1
github.com/sirupsen/logrus v1.9.1
github.com/stretchr/testify v1.8.4
go.uber.org/zap v1.26.0
gopkg.in/yaml.v3 v3.0.1
Expand All @@ -21,14 +22,18 @@ require (

require (
github.com/google/gnostic-models v0.6.8 // indirect
github.com/onsi/ginkgo/v2 v2.11.0 // indirect
github.com/onsi/gomega v1.27.10 // indirect
go.uber.org/goleak v1.2.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sync v0.2.0 // indirect
)

require (
github.com/emicklei/go-restful/v3 v3.9.0 // indirect
github.com/evanphx/json-patch v5.6.0+incompatible // indirect
github.com/go-errors/errors v1.4.2 // indirect
github.com/go-logr/logr v1.3.0 // indirect
github.com/go-logr/logr v1.3.0
github.com/go-openapi/jsonpointer v0.19.6 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.22.3 // indirect
Expand Down Expand Up @@ -59,7 +64,6 @@ require (
github.com/spf13/pflag v1.0.5 // indirect
github.com/xlab/treeprint v1.2.0 // indirect
go.starlark.net v0.0.0-20230525235612-a134d8f9ddca // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/oauth2 v0.8.0 // indirect
golang.org/x/sys v0.13.0 // indirect
Expand Down
17 changes: 11 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,10 @@ github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/
github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/onsi/ginkgo/v2 v2.9.4 h1:xR7vG4IXt5RWx6FfIjyAtsoMAtnc3C/rFXBBd2AjZwE=
github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE=
github.com/onsi/ginkgo/v2 v2.11.0 h1:WgqUCUt/lT6yXoQ8Wef0fsNn5cAuMK7+KT9UFRz2tcU=
github.com/onsi/ginkgo/v2 v2.11.0/go.mod h1:ZhrRA5XmEE3x3rhlzamx/JJvujdZoJ2uvgI7kR0iZvM=
github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI=
github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI=
Expand All @@ -115,6 +117,8 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sirupsen/logrus v1.9.1 h1:Ou41VVR3nMWWmTiEUnj0OlsgOSCUFgsPAOl6jRIcVtQ=
github.com/sirupsen/logrus v1.9.1/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
Expand All @@ -136,9 +140,10 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.starlark.net v0.0.0-20230525235612-a134d8f9ddca h1:VdD38733bfYv5tUZwEIskMM93VanwNIi5bIKnDrJdEY=
go.starlark.net v0.0.0-20230525235612-a134d8f9ddca/go.mod h1:jxU+3+j+71eXOW14274+SmmuW82qJzl6iZSeqEtTGds=
go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A=
go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
Expand Down Expand Up @@ -197,7 +202,7 @@ golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBn
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.9.1 h1:8WMNJAz3zrtPmnYC7ISf5dEn3MT0gY7jBJfw27yrrLo=
golang.org/x/tools v0.9.3 h1:Gn1I8+64MsuTb/HpH+LmQtNas23LhUVr3rYZ0eKuaMM=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Expand Down
57 changes: 54 additions & 3 deletions pkg/trivyk8s/trivyk8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ import (
"encoding/json"
"fmt"
"strings"
"sync"
"time"

"github.com/aquasecurity/trivy-kubernetes/pkg/artifacts"
"github.com/aquasecurity/trivy-kubernetes/pkg/bom"
"github.com/aquasecurity/trivy-kubernetes/pkg/jobs"
"github.com/aquasecurity/trivy-kubernetes/pkg/k8s"
"github.com/go-logr/logr"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
Expand Down Expand Up @@ -50,21 +52,58 @@ type client struct {
namespace string
resources []string
allNamespaces bool
logger *zap.SugaredLogger
logger interface{}
excludeOwned bool
scanJobParams scanJobParams
loggerInit sync.Once
}

type K8sOption func(*client)

// LeveledLogger is an interface that can be implemented by any logger or a
// logger wrapper to provide leveled logging. The methods accept a message
// string and a variadic number of key-value pairs. For log.Printf style
// formatting where message string contains a format specifier, use Logger
// interface.
type LeveledLogger interface {
Error(msg string, keysAndValues ...interface{})
Info(msg string, keysAndValues ...interface{})
Debug(msg string, keysAndValues ...interface{})
Warn(msg string, keysAndValues ...interface{})
}

// Logger interface allows to use other loggers than
// standard log.Logger.
type Logger interface {
Printf(string, ...interface{})
}

func (c *client) log() interface{} {
c.loggerInit.Do(func() {
if c.logger == nil {
return
}

switch c.logger.(type) {
case Logger, LeveledLogger, logr.Logger, *zap.SugaredLogger:
// ok
default:
// This should happen in dev when they are setting Logger and work on code, not in prod.
panic(fmt.Sprintf("invalid logger type passed, must be Logger, LeveledLogger, logr.Logger or zap.SugaredLogger , was %T", c.logger))
}
})

return c.logger
}

func WithExcludeOwned(excludeOwned bool) K8sOption {
return func(c *client) {
c.excludeOwned = excludeOwned
}
}

// New creates a trivyK8S client
func New(cluster k8s.Cluster, logger *zap.SugaredLogger, opts ...K8sOption) TrivyK8S {
func New(cluster k8s.Cluster, logger interface{}, opts ...K8sOption) TrivyK8S {
c := &client{cluster: cluster, logger: logger}
for _, opt := range opts {
opt(c)
Expand Down Expand Up @@ -104,6 +143,8 @@ func isNamespaced(namespace string, allNamespace bool) bool {

// ListArtifacts returns kubernetes scannable artifacs.
func (c *client) ListArtifacts(ctx context.Context) ([]*artifacts.Artifact, error) {
logger := c.log()

artifactList := make([]*artifacts.Artifact, 0)

namespaced := isNamespaced(c.namespace, c.allNamespaces)
Expand All @@ -120,7 +161,17 @@ func (c *client) ListArtifacts(ctx context.Context) ([]*artifacts.Artifact, erro
lerr := fmt.Errorf("failed listing resources for gvr: %v - %w", gvr, err)

if errors.IsNotFound(err) {
c.logger.Error(lerr)

switch v := logger.(type) {
case logr.Logger:
v.Error(lerr, lerr.Error())
case *zap.SugaredLogger:
v.Errorf(lerr.Error())
case LeveledLogger:
v.Error(lerr.Error())
case Logger:
v.Printf(lerr.Error())
}
// if a resource is not found, we log and continue
continue
}
Expand Down
Loading