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

new(cmd/driver,pkg/options,internal/config): added driver config cmd tests #362

Merged
merged 1 commit into from
Dec 1, 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
5 changes: 4 additions & 1 deletion cmd/driver/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ func (o *driverConfigOptions) RunDriverConfig(ctx context.Context, cmd *cobra.Co

d, err := driverdistro.Discover(info, driverCfg.HostRoot)
if err != nil {
return err
if !errors.Is(err, driverdistro.ErrUnsupported) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When error is ErrUnsupported, just print that we detected an unsupported OS (we failed to determine it), and go on using the fallback generic logic.

return err
}
o.Printer.Logger.Info("Detected an unsupported target system; falling back at generic logic.")
}
o.Printer.Logger.Debug("Discovered distro", o.Printer.Logger.Args("target", d))

Expand Down
69 changes: 69 additions & 0 deletions cmd/driver/config/config_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2023 The Falco Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package driverconfig_test

import (
"context"
"os"
"path/filepath"
"testing"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"github.com/spf13/cobra"

"github.com/falcosecurity/falcoctl/cmd"
commonoptions "github.com/falcosecurity/falcoctl/pkg/options"
testutils "github.com/falcosecurity/falcoctl/pkg/test"
)

var (
ctx = context.Background()
output = gbytes.NewBuffer()
rootCmd *cobra.Command
opt *commonoptions.Common
configFile string
err error
args []string
)

func TestConfig(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Config Suite")
}

var _ = BeforeSuite(func() {

// Create and configure the common options.
opt = commonoptions.NewOptions()
opt.Initialize(commonoptions.WithWriter(output))

// Create temporary directory used to save the configuration file.
configFile, err = testutils.CreateEmptyFile("falcoctl.yaml")
Expect(err).Should(Succeed())
})

var _ = AfterSuite(func() {
configDir := filepath.Dir(configFile)
Expect(os.RemoveAll(configDir)).Should(Succeed())
})

func executeRoot(args []string) error {
rootCmd.SetArgs(args)
rootCmd.SetOut(output)
return cmd.Execute(rootCmd, opt)
}
82 changes: 82 additions & 0 deletions cmd/driver/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2023 The Falco Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package driverconfig_test

import (
"regexp"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"

"github.com/falcosecurity/falcoctl/cmd"
)

var driverConfigHelp = `Configure a driver for future usages with other driver subcommands.`

var addAssertFailedBehavior = func(specificError string) {
It("check that fails and the usage is not printed", func() {
Expect(err).To(HaveOccurred())
Expect(output).Should(gbytes.Say(regexp.QuoteMeta(specificError)))
})
}

var _ = Describe("config", func() {

var (
driverCmd = "driver"
configCmd = "config"
)

// Each test gets its own root command and runs it.
// The err variable is asserted by each test.
JustBeforeEach(func() {
rootCmd = cmd.New(ctx, opt)
err = executeRoot(args)
})

JustAfterEach(func() {
Expect(output.Clear()).ShouldNot(HaveOccurred())
})

Context("help message", func() {
BeforeEach(func() {
args = []string{driverCmd, configCmd, "--help"}
})

It("should match the saved one", func() {
Expect(output).Should(gbytes.Say(driverConfigHelp))
})
})

// Here we are testing failure cases for configuring a driver.
Context("failure", func() {
When("with non absolute host-root", func() {
BeforeEach(func() {
args = []string{driverCmd, configCmd, "--config", configFile, "--host-root", "foo/"}
})
addAssertFailedBehavior("ERROR host-root must be an absolute path: foo/")
})

When("with invalid driver type", func() {
BeforeEach(func() {
args = []string{driverCmd, configCmd, "--config", configFile, "--type", "foo"}
})
addAssertFailedBehavior(`ERROR invalid argument "foo" for "--type" flag: invalid argument "foo",` +
` please provide one of (auto, ebpf, kmod, modern_ebpf)`)
})
})
})
5 changes: 4 additions & 1 deletion cmd/driver/printenv/printenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package driverprintenv

import (
"errors"
"strings"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -67,7 +68,9 @@ func (o *driverPrintenvOptions) RunDriverPrintenv(_ context.Context) error {

d, err := driverdistro.Discover(kr, driver.HostRoot)
if err != nil {
return err
if !errors.Is(err, driverdistro.ErrUnsupported) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When error is ErrUnsupported go on with undetermined distro target.

return err
}
}
o.Printer.DefaultText.Printf("TARGET_ID=%q\n", d.String())

Expand Down
8 changes: 6 additions & 2 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,11 @@ func Load(path string) error {
// Set default registry auth config path
viper.SetDefault(RegistryCredentialConfigKey, DefaultRegistryCredentialConfPath)
// Set default driver
viper.SetDefault(DriverKey, DefaultDriver)
viper.SetDefault(DriverTypeKey, DefaultDriver.Type)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes the retrieving of DriverFooKey when falcoctl.yaml is an empty file (as used in tests).
Otherwise Driverer would find an empty DriverTypeKey value and fail during the conversion to a drivertype.Type.

viper.SetDefault(DriverHostRootKey, DefaultDriver.HostRoot)
viper.SetDefault(DriverNameKey, DefaultDriver.Name)
viper.SetDefault(DriverReposKey, DefaultDriver.Repos)
viper.SetDefault(DriverVersionKey, DefaultDriver.Version)

err = viper.ReadInConfig()
if errors.As(err, &viper.ConfigFileNotFoundError{}) || os.IsNotExist(err) {
Expand Down Expand Up @@ -642,7 +646,7 @@ func UpdateConfigFile(key string, value interface{}, path string) error {
v.Set(key, value)

if err := v.WriteConfig(); err != nil {
return fmt.Errorf("unable to set key %q to config file: %w", IndexesKey, err)
return fmt.Errorf("unable to set key %q to config file: %w", key, err)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was just a wrong log.

}

return nil
Expand Down
6 changes: 5 additions & 1 deletion pkg/options/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
package options

import (
"sort"

drivertype "github.com/falcosecurity/falcoctl/pkg/driver/type"
)

Expand All @@ -26,7 +28,9 @@ type DriverTypes struct {

// NewDriverTypes returns a new Enum configured for the driver types.
func NewDriverTypes() *DriverTypes {
types := drivertype.GetTypes()
sort.Strings(types)
return &DriverTypes{
Enum: NewEnum(drivertype.GetTypes(), drivertype.TypeKmod),
Enum: NewEnum(types, drivertype.TypeKmod),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To get a stable CLI help message, we need to sort the strings so that they always appear with same sorting.

}
}