Skip to content

Commit

Permalink
chore(cmd,pkg,validate): drop logrus direct dependency.
Browse files Browse the repository at this point in the history
Make use of golang 1.21 slog package.
Moreover, avoid enforcing a cobra.OnInitialize() function that would run even
when driverkit is invoked as a library.

Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
  • Loading branch information
FedeDP authored and poiana committed Sep 5, 2023
1 parent c00878e commit 802c274
Show file tree
Hide file tree
Showing 17 changed files with 150 additions and 147 deletions.
8 changes: 5 additions & 3 deletions cmd/config_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ package cmd

import (
"fmt"
"log/slog"
"os"

"github.com/creasty/defaults"
"github.com/falcosecurity/driverkit/validate"
"github.com/go-playground/validator/v10"
logger "github.com/sirupsen/logrus"
)

var validProcessors = []string{"docker", "kubernetes", "kubernetes-in-cluster"}
Expand All @@ -16,7 +17,7 @@ var configOptions *ConfigOptions
// ConfigOptions represent the persistent configuration flags of driverkit.
type ConfigOptions struct {
ConfigFile string
LogLevel string `validate:"logrus" name:"log level" default:"info"`
LogLevel string `validate:"loglevel" name:"log level" default:"info"`
Timeout int `validate:"number,min=30" default:"120" name:"timeout"`
ProxyURL string `validate:"omitempty,proxy" name:"proxy url"`
DryRun bool
Expand All @@ -28,7 +29,8 @@ type ConfigOptions struct {
func NewConfigOptions() *ConfigOptions {
o := &ConfigOptions{}
if err := defaults.Set(o); err != nil {
logger.WithError(err).WithField("options", "ConfigOptions").Fatal("error setting driverkit options defaults")
slog.With("err", err.Error(), "options", "ConfigOptions").Error("error setting driverkit options defaults")
os.Exit(1)
}
return o
}
Expand Down
8 changes: 5 additions & 3 deletions cmd/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package cmd

import (
"github.com/falcosecurity/driverkit/pkg/driverbuilder"
logger "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"log/slog"
"os"
)

// NewDockerCmd creates the `driverkit docker` command.
Expand All @@ -14,10 +15,11 @@ func NewDockerCmd(rootOpts *RootOptions, rootFlags *pflag.FlagSet) *cobra.Comman
Use: "docker",
Short: "Build Falco kernel modules and eBPF probes against a docker daemon.",
Run: func(c *cobra.Command, args []string) {
logger.WithField("processor", c.Name()).Info("driver building, it will take a few seconds")
slog.With("processor", c.Name()).Info("driver building, it will take a few seconds")
if !configOptions.DryRun {
if err := driverbuilder.NewDockerBuildProcessor(viper.GetInt("timeout"), viper.GetString("proxy")).Start(rootOpts.ToBuild()); err != nil {
logger.WithError(err).Fatal("exiting")
slog.With("err", err.Error()).Error("exiting")
os.Exit(1)
}
}
},
Expand Down
4 changes: 2 additions & 2 deletions cmd/images.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package cmd

import (
"github.com/olekukonko/tablewriter"
logger "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"log/slog"
"os"
)

Expand All @@ -14,7 +14,7 @@ func NewImagesCmd(rootOpts *RootOptions, rootFlags *pflag.FlagSet) *cobra.Comman
Use: "images",
Short: "List builder images",
Run: func(c *cobra.Command, args []string) {
logger.WithField("processor", c.Name()).Info("listing images")
slog.With("processor", c.Name()).Info("listing images")
b := rootOpts.ToBuild()
b.LoadImages()

Expand Down
8 changes: 5 additions & 3 deletions cmd/kubernetes.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package cmd

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

"github.com/falcosecurity/driverkit/pkg/driverbuilder"
"github.com/falcosecurity/driverkit/pkg/kubernetes/factory"
logger "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
Expand Down Expand Up @@ -44,10 +45,11 @@ func NewKubernetesCmd(rootOpts *RootOptions, rootFlags *pflag.FlagSet) *cobra.Co
kubefactory := factory.NewFactory(configFlags)

kubernetesCmd.Run = func(cmd *cobra.Command, args []string) {
logger.WithField("processor", cmd.Name()).Info("driver building, it will take a few seconds")
slog.With("processor", cmd.Name()).Info("driver building, it will take a few seconds")
if !configOptions.DryRun {
if err := kubernetesRun(cmd, args, kubefactory, rootOpts); err != nil {
logger.WithError(err).Fatal("exiting")
slog.With("err", err.Error()).Error("exiting")
os.Exit(1)
}
}
}
Expand Down
14 changes: 9 additions & 5 deletions cmd/kubernetes_in_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ package cmd
import (
"github.com/falcosecurity/driverkit/pkg/driverbuilder"
"github.com/falcosecurity/driverkit/pkg/kubernetes/factory"
logger "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"log/slog"
"os"
)

// NewKubernetesInClusterCmd creates the `driverkit kubernetes` command.
Expand All @@ -27,17 +28,20 @@ func NewKubernetesInClusterCmd(rootOpts *RootOptions, rootFlags *pflag.FlagSet)
kubernetesInClusterCmd.PersistentFlags().AddFlagSet(rootFlags)

kubernetesInClusterCmd.Run = func(cmd *cobra.Command, args []string) {
logger.WithField("processor", cmd.Name()).Info("driver building, it will take a few seconds")
slog.With("processor", cmd.Name()).Info("driver building, it will take a few seconds")
if !configOptions.DryRun {
config, err := rest.InClusterConfig()
if err != nil {
logger.WithError(err).Fatal("exiting")
slog.With("err", err.Error()).Error("exiting")
os.Exit(1)
}
if err = factory.SetKubernetesDefaults(config); err != nil {
logger.WithError(err).Fatal("exiting")
slog.With("err", err.Error()).Error("exiting")
os.Exit(1)
}
if err = kubernetesInClusterRun(cmd, args, config, rootOpts); err != nil {
logger.WithError(err).Fatal("exiting")
slog.With("err", err.Error()).Error("exiting")
os.Exit(1)
}
}
}
Expand Down
41 changes: 21 additions & 20 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package cmd
import (
"fmt"
"github.com/falcosecurity/driverkit/pkg/kernelrelease"
"github.com/falcosecurity/driverkit/validate"
"io"
"log/slog"
"os"
"runtime"
"sort"
Expand All @@ -15,7 +17,6 @@ import (
"github.com/spf13/pflag"

homedir "github.com/mitchellh/go-homedir"
logger "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)

Expand Down Expand Up @@ -80,7 +81,7 @@ func persistentValidateFunc(rootCommand *RootCmd, rootOpts *RootOptions) func(c
if c.Root() != c && c.Name() != "help" && c.Name() != "__complete" && c.Name() != "__completeNoDesc" && c.Name() != "completion" {
if errs := rootOpts.Validate(); errs != nil {
for _, err := range errs {
logger.WithError(err).Error("error validating build options")
slog.With("err", err.Error()).Error("error validating build options")
}
return fmt.Errorf("exiting for validation errors")
}
Expand Down Expand Up @@ -108,9 +109,12 @@ func NewRootCmd() *RootCmd {
DisableFlagsInUseLine: true,
DisableAutoGenTag: true,
Version: version.String(),
PreRun: func(cmd *cobra.Command, args []string) {
initConfig()
},
Run: func(c *cobra.Command, args []string) {
if len(args) == 0 {
logger.WithField("processors", validProcessors).Info("specify a valid processor")
slog.With("processors", validProcessors).Info("specify a valid processor")
}
// Fallback to help
c.Help()
Expand Down Expand Up @@ -206,7 +210,13 @@ func (r *RootCmd) Command() *cobra.Command {
func (r *RootCmd) SetOutput(w io.Writer) {
r.c.SetOut(w)
r.c.SetErr(w)
logger.SetOutput(w)
h := slog.NewJSONHandler(w, &slog.HandlerOptions{Level: validate.ProgramLevel})
slog.SetDefault(slog.New(h))
}

func init() {
h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: validate.ProgramLevel})
slog.SetDefault(slog.New(h))
}

// SetArgs proxies the arguments to the underlying cobra.Command.
Expand All @@ -223,25 +233,16 @@ func (r *RootCmd) Execute() error {
func Start() {
root := NewRootCmd()
if err := root.Execute(); err != nil {
logger.WithError(err).Fatal("error executing driverkit")
slog.With("err", err.Error()).Error("error executing driverkit")
os.Exit(1)
}
}

func init() {
logger.SetFormatter(&logger.TextFormatter{
ForceColors: true,
DisableLevelTruncation: false,
DisableTimestamp: true,
})

cobra.OnInitialize(initConfig)
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if errs := configOptions.Validate(); errs != nil {
for _, err := range errs {
logger.WithError(err).Error("error validating config options")
slog.With("err", err.Error()).Error("error validating config options")
}
// configOptions.configErrors should be true here
}
Expand All @@ -251,7 +252,7 @@ func initConfig() {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
logger.WithError(err).Debug("error getting the home directory")
slog.With("err", err.Error()).Debug("error getting the home directory")
// not setting configOptions.configErrors = true because we fallback to `$HOME/.driverkit.yaml` and try with it
}

Expand All @@ -265,14 +266,14 @@ func initConfig() {

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
logger.WithField("file", viper.ConfigFileUsed()).Info("using config file")
slog.With("file", viper.ConfigFileUsed()).Info("using config file")
} else {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found, ignore ...
logger.Debug("running without a configuration file")
slog.Debug("running without a configuration file")
} else {
// Config file was found but another error was produced
logger.WithField("file", viper.ConfigFileUsed()).WithError(err).Debug("error running with config file")
slog.With("file", viper.ConfigFileUsed(), "err", err.Error()).Debug("error running with config file")
configOptions.configErrors = true
}
}
Expand Down
51 changes: 18 additions & 33 deletions cmd/root_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/falcosecurity/driverkit/pkg/kernelrelease"
"github.com/falcosecurity/driverkit/validate"
"github.com/go-playground/validator/v10"
logger "github.com/sirupsen/logrus"
"log/slog"
"os"
)

Expand Down Expand Up @@ -56,7 +56,8 @@ func init() {
func NewRootOptions() *RootOptions {
rootOpts := &RootOptions{}
if err := defaults.Set(rootOpts); err != nil {
logger.WithError(err).WithField("options", "RootOptions").Fatal("error setting driverkit options defaults")
slog.With("err", err.Error(), "options", "RootOptions").Error("error setting driverkit options defaults")
os.Exit(1)
}
return rootOpts
}
Expand Down Expand Up @@ -87,34 +88,18 @@ func (ro *RootOptions) Validate() []error {
//
// Call it only after validation.
func (ro *RootOptions) Log() {
fields := logger.Fields{}
if ro.Output.Module != "" {
fields["output-module"] = ro.Output.Module
}
if ro.Output.Probe != "" {
fields["output-probe"] = ro.Output.Probe

}
if ro.DriverVersion != "" {
fields["driverversion"] = ro.DriverVersion
}
if ro.KernelRelease != "" {
fields["kernelrelease"] = ro.KernelRelease
}
if ro.KernelVersion != "" {
fields["kernelversion"] = ro.KernelVersion
}
if ro.Target != "" {
fields["target"] = ro.Target
}
fields["arch"] = ro.Architecture
if len(ro.KernelUrls) > 0 {
fields["kernelurls"] = ro.KernelUrls
}
fields["repo-org"] = ro.Repo.Org
fields["repo-name"] = ro.Repo.Name

logger.WithFields(fields).Debug("running with options")
slog.Debug("running with options",
"output-module", ro.Output.Module,
"output-probe", ro.Output.Probe,
"driverversion", ro.DriverVersion,
"kernelrelease", ro.KernelRelease,
"kernelversion", ro.KernelVersion,
"target", ro.Target,
"arch", ro.Architecture,
"kernelurls", ro.KernelUrls,
"repo-org", ro.Repo.Org,
"repo-name", ro.Repo.Name,
)
}

func (ro *RootOptions) ToBuild() *builder.Build {
Expand Down Expand Up @@ -160,7 +145,7 @@ func (ro *RootOptions) ToBuild() *builder.Build {
imageLister, err = builder.NewRepoImagesLister(builderRepo, build)
}
if err != nil {
logger.WithError(err).Warnf("Skipping %s repo\n", builderRepo)
slog.With("err", err.Error()).Warn("Skipping repo", "repo", builderRepo)
} else {
build.ImagesListers = append(build.ImagesListers, imageLister)
}
Expand All @@ -170,11 +155,11 @@ func (ro *RootOptions) ToBuild() *builder.Build {
kr := build.KernelReleaseFromBuildConfig()
if len(build.ModuleFilePath) > 0 && !kr.SupportsModule() {
build.ModuleFilePath = ""
logger.Warningf("Skipping build attempt of module for unsupported kernel version %s", kr.String())
slog.Warn("Skipping build attempt of module for unsupported kernel release", "kernelrelease", kr.String())
}
if len(build.ProbeFilePath) > 0 && !kr.SupportsProbe() {
build.ProbeFilePath = ""
logger.Warningf("Skipping build attempt of probe for unsupported kernel version %s", kr.String())
slog.Warn("Skipping build attempt of module for unsupported kernel release", "kernelrelease", kr.String())
}

return build
Expand Down
15 changes: 9 additions & 6 deletions docgen/docgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import (
"flag"
"fmt"
"io/ioutil"
"log/slog"
"os"
"path"
"strings"

"github.com/falcosecurity/driverkit/cmd"
logger "github.com/sirupsen/logrus"
"github.com/spf13/cobra/doc"
)

Expand Down Expand Up @@ -72,18 +72,21 @@ func main() {
// Generate markdown docs
err := doc.GenMarkdownTreeCustom(root, outputDir, prepender(num), linker)
if err != nil {
logger.WithError(err).Fatal("markdown generation")
slog.With("err", err.Error()).Error("markdown generation")
os.Exit(1)
}

if targetWebsite {
err := os.Rename(path.Join(outputDir, "driverkit.md"), path.Join(outputDir, "_index.md"))
err = os.Rename(path.Join(outputDir, "driverkit.md"), path.Join(outputDir, "_index.md"))
if err != nil {
logger.WithError(err).Fatal("renaming main docs page")
slog.With("err", err.Error()).Error("renaming main docs page")
os.Exit(1)
}
}

if err := stripSensitive(); err != nil {
logger.WithError(err).Fatal("error replacing sensitive data")
if err = stripSensitive(); err != nil {
slog.With("err", err.Error()).Error("error replacing sensitive data")
os.Exit(1)
}
}

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ require (
github.com/go-playground/validator/v10 v10.15.1
github.com/mitchellh/go-homedir v1.1.0
github.com/opencontainers/image-spec v1.1.0-rc4
github.com/sirupsen/logrus v1.9.3
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/cobra v1.7.0
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.16.0
Expand Down
Loading

0 comments on commit 802c274

Please sign in to comment.