Skip to content
This repository has been archived by the owner on Sep 20, 2024. It is now read-only.

refactor: replace logrus with slog #391

Merged
merged 2 commits into from
Oct 26, 2023
Merged
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
6 changes: 3 additions & 3 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ jobs:
name: Build
runs-on: ubuntu-20.04
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v4
with:
go-version: 1.20.5
- name: Checkout code
uses: actions/checkout@v4
go-version-file: go.mod
- name: yaml-lint
uses: ibiqlik/action-yamllint@v3
- name: Setup make
Expand Down
23 changes: 11 additions & 12 deletions cmd/scanner-trivy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"log/slog"
"os"
"os/signal"
"syscall"
Expand All @@ -15,7 +16,6 @@ import (
"github.com/aquasecurity/harbor-scanner-trivy/pkg/redisx"
"github.com/aquasecurity/harbor-scanner-trivy/pkg/scan"
"github.com/aquasecurity/harbor-scanner-trivy/pkg/trivy"
log "github.com/sirupsen/logrus"
)

var (
Expand All @@ -26,10 +26,10 @@ var (
)

func main() {
log.SetOutput(os.Stdout)
log.SetLevel(etc.GetLogLevel())
log.SetReportCaller(false)
log.SetFormatter(&log.JSONFormatter{})
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: etc.LogLevel(),
}))
slog.SetDefault(logger)

info := etc.BuildInfo{
Version: version,
Expand All @@ -38,16 +38,15 @@ func main() {
}

if err := run(info); err != nil {
log.Fatalf("Error: %v", err)
slog.Error("Error: %v", err)
os.Exit(1)
}
}

func run(info etc.BuildInfo) error {
log.WithFields(log.Fields{
"version": info.Version,
"commit": info.Commit,
"built_at": info.Date,
}).Info("Starting harbor-scanner-trivy")
slog.Info("Starting harbor-scanner-trivy", slog.String("version", info.Version),
slog.String("commit", info.Commit), slog.String("built_at", info.Date),
)

config, err := etc.GetConfig()
if err != nil {
Expand Down Expand Up @@ -79,7 +78,7 @@ func run(info etc.BuildInfo) error {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM)
captured := <-sigint
log.WithField("signal", captured.String()).Debug("Trapped os signal")
slog.Debug("Trapped os signal", slog.String("signal", captured.String()))

apiServer.Shutdown()
worker.Stop()
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/aquasecurity/harbor-scanner-trivy

go 1.20
go 1.21

require (
github.com/FZambia/sentinel v1.1.1
Expand All @@ -12,7 +12,6 @@ require (
github.com/gorilla/mux v1.8.0
github.com/opencontainers/go-digest v1.0.0
github.com/prometheus/client_golang v1.17.0
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.8.4
github.com/testcontainers/testcontainers-go v0.25.0
golang.org/x/net v0.17.0
Expand Down Expand Up @@ -55,6 +54,7 @@ require (
github.com/robfig/cron v1.2.0 // indirect
github.com/shirou/gopsutil/v3 v3.23.8 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
Expand Down
9 changes: 9 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk=
dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 h1:bvDV9vkmnHYOMsOr4WLk+Vo07yKIzd94sVoIqshQ4bU=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
Expand Down Expand Up @@ -28,6 +29,7 @@ github.com/cpuguy83/dockercfg v0.3.1 h1:/FpZ+JaygUR/lZP2NlFI2DVfrOEMAIKP5wWEJdoY
github.com/cpuguy83/dockercfg v0.3.1/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY=
github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
Expand Down Expand Up @@ -71,6 +73,7 @@ github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw
github.com/klauspost/compress v1.16.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
Expand Down Expand Up @@ -115,6 +118,7 @@ github.com/prometheus/procfs v0.11.1/go.mod h1:eesXgaPo1q7lBpVMoMy0ZOFTth9hBn4W/
github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ=
github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/seccomp/libseccomp-golang v0.9.2-0.20220502022130-f33da4d89646/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg=
github.com/shirou/gopsutil/v3 v3.23.8 h1:xnATPiybo6GgdRoC4YoGnxXZFRc3dqQTGi73oLvvBrE=
Expand Down Expand Up @@ -172,6 +176,7 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand All @@ -195,7 +200,9 @@ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9sn
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
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=
Expand All @@ -218,8 +225,10 @@ google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.5.0 h1:Ljk6PdHdOhAb5aDMWXjDLMMhph+BpztA4v1QdqEW2eY=
gotest.tools/v3 v3.5.0/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU=
64 changes: 27 additions & 37 deletions pkg/etc/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,82 +3,72 @@ package etc
import (
"errors"
"fmt"
"log/slog"
"os"

log "github.com/sirupsen/logrus"
)

// Check checks config values to fail fast in case of any problems
// that we might have due to invalid config.
func Check(config Config) (err error) {
log.WithFields(log.Fields{
"pid": os.Getpid(),
}).Debug("Current process")
func Check(config Config) error {
slog.Debug("Current process", slog.Int("pid", os.Getpid()))

log.WithFields(log.Fields{
"uid": os.Getuid(),
"gid": os.Getegid(),
"home_dir": os.Getenv("HOME"),
}).Debug("Current user")
slog.Debug("Current user",
slog.Int("uid", os.Getuid()),
slog.Int("gid", os.Getegid()),
slog.String("home_dir", os.Getenv("HOME")),
)

if config.Trivy.CacheDir == "" {
err = errors.New("trivy cache dir must not be blank")
return
return errors.New("trivy cache dir must not be blank")
}

if config.Trivy.ReportsDir == "" {
err = errors.New("trivy reports dir must not be blank")
return
return errors.New("trivy reports dir must not be blank")
}

if err = ensureDirExists(config.Trivy.CacheDir, "trivy cache dir"); err != nil {
return
if err := ensureDirExists(config.Trivy.CacheDir, "trivy cache dir"); err != nil {
return err
}

if err = ensureDirExists(config.Trivy.ReportsDir, "trivy reports dir"); err != nil {
return
if err := ensureDirExists(config.Trivy.ReportsDir, "trivy reports dir"); err != nil {
return err
}

if config.API.IsTLSEnabled() {
if !fileExists(config.API.TLSCertificate) {
err = fmt.Errorf("TLS certificate file does not exist: %s", config.API.TLSCertificate)
return
return fmt.Errorf("TLS certificate file does not exist: %s", config.API.TLSCertificate)
}

if !fileExists(config.API.TLSKey) {
err = fmt.Errorf("TLS private key file does not exist: %s", config.API.TLSKey)
return
return fmt.Errorf("TLS private key file does not exist: %s", config.API.TLSKey)
}

for _, path := range config.API.ClientCAs {
if !fileExists(path) {
err = fmt.Errorf("ClientCA file does not exist: %s", path)
return
return fmt.Errorf("ClientCA file does not exist: %s", path)
}
}
}

return
return nil
}

func ensureDirExists(path, description string) (err error) {
func ensureDirExists(path, description string) error {
logger := slog.With(slog.String("path", path))
if !dirExists(path) {
log.WithField("path", path).Warnf("%s does not exist", description)
log.WithField("path", path).Debugf("Creating %s", description)
if err = os.MkdirAll(path, 0777); err != nil {
err = fmt.Errorf("creating %s: %w", description, err)
return
logger.Warn(fmt.Sprintf("%s does not exist", description))
logger.Debug(fmt.Sprintf("Creating %s", description))
if err := os.MkdirAll(path, 0777); err != nil {
return fmt.Errorf("creating %s: %w", description, err)
}
}
fi, err := os.Stat(path)
if err != nil {
return
return err
}

log.WithFields(log.Fields{
"mode": fi.Mode().String(),
}).Debugf("%s permissions", description)
return
logger.Debug(fmt.Sprintf("%s permissions", description), slog.String("mode", fi.Mode().String()))
return nil
}

// dirExists checks if a dir exists before we
Expand Down
23 changes: 15 additions & 8 deletions pkg/etc/config.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package etc

import (
"log/slog"
"os"
"strings"
"time"

"github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor"
"github.com/caarlos0/env/v6"
"github.com/sirupsen/logrus"
)

type BuildInfo struct {
Expand Down Expand Up @@ -73,15 +74,21 @@ type RedisPool struct {
WriteTimeout time.Duration `env:"SCANNER_REDIS_POOL_WRITE_TIMEOUT" envDefault:"1s"`
}

func GetLogLevel() logrus.Level {
func LogLevel() slog.Level {
if value, ok := os.LookupEnv("SCANNER_LOG_LEVEL"); ok {
level, err := logrus.ParseLevel(value)
if err != nil {
return logrus.InfoLevel
switch strings.ToLower(value) {
case "error":
return slog.LevelError
case "warn", "warning":
return slog.LevelWarn
case "info":
return slog.LevelInfo
case "trace", "debug":
return slog.LevelDebug
}
return level
return slog.LevelInfo
}
return logrus.InfoLevel
return slog.LevelInfo
}

func GetConfig() (Config, error) {
Expand All @@ -92,7 +99,7 @@ func GetConfig() (Config, error) {
}

if _, ok := os.LookupEnv("SCANNER_TRIVY_DEBUG_MODE"); !ok {
if GetLogLevel() == logrus.DebugLevel {
if LogLevel() == slog.LevelDebug {
cfg.Trivy.DebugMode = true
}
}
Expand Down
Loading
Loading