Skip to content

Commit

Permalink
feat: CLI command for configuration validation (#1497)
Browse files Browse the repository at this point in the history
  • Loading branch information
0xERR0R authored May 26, 2024
1 parent 5a5ba55 commit 3dcd310
Show file tree
Hide file tree
Showing 11 changed files with 126 additions and 30 deletions.
7 changes: 4 additions & 3 deletions cmd/blocking.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import (

func newBlockingCommand() *cobra.Command {
c := &cobra.Command{
Use: "blocking",
Aliases: []string{"block"},
Short: "Control status of blocking resolver",
Use: "blocking",
Aliases: []string{"block"},
Short: "Control status of blocking resolver",
PersistentPreRunE: initConfigPreRun,
}
c.AddCommand(&cobra.Command{
Use: "enable",
Expand Down
5 changes: 3 additions & 2 deletions cmd/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ import (

func newCacheCommand() *cobra.Command {
c := &cobra.Command{
Use: "cache",
Short: "Performs cache operations",
Use: "cache",
Short: "Performs cache operations",
PersistentPreRunE: initConfigPreRun,
}
c.AddCommand(&cobra.Command{
Use: "flush",
Expand Down
5 changes: 3 additions & 2 deletions cmd/lists.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import (
// NewListsCommand creates new command instance
func NewListsCommand() *cobra.Command {
c := &cobra.Command{
Use: "lists",
Short: "lists operations",
Use: "lists",
Short: "lists operations",
PersistentPreRunE: initConfigPreRun,
}

c.AddCommand(newRefreshCommand())
Expand Down
9 changes: 5 additions & 4 deletions cmd/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ import (
// NewQueryCommand creates new command instance
func NewQueryCommand() *cobra.Command {
c := &cobra.Command{
Use: "query <domain>",
Args: cobra.ExactArgs(1),
Short: "performs DNS query",
RunE: query,
Use: "query <domain>",
Args: cobra.ExactArgs(1),
Short: "performs DNS query",
RunE: query,
PersistentPreRunE: initConfigPreRun,
}

c.Flags().StringP("type", "t", "A", "query type (A, AAAA, ...)")
Expand Down
21 changes: 10 additions & 11 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import (

"github.com/0xERR0R/blocky/config"
"github.com/0xERR0R/blocky/log"
"github.com/0xERR0R/blocky/util"

"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -39,6 +37,7 @@ func NewRootCommand() *cobra.Command {
and ad-blocker for local network.
Complete documentation is available at https://github.com/0xERR0R/blocky`,
PreRunE: initConfigPreRun,
RunE: func(cmd *cobra.Command, args []string) error {
return newServeCommand().RunE(cmd, args)
},
Expand All @@ -56,7 +55,8 @@ Complete documentation is available at https://github.com/0xERR0R/blocky`,
newBlockingCommand(),
NewListsCommand(),
NewHealthcheckCommand(),
newCacheCommand())
newCacheCommand(),
NewValidateCommand())

return c
}
Expand All @@ -65,12 +65,11 @@ func apiURL() string {
return fmt.Sprintf("http://%s%s", net.JoinHostPort(apiHost, strconv.Itoa(int(apiPort))), "/api")
}

//nolint:gochecknoinits
func init() {
cobra.OnInitialize(initConfig)
func initConfigPreRun(cmd *cobra.Command, args []string) error {
return initConfig()
}

func initConfig() {
func initConfig() error {
if configPath == defaultConfigPath {
val, present := os.LookupEnv(configFileEnvVar)
if present {
Expand All @@ -85,7 +84,7 @@ func initConfig() {

cfg, err := config.LoadConfig(configPath, false)
if err != nil {
util.FatalOnError("unable to load configuration: ", err)
return fmt.Errorf("unable to load configuration file '%s': %w", configPath, err)
}

log.Configure(&cfg.Log)
Expand All @@ -99,13 +98,13 @@ func initConfig() {

port, err := config.ConvertPort(split[lastIdx])
if err != nil {
util.FatalOnError("can't convert port to number (1 - 65535)", err)

return
return fmt.Errorf("can't convert port '%s' to number (1 - 65535): %w", split[lastIdx], err)
}

apiPort = port
}

return nil
}

// Execute starts the command
Expand Down
4 changes: 2 additions & 2 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ var _ = Describe("root command", func() {
os.Setenv(configFileEnvVarOld, tmpFile.Path)
DeferCleanup(func() { os.Unsetenv(configFileEnvVarOld) })

initConfig()
Expect(initConfig()).Should(Succeed())

Expect(configPath).Should(Equal(tmpFile.Path))
})
Expand All @@ -62,7 +62,7 @@ var _ = Describe("root command", func() {
os.Setenv(configFileEnvVar, tmpFile.Path)
DeferCleanup(func() { os.Unsetenv(configFileEnvVar) })

initConfig()
Expect(initConfig()).Should(Succeed())

Expect(configPath).Should(Equal(tmpFile.Path))
})
Expand Down
10 changes: 6 additions & 4 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ var (

func newServeCommand() *cobra.Command {
return &cobra.Command{
Use: "serve",
Args: cobra.NoArgs,
Short: "start blocky DNS server (default command)",
RunE: startServer,
Use: "serve",
Args: cobra.NoArgs,
Short: "start blocky DNS server (default command)",
RunE: startServer,
PersistentPreRunE: initConfigPreRun,
SilenceUsage: true,
}
}

Expand Down
4 changes: 2 additions & 2 deletions cmd/serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ var _ = Describe("Serve command", func() {
os.Setenv(configFileEnvVar, cfgFile.Path)
DeferCleanup(func() { os.Unsetenv(configFileEnvVar) })

initConfig()
Expect(initConfig()).Should(Succeed())
})

errChan := make(chan error)
Expand Down Expand Up @@ -89,7 +89,7 @@ var _ = Describe("Serve command", func() {
os.Setenv(configFileEnvVar, cfgFile.Path)
DeferCleanup(func() { os.Unsetenv(configFileEnvVar) })

initConfig()
Expect(initConfig()).Should(Succeed())
})

errChan := make(chan error)
Expand Down
38 changes: 38 additions & 0 deletions cmd/validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package cmd

import (
"errors"
"os"

"github.com/0xERR0R/blocky/log"

"github.com/spf13/cobra"
)

// NewValidateCommand creates new command instance
func NewValidateCommand() *cobra.Command {
return &cobra.Command{
Use: "validate",
Args: cobra.NoArgs,
Short: "Validates the configuration",
RunE: validateConfiguration,
}
}

func validateConfiguration(_ *cobra.Command, _ []string) error {
log.Log().Infof("Validating configuration file: %s", configPath)

_, err := os.Stat(configPath)
if err != nil && errors.Is(err, os.ErrNotExist) {
return errors.New("configuration path does not exist")
}

err = initConfig()
if err != nil {
return err
}

log.Log().Info("Configuration is valid")

return nil
}
52 changes: 52 additions & 0 deletions cmd/validate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package cmd

import (
"github.com/0xERR0R/blocky/helpertest"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

var _ = Describe("Validate command", func() {
var tmpDir *helpertest.TmpFolder
BeforeEach(func() {
tmpDir = helpertest.NewTmpFolder("config")
})
When("Validate is called with not existing configuration file", func() {
It("should terminate with error", func() {
c := NewRootCommand()
c.SetArgs([]string{"validate", "--config", "/notexisting/path.yaml"})

Expect(c.Execute()).Should(HaveOccurred())
})
})

When("Validate is called with existing valid configuration file", func() {
It("should terminate without error", func() {
cfgFile := tmpDir.CreateStringFile("config.yaml",
"upstreams:",
" groups:",
" default:",
" - 1.1.1.1")

c := NewRootCommand()
c.SetArgs([]string{"validate", "--config", cfgFile.Path})

Expect(c.Execute()).Should(Succeed())
})
})

When("Validate is called with existing invalid configuration file", func() {
It("should terminate with error", func() {
cfgFile := tmpDir.CreateStringFile("config.yaml",
"upstreams:",
" groups:",
" default:",
" - 1.broken file")

c := NewRootCommand()
c.SetArgs([]string{"validate", "--config", cfgFile.Path})

Expect(c.Execute()).Should(HaveOccurred())
})
})
})
1 change: 1 addition & 0 deletions docs/interfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ To run the CLI, please ensure, that blocky DNS server is running, then execute `
- `./blocky query <domain>` execute DNS query (A) (simple replacement for dig, useful for debug purposes)
- `./blocky query <domain> --type <queryType>` execute DNS query with passed query type (A, AAAA, MX, ...)
- `./blocky lists refresh` reloads all allow/denylists
- `./blocky validate [--config /path/to/config.yaml]` validates configuration file

!!! tip

Expand Down

0 comments on commit 3dcd310

Please sign in to comment.