Refactoring/config struct names (#1315)

* vscode config changed in new version

* FilteringConfig -> Filtering

* CachingConfig -> Caching

* QueryLogConfig -> QueryLog

* MetricsConfig -> Metrics

* HostsFileConfig -> HostsFile

* PortsConfig -> Ports

* BootstrapDNSConfig -> BootstrapDNS

* BootstrappedUpstreamConfig -> BootstrappedUpstream

* bootstrapDNSConfig -> bootstrapDNS

* bootstrappedUpstreamConfig -> bootstrappedUpstream

* SourceLoadingConfig -> SourceLoading

* DownloaderConfig -> Downloader
This commit is contained in:
Kwitsch 2023-12-20 21:38:33 +01:00 committed by GitHub
parent dece894bd6
commit 03131c443c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 182 additions and 182 deletions

View File

@ -5,8 +5,8 @@
"editor.formatOnSave": true, "editor.formatOnSave": true,
"editor.formatOnPaste": true, "editor.formatOnPaste": true,
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": {
"source.organizeImports": true, "source.organizeImports": "explicit",
"source.fixAll": true "source.fixAll": "explicit"
}, },
"editor.rulers": [120], "editor.rulers": [120],
"go.showWelcome": false, "go.showWelcome": false,

View File

@ -13,7 +13,7 @@ type Blocking struct {
ClientGroupsBlock map[string][]string `yaml:"clientGroupsBlock"` ClientGroupsBlock map[string][]string `yaml:"clientGroupsBlock"`
BlockType string `yaml:"blockType" default:"ZEROIP"` BlockType string `yaml:"blockType" default:"ZEROIP"`
BlockTTL Duration `yaml:"blockTTL" default:"6h"` BlockTTL Duration `yaml:"blockTTL" default:"6h"`
Loading SourceLoadingConfig `yaml:"loading"` Loading SourceLoading `yaml:"loading"`
// Deprecated options // Deprecated options
Deprecated struct { Deprecated struct {

View File

@ -6,8 +6,8 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
// CachingConfig configuration for domain caching // Caching configuration for domain caching
type CachingConfig struct { type Caching struct {
MinCachingTime Duration `yaml:"minTime"` MinCachingTime Duration `yaml:"minTime"`
MaxCachingTime Duration `yaml:"maxTime"` MaxCachingTime Duration `yaml:"maxTime"`
CacheTimeNegative Duration `yaml:"cacheTimeNegative" default:"30m"` CacheTimeNegative Duration `yaml:"cacheTimeNegative" default:"30m"`
@ -19,12 +19,12 @@ type CachingConfig struct {
} }
// IsEnabled implements `config.Configurable`. // IsEnabled implements `config.Configurable`.
func (c *CachingConfig) IsEnabled() bool { func (c *Caching) IsEnabled() bool {
return c.MaxCachingTime.IsAtLeastZero() return c.MaxCachingTime.IsAtLeastZero()
} }
// LogConfig implements `config.Configurable`. // LogConfig implements `config.Configurable`.
func (c *CachingConfig) LogConfig(logger *logrus.Entry) { func (c *Caching) LogConfig(logger *logrus.Entry) {
logger.Infof("minTime = %s", c.MinCachingTime) logger.Infof("minTime = %s", c.MinCachingTime)
logger.Infof("maxTime = %s", c.MaxCachingTime) logger.Infof("maxTime = %s", c.MaxCachingTime)
logger.Infof("cacheTimeNegative = %s", c.CacheTimeNegative) logger.Infof("cacheTimeNegative = %s", c.CacheTimeNegative)
@ -39,7 +39,7 @@ func (c *CachingConfig) LogConfig(logger *logrus.Entry) {
} }
} }
func (c *CachingConfig) EnablePrefetch() { func (c *Caching) EnablePrefetch() {
const day = Duration(24 * time.Hour) const day = Duration(24 * time.Hour)
if !c.IsEnabled() { if !c.IsEnabled() {

View File

@ -9,19 +9,19 @@ import (
) )
var _ = Describe("CachingConfig", func() { var _ = Describe("CachingConfig", func() {
var cfg CachingConfig var cfg Caching
suiteBeforeEach() suiteBeforeEach()
BeforeEach(func() { BeforeEach(func() {
cfg = CachingConfig{ cfg = Caching{
MaxCachingTime: Duration(time.Hour), MaxCachingTime: Duration(time.Hour),
} }
}) })
Describe("IsEnabled", func() { Describe("IsEnabled", func() {
It("should be true by default", func() { It("should be true by default", func() {
cfg := CachingConfig{} cfg := Caching{}
Expect(defaults.Set(&cfg)).Should(Succeed()) Expect(defaults.Set(&cfg)).Should(Succeed())
Expect(cfg.IsEnabled()).Should(BeTrue()) Expect(cfg.IsEnabled()).Should(BeTrue())
@ -29,7 +29,7 @@ var _ = Describe("CachingConfig", func() {
When("the config is disabled", func() { When("the config is disabled", func() {
BeforeEach(func() { BeforeEach(func() {
cfg = CachingConfig{ cfg = Caching{
MaxCachingTime: Duration(time.Hour * -1), MaxCachingTime: Duration(time.Hour * -1),
} }
}) })
@ -46,7 +46,7 @@ var _ = Describe("CachingConfig", func() {
When("the config is disabled", func() { When("the config is disabled", func() {
It("should be false", func() { It("should be false", func() {
cfg := CachingConfig{ cfg := Caching{
MaxCachingTime: Duration(-1), MaxCachingTime: Duration(-1),
} }
@ -58,7 +58,7 @@ var _ = Describe("CachingConfig", func() {
Describe("LogConfig", func() { Describe("LogConfig", func() {
When("prefetching is enabled", func() { When("prefetching is enabled", func() {
BeforeEach(func() { BeforeEach(func() {
cfg = CachingConfig{ cfg = Caching{
Prefetching: true, Prefetching: true,
} }
}) })
@ -75,7 +75,7 @@ var _ = Describe("CachingConfig", func() {
Describe("EnablePrefetch", func() { Describe("EnablePrefetch", func() {
When("prefetching is enabled", func() { When("prefetching is enabled", func() {
BeforeEach(func() { BeforeEach(func() {
cfg = CachingConfig{} cfg = Caching{}
}) })
It("should return configuration", func() { It("should return configuration", func() {

View File

@ -171,41 +171,41 @@ func (l *ListenConfig) UnmarshalText(data []byte) error {
return nil return nil
} }
// UnmarshalYAML creates BootstrapDNSConfig from YAML // UnmarshalYAML creates BootstrapDNS from YAML
func (b *BootstrapDNSConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { func (b *BootstrapDNS) UnmarshalYAML(unmarshal func(interface{}) error) error {
var single BootstrappedUpstreamConfig var single BootstrappedUpstream
if err := unmarshal(&single); err == nil { if err := unmarshal(&single); err == nil {
*b = BootstrapDNSConfig{single} *b = BootstrapDNS{single}
return nil return nil
} }
// bootstrapDNSConfig is used to avoid infinite recursion: // bootstrapDNS is used to avoid infinite recursion:
// if we used BootstrapDNSConfig, unmarshal would just call us again. // if we used BootstrapDNS, unmarshal would just call us again.
var c bootstrapDNSConfig var c bootstrapDNS
if err := unmarshal(&c); err != nil { if err := unmarshal(&c); err != nil {
return err return err
} }
*b = BootstrapDNSConfig(c) *b = BootstrapDNS(c)
return nil return nil
} }
// UnmarshalYAML creates BootstrapConfig from YAML // UnmarshalYAML creates BootstrappedUpstream from YAML
func (b *BootstrappedUpstreamConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { func (b *BootstrappedUpstream) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&b.Upstream); err == nil { if err := unmarshal(&b.Upstream); err == nil {
return nil return nil
} }
// bootstrapConfig is used to avoid infinite recursion: // bootstrappedUpstream is used to avoid infinite recursion:
// if we used BootstrapConfig, unmarshal would just call us again. // if we used BootstrappedUpstream, unmarshal would just call us again.
var c bootstrappedUpstreamConfig var c bootstrappedUpstream
if err := unmarshal(&c); err != nil { if err := unmarshal(&c); err != nil {
return err return err
} }
*b = BootstrappedUpstreamConfig(c) *b = BootstrappedUpstream(c)
return nil return nil
} }
@ -218,19 +218,19 @@ type Config struct {
Conditional ConditionalUpstream `yaml:"conditional"` Conditional ConditionalUpstream `yaml:"conditional"`
Blocking Blocking `yaml:"blocking"` Blocking Blocking `yaml:"blocking"`
ClientLookup ClientLookup `yaml:"clientLookup"` ClientLookup ClientLookup `yaml:"clientLookup"`
Caching CachingConfig `yaml:"caching"` Caching Caching `yaml:"caching"`
QueryLog QueryLogConfig `yaml:"queryLog"` QueryLog QueryLog `yaml:"queryLog"`
Prometheus MetricsConfig `yaml:"prometheus"` Prometheus Metrics `yaml:"prometheus"`
Redis Redis `yaml:"redis"` Redis Redis `yaml:"redis"`
Log log.Config `yaml:"log"` Log log.Config `yaml:"log"`
Ports PortsConfig `yaml:"ports"` Ports Ports `yaml:"ports"`
MinTLSServeVer TLSVersion `yaml:"minTlsServeVersion" default:"1.2"` MinTLSServeVer TLSVersion `yaml:"minTlsServeVersion" default:"1.2"`
CertFile string `yaml:"certFile"` CertFile string `yaml:"certFile"`
KeyFile string `yaml:"keyFile"` KeyFile string `yaml:"keyFile"`
BootstrapDNS BootstrapDNSConfig `yaml:"bootstrapDns"` BootstrapDNS BootstrapDNS `yaml:"bootstrapDns"`
HostsFile HostsFileConfig `yaml:"hostsFile"` HostsFile HostsFile `yaml:"hostsFile"`
FQDNOnly FQDNOnly `yaml:"fqdnOnly"` FQDNOnly FQDNOnly `yaml:"fqdnOnly"`
Filtering FilteringConfig `yaml:"filtering"` Filtering Filtering `yaml:"filtering"`
EDE EDE `yaml:"ede"` EDE EDE `yaml:"ede"`
ECS ECS `yaml:"ecs"` ECS ECS `yaml:"ecs"`
SUDN SUDN `yaml:"specialUseDomains"` SUDN SUDN `yaml:"specialUseDomains"`
@ -253,40 +253,40 @@ type Config struct {
} `yaml:",inline"` } `yaml:",inline"`
} }
type PortsConfig struct { type Ports struct {
DNS ListenConfig `yaml:"dns" default:"53"` DNS ListenConfig `yaml:"dns" default:"53"`
HTTP ListenConfig `yaml:"http"` HTTP ListenConfig `yaml:"http"`
HTTPS ListenConfig `yaml:"https"` HTTPS ListenConfig `yaml:"https"`
TLS ListenConfig `yaml:"tls"` TLS ListenConfig `yaml:"tls"`
} }
func (c *PortsConfig) LogConfig(logger *logrus.Entry) { func (c *Ports) LogConfig(logger *logrus.Entry) {
logger.Infof("DNS = %s", c.DNS) logger.Infof("DNS = %s", c.DNS)
logger.Infof("TLS = %s", c.TLS) logger.Infof("TLS = %s", c.TLS)
logger.Infof("HTTP = %s", c.HTTP) logger.Infof("HTTP = %s", c.HTTP)
logger.Infof("HTTPS = %s", c.HTTPS) logger.Infof("HTTPS = %s", c.HTTPS)
} }
// split in two types to avoid infinite recursion. See `BootstrapDNSConfig.UnmarshalYAML`. // split in two types to avoid infinite recursion. See `BootstrapDNS.UnmarshalYAML`.
type ( type (
BootstrapDNSConfig bootstrapDNSConfig BootstrapDNS bootstrapDNS
bootstrapDNSConfig []BootstrappedUpstreamConfig bootstrapDNS []BootstrappedUpstream
) )
func (b *BootstrapDNSConfig) IsEnabled() bool { func (b *BootstrapDNS) IsEnabled() bool {
return len(*b) != 0 return len(*b) != 0
} }
func (b *BootstrapDNSConfig) LogConfig(*logrus.Entry) { func (b *BootstrapDNS) LogConfig(*logrus.Entry) {
// This should not be called, at least for now: // This should not be called, at least for now:
// The Boostrap resolver is not in the chain and thus its config is not logged // The Boostrap resolver is not in the chain and thus its config is not logged
panic("not implemented") panic("not implemented")
} }
// split in two types to avoid infinite recursion. See `BootstrappedUpstreamConfig.UnmarshalYAML`. // split in two types to avoid infinite recursion. See `BootstrappedUpstream.UnmarshalYAML`.
type ( type (
BootstrappedUpstreamConfig bootstrappedUpstreamConfig BootstrappedUpstream bootstrappedUpstream
bootstrappedUpstreamConfig struct { bootstrappedUpstream struct {
Upstream Upstream `yaml:"upstream"` Upstream Upstream `yaml:"upstream"`
IPs []net.IP `yaml:"ips"` IPs []net.IP `yaml:"ips"`
} }
@ -319,16 +319,16 @@ func (c *Init) LogConfig(logger *logrus.Entry) {
logger.Debugf("strategy = %s", c.Strategy) logger.Debugf("strategy = %s", c.Strategy)
} }
type SourceLoadingConfig struct { type SourceLoading struct {
Init `yaml:",inline"` Init `yaml:",inline"`
Concurrency uint `yaml:"concurrency" default:"4"` Concurrency uint `yaml:"concurrency" default:"4"`
MaxErrorsPerSource int `yaml:"maxErrorsPerSource" default:"5"` MaxErrorsPerSource int `yaml:"maxErrorsPerSource" default:"5"`
RefreshPeriod Duration `yaml:"refreshPeriod" default:"4h"` RefreshPeriod Duration `yaml:"refreshPeriod" default:"4h"`
Downloads DownloaderConfig `yaml:"downloads"` Downloads Downloader `yaml:"downloads"`
} }
func (c *SourceLoadingConfig) LogConfig(logger *logrus.Entry) { func (c *SourceLoading) LogConfig(logger *logrus.Entry) {
c.Init.LogConfig(logger) c.Init.LogConfig(logger)
logger.Infof("concurrency = %d", c.Concurrency) logger.Infof("concurrency = %d", c.Concurrency)
logger.Debugf("maxErrorsPerSource = %d", c.MaxErrorsPerSource) logger.Debugf("maxErrorsPerSource = %d", c.MaxErrorsPerSource)
@ -343,7 +343,7 @@ func (c *SourceLoadingConfig) LogConfig(logger *logrus.Entry) {
log.WithIndent(logger, " ", c.Downloads.LogConfig) log.WithIndent(logger, " ", c.Downloads.LogConfig)
} }
func (c *SourceLoadingConfig) StartPeriodicRefresh( func (c *SourceLoading) StartPeriodicRefresh(
ctx context.Context, refresh func(context.Context) error, logErr func(error), ctx context.Context, refresh func(context.Context) error, logErr func(error),
) error { ) error {
err := c.Strategy.Do(ctx, refresh, logErr) err := c.Strategy.Do(ctx, refresh, logErr)
@ -358,7 +358,7 @@ func (c *SourceLoadingConfig) StartPeriodicRefresh(
return nil return nil
} }
func (c *SourceLoadingConfig) periodically( func (c *SourceLoading) periodically(
ctx context.Context, refresh func(context.Context) error, logErr func(error), ctx context.Context, refresh func(context.Context) error, logErr func(error),
) { ) {
refresh = recoverToError(refresh, func(panicVal any) error { refresh = recoverToError(refresh, func(panicVal any) error {
@ -394,13 +394,13 @@ func recoverToError(do func(context.Context) error, onPanic func(any) error) fun
} }
} }
type DownloaderConfig struct { type Downloader struct {
Timeout Duration `yaml:"timeout" default:"5s"` Timeout Duration `yaml:"timeout" default:"5s"`
Attempts uint `yaml:"attempts" default:"3"` Attempts uint `yaml:"attempts" default:"3"`
Cooldown Duration `yaml:"cooldown" default:"500ms"` Cooldown Duration `yaml:"cooldown" default:"500ms"`
} }
func (c *DownloaderConfig) LogConfig(logger *logrus.Entry) { func (c *Downloader) LogConfig(logger *logrus.Entry) {
logger.Infof("timeout = %s", c.Timeout) logger.Infof("timeout = %s", c.Timeout)
logger.Infof("attempts = %d", c.Attempts) logger.Infof("attempts = %d", c.Attempts)
logger.Debugf("cooldown = %s", c.Cooldown) logger.Debugf("cooldown = %s", c.Cooldown)

View File

@ -547,10 +547,10 @@ bootstrapDns:
) )
Describe("SourceLoadingConfig", func() { Describe("SourceLoadingConfig", func() {
var cfg SourceLoadingConfig var cfg SourceLoading
BeforeEach(func() { BeforeEach(func() {
cfg = SourceLoadingConfig{ cfg = SourceLoading{
Concurrency: 12, Concurrency: 12,
RefreshPeriod: Duration(time.Hour), RefreshPeriod: Duration(time.Hour),
} }
@ -744,22 +744,22 @@ bootstrapDns:
Describe("BootstrapDNSConfig", func() { Describe("BootstrapDNSConfig", func() {
It("is not enabled when empty", func() { It("is not enabled when empty", func() {
var sut BootstrapDNSConfig var sut BootstrapDNS
Expect(sut.IsEnabled()).Should(BeFalse()) Expect(sut.IsEnabled()).Should(BeFalse())
}) })
It("is enabled if non empty", func() { It("is enabled if non empty", func() {
sut := BootstrapDNSConfig{ sut := BootstrapDNS{
BootstrappedUpstreamConfig{}, BootstrappedUpstream{},
BootstrappedUpstreamConfig{}, BootstrappedUpstream{},
} }
Expect(sut.IsEnabled()).Should(BeTrue()) Expect(sut.IsEnabled()).Should(BeTrue())
}) })
It("LogConfig panics", func() { It("LogConfig panics", func() {
sut := BootstrapDNSConfig{} sut := BootstrapDNS{}
Expect(func() { Expect(func() {
sut.LogConfig(logger) sut.LogConfig(logger)
@ -777,7 +777,7 @@ bootstrapDns:
DeferCleanup(cancelFn) DeferCleanup(cancelFn)
}) })
It("handles panics", func() { It("handles panics", func() {
sut := SourceLoadingConfig{ sut := SourceLoading{
Init: Init{Strategy: InitStrategyFailOnError}, Init: Init{Strategy: InitStrategyFailOnError},
} }
@ -793,7 +793,7 @@ bootstrapDns:
}) })
It("periodically calls refresh", func() { It("periodically calls refresh", func() {
sut := SourceLoadingConfig{ sut := SourceLoading{
Init: Init{Strategy: InitStrategyFast}, Init: Init{Strategy: InitStrategyFast},
RefreshPeriod: Duration(5 * time.Millisecond), RefreshPeriod: Duration(5 * time.Millisecond),
} }

View File

@ -4,17 +4,17 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
type FilteringConfig struct { type Filtering struct {
QueryTypes QTypeSet `yaml:"queryTypes"` QueryTypes QTypeSet `yaml:"queryTypes"`
} }
// IsEnabled implements `config.Configurable`. // IsEnabled implements `config.Configurable`.
func (c *FilteringConfig) IsEnabled() bool { func (c *Filtering) IsEnabled() bool {
return len(c.QueryTypes) != 0 return len(c.QueryTypes) != 0
} }
// LogConfig implements `config.Configurable`. // LogConfig implements `config.Configurable`.
func (c *FilteringConfig) LogConfig(logger *logrus.Entry) { func (c *Filtering) LogConfig(logger *logrus.Entry) {
logger.Info("query types:") logger.Info("query types:")
for qType := range c.QueryTypes { for qType := range c.QueryTypes {

View File

@ -9,19 +9,19 @@ import (
) )
var _ = Describe("FilteringConfig", func() { var _ = Describe("FilteringConfig", func() {
var cfg FilteringConfig var cfg Filtering
suiteBeforeEach() suiteBeforeEach()
BeforeEach(func() { BeforeEach(func() {
cfg = FilteringConfig{ cfg = Filtering{
QueryTypes: NewQTypeSet(AAAA, MX), QueryTypes: NewQTypeSet(AAAA, MX),
} }
}) })
Describe("IsEnabled", func() { Describe("IsEnabled", func() {
It("should be false by default", func() { It("should be false by default", func() {
cfg := FilteringConfig{} cfg := Filtering{}
Expect(defaults.Set(&cfg)).Should(Succeed()) Expect(defaults.Set(&cfg)).Should(Succeed())
Expect(cfg.IsEnabled()).Should(BeFalse()) Expect(cfg.IsEnabled()).Should(BeFalse())
@ -35,7 +35,7 @@ var _ = Describe("FilteringConfig", func() {
When("disabled", func() { When("disabled", func() {
It("should be false", func() { It("should be false", func() {
cfg := FilteringConfig{} cfg := Filtering{}
Expect(cfg.IsEnabled()).Should(BeFalse()) Expect(cfg.IsEnabled()).Should(BeFalse())
}) })

View File

@ -6,11 +6,11 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
type HostsFileConfig struct { type HostsFile struct {
Sources []BytesSource `yaml:"sources"` Sources []BytesSource `yaml:"sources"`
HostsTTL Duration `yaml:"hostsTTL" default:"1h"` HostsTTL Duration `yaml:"hostsTTL" default:"1h"`
FilterLoopback bool `yaml:"filterLoopback"` FilterLoopback bool `yaml:"filterLoopback"`
Loading SourceLoadingConfig `yaml:"loading"` Loading SourceLoading `yaml:"loading"`
// Deprecated options // Deprecated options
Deprecated struct { Deprecated struct {
@ -19,7 +19,7 @@ type HostsFileConfig struct {
} `yaml:",inline"` } `yaml:",inline"`
} }
func (c *HostsFileConfig) migrate(logger *logrus.Entry) bool { func (c *HostsFile) migrate(logger *logrus.Entry) bool {
return Migrate(logger, "hostsFile", c.Deprecated, map[string]Migrator{ return Migrate(logger, "hostsFile", c.Deprecated, map[string]Migrator{
"refreshPeriod": Move(To("loading.refreshPeriod", &c.Loading)), "refreshPeriod": Move(To("loading.refreshPeriod", &c.Loading)),
"filePath": Apply(To("sources", c), func(value BytesSource) { "filePath": Apply(To("sources", c), func(value BytesSource) {
@ -29,12 +29,12 @@ func (c *HostsFileConfig) migrate(logger *logrus.Entry) bool {
} }
// IsEnabled implements `config.Configurable`. // IsEnabled implements `config.Configurable`.
func (c *HostsFileConfig) IsEnabled() bool { func (c *HostsFile) IsEnabled() bool {
return len(c.Sources) != 0 return len(c.Sources) != 0
} }
// LogConfig implements `config.Configurable`. // LogConfig implements `config.Configurable`.
func (c *HostsFileConfig) LogConfig(logger *logrus.Entry) { func (c *HostsFile) LogConfig(logger *logrus.Entry) {
logger.Infof("TTL: %s", c.HostsTTL) logger.Infof("TTL: %s", c.HostsTTL)
logger.Infof("filter loopback addresses: %t", c.FilterLoopback) logger.Infof("filter loopback addresses: %t", c.FilterLoopback)

View File

@ -9,25 +9,25 @@ import (
) )
var _ = Describe("HostsFileConfig", func() { var _ = Describe("HostsFileConfig", func() {
var cfg HostsFileConfig var cfg HostsFile
suiteBeforeEach() suiteBeforeEach()
BeforeEach(func() { BeforeEach(func() {
cfg = HostsFileConfig{ cfg = HostsFile{
Sources: append( Sources: append(
NewBytesSources("/a/file/path"), NewBytesSources("/a/file/path"),
TextBytesSource("127.0.0.1 localhost"), TextBytesSource("127.0.0.1 localhost"),
), ),
HostsTTL: Duration(29 * time.Minute), HostsTTL: Duration(29 * time.Minute),
Loading: SourceLoadingConfig{RefreshPeriod: Duration(30 * time.Minute)}, Loading: SourceLoading{RefreshPeriod: Duration(30 * time.Minute)},
FilterLoopback: true, FilterLoopback: true,
} }
}) })
Describe("IsEnabled", func() { Describe("IsEnabled", func() {
It("should be false by default", func() { It("should be false by default", func() {
cfg := HostsFileConfig{} cfg := HostsFile{}
Expect(defaults.Set(&cfg)).Should(Succeed()) Expect(defaults.Set(&cfg)).Should(Succeed())
Expect(cfg.IsEnabled()).Should(BeFalse()) Expect(cfg.IsEnabled()).Should(BeFalse())
@ -41,7 +41,7 @@ var _ = Describe("HostsFileConfig", func() {
When("disabled", func() { When("disabled", func() {
It("should be false", func() { It("should be false", func() {
cfg := HostsFileConfig{} cfg := HostsFile{}
Expect(cfg.IsEnabled()).Should(BeFalse()) Expect(cfg.IsEnabled()).Should(BeFalse())
}) })
@ -62,7 +62,7 @@ var _ = Describe("HostsFileConfig", func() {
Describe("migrate", func() { Describe("migrate", func() {
It("should", func() { It("should", func() {
cfg, err := WithDefaults[HostsFileConfig]() cfg, err := WithDefaults[HostsFile]()
Expect(err).Should(Succeed()) Expect(err).Should(Succeed())
cfg.Deprecated.Filepath = ptrOf(newBytesSource("/a/file/path")) cfg.Deprecated.Filepath = ptrOf(newBytesSource("/a/file/path"))

View File

@ -2,18 +2,18 @@ package config
import "github.com/sirupsen/logrus" import "github.com/sirupsen/logrus"
// MetricsConfig contains the config values for prometheus // Metrics contains the config values for prometheus
type MetricsConfig struct { type Metrics struct {
Enable bool `yaml:"enable" default:"false"` Enable bool `yaml:"enable" default:"false"`
Path string `yaml:"path" default:"/metrics"` Path string `yaml:"path" default:"/metrics"`
} }
// IsEnabled implements `config.Configurable`. // IsEnabled implements `config.Configurable`.
func (c *MetricsConfig) IsEnabled() bool { func (c *Metrics) IsEnabled() bool {
return c.Enable return c.Enable
} }
// LogConfig implements `config.Configurable`. // LogConfig implements `config.Configurable`.
func (c *MetricsConfig) LogConfig(logger *logrus.Entry) { func (c *Metrics) LogConfig(logger *logrus.Entry) {
logger.Infof("url path: %s", c.Path) logger.Infof("url path: %s", c.Path)
} }

View File

@ -7,12 +7,12 @@ import (
) )
var _ = Describe("MetricsConfig", func() { var _ = Describe("MetricsConfig", func() {
var cfg MetricsConfig var cfg Metrics
suiteBeforeEach() suiteBeforeEach()
BeforeEach(func() { BeforeEach(func() {
cfg = MetricsConfig{ cfg = Metrics{
Enable: true, Enable: true,
Path: "/custom/path", Path: "/custom/path",
} }
@ -20,7 +20,7 @@ var _ = Describe("MetricsConfig", func() {
Describe("IsEnabled", func() { Describe("IsEnabled", func() {
It("should be false by default", func() { It("should be false by default", func() {
cfg := MetricsConfig{} cfg := Metrics{}
Expect(defaults.Set(&cfg)).Should(Succeed()) Expect(defaults.Set(&cfg)).Should(Succeed())
Expect(cfg.IsEnabled()).Should(BeFalse()) Expect(cfg.IsEnabled()).Should(BeFalse())
@ -34,7 +34,7 @@ var _ = Describe("MetricsConfig", func() {
When("disabled", func() { When("disabled", func() {
It("should be false", func() { It("should be false", func() {
cfg := MetricsConfig{} cfg := Metrics{}
Expect(cfg.IsEnabled()).Should(BeFalse()) Expect(cfg.IsEnabled()).Should(BeFalse())
}) })

View File

@ -4,8 +4,8 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
// QueryLogConfig configuration for the query logging // QueryLog configuration for the query logging
type QueryLogConfig struct { type QueryLog struct {
Target string `yaml:"target"` Target string `yaml:"target"`
Type QueryLogType `yaml:"type"` Type QueryLogType `yaml:"type"`
LogRetentionDays uint64 `yaml:"logRetentionDays"` LogRetentionDays uint64 `yaml:"logRetentionDays"`
@ -16,19 +16,19 @@ type QueryLogConfig struct {
} }
// SetDefaults implements `defaults.Setter`. // SetDefaults implements `defaults.Setter`.
func (c *QueryLogConfig) SetDefaults() { func (c *QueryLog) SetDefaults() {
// Since the default depends on the enum values, set it dynamically // Since the default depends on the enum values, set it dynamically
// to avoid having to repeat the values in the annotation. // to avoid having to repeat the values in the annotation.
c.Fields = QueryLogFieldValues() c.Fields = QueryLogFieldValues()
} }
// IsEnabled implements `config.Configurable`. // IsEnabled implements `config.Configurable`.
func (c *QueryLogConfig) IsEnabled() bool { func (c *QueryLog) IsEnabled() bool {
return c.Type != QueryLogTypeNone return c.Type != QueryLogTypeNone
} }
// LogConfig implements `config.Configurable`. // LogConfig implements `config.Configurable`.
func (c *QueryLogConfig) LogConfig(logger *logrus.Entry) { func (c *QueryLog) LogConfig(logger *logrus.Entry) {
logger.Infof("type: %s", c.Type) logger.Infof("type: %s", c.Type)
if c.Target != "" { if c.Target != "" {

View File

@ -9,12 +9,12 @@ import (
) )
var _ = Describe("QueryLogConfig", func() { var _ = Describe("QueryLogConfig", func() {
var cfg QueryLogConfig var cfg QueryLog
suiteBeforeEach() suiteBeforeEach()
BeforeEach(func() { BeforeEach(func() {
cfg = QueryLogConfig{ cfg = QueryLog{
Target: "/dev/null", Target: "/dev/null",
Type: QueryLogTypeCsvClient, Type: QueryLogTypeCsvClient,
LogRetentionDays: 0, LogRetentionDays: 0,
@ -25,7 +25,7 @@ var _ = Describe("QueryLogConfig", func() {
Describe("IsEnabled", func() { Describe("IsEnabled", func() {
It("should be true by default", func() { It("should be true by default", func() {
cfg := QueryLogConfig{} cfg := QueryLog{}
Expect(defaults.Set(&cfg)).Should(Succeed()) Expect(defaults.Set(&cfg)).Should(Succeed())
Expect(cfg.IsEnabled()).Should(BeTrue()) Expect(cfg.IsEnabled()).Should(BeTrue())
@ -39,7 +39,7 @@ var _ = Describe("QueryLogConfig", func() {
When("disabled", func() { When("disabled", func() {
It("should be false", func() { It("should be false", func() {
cfg := QueryLogConfig{ cfg := QueryLog{
Type: QueryLogTypeNone, Type: QueryLogTypeNone,
} }
@ -59,7 +59,7 @@ var _ = Describe("QueryLogConfig", func() {
Describe("SetDefaults", func() { Describe("SetDefaults", func() {
It("should log configuration", func() { It("should log configuration", func() {
cfg := QueryLogConfig{} cfg := QueryLog{}
Expect(cfg.Fields).Should(BeEmpty()) Expect(cfg.Fields).Should(BeEmpty())
Expect(defaults.Set(&cfg)).Should(Succeed()) Expect(defaults.Set(&cfg)).Should(Succeed())

View File

@ -33,16 +33,16 @@ type FileDownloader interface {
// httpDownloader downloads files via HTTP protocol // httpDownloader downloads files via HTTP protocol
type httpDownloader struct { type httpDownloader struct {
cfg config.DownloaderConfig cfg config.Downloader
client http.Client client http.Client
} }
func NewDownloader(cfg config.DownloaderConfig, transport http.RoundTripper) FileDownloader { func NewDownloader(cfg config.Downloader, transport http.RoundTripper) FileDownloader {
return newDownloader(cfg, transport) return newDownloader(cfg, transport)
} }
func newDownloader(cfg config.DownloaderConfig, transport http.RoundTripper) *httpDownloader { func newDownloader(cfg config.Downloader, transport http.RoundTripper) *httpDownloader {
return &httpDownloader{ return &httpDownloader{
cfg: cfg, cfg: cfg,

View File

@ -22,7 +22,7 @@ import (
var _ = Describe("Downloader", func() { var _ = Describe("Downloader", func() {
var ( var (
sutConfig config.DownloaderConfig sutConfig config.Downloader
sut *httpDownloader sut *httpDownloader
failedDownloadCountEvtChannel chan string failedDownloadCountEvtChannel chan string
loggerHook *test.Hook loggerHook *test.Hook
@ -30,7 +30,7 @@ var _ = Describe("Downloader", func() {
BeforeEach(func() { BeforeEach(func() {
var err error var err error
sutConfig, err = config.WithDefaults[config.DownloaderConfig]() sutConfig, err = config.WithDefaults[config.Downloader]()
Expect(err).Should(Succeed()) Expect(err).Should(Succeed())
failedDownloadCountEvtChannel = make(chan string, 5) failedDownloadCountEvtChannel = make(chan string, 5)
@ -57,7 +57,7 @@ var _ = Describe("Downloader", func() {
transport := &http.Transport{} transport := &http.Transport{}
sut = NewDownloader( sut = NewDownloader(
config.DownloaderConfig{ config.Downloader{
Attempts: 5, Attempts: 5,
Cooldown: config.Duration(2 * time.Second), Cooldown: config.Duration(2 * time.Second),
Timeout: config.Duration(5 * time.Second), Timeout: config.Duration(5 * time.Second),
@ -128,7 +128,7 @@ var _ = Describe("Downloader", func() {
var attempt uint64 = 1 var attempt uint64 = 1
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.DownloaderConfig{ sutConfig = config.Downloader{
Timeout: config.Duration(20 * time.Millisecond), Timeout: config.Duration(20 * time.Millisecond),
Attempts: 3, Attempts: 3,
Cooldown: config.Duration(time.Millisecond), Cooldown: config.Duration(time.Millisecond),
@ -165,7 +165,7 @@ var _ = Describe("Downloader", func() {
}) })
When("If timeout occurs on all request", func() { When("If timeout occurs on all request", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.DownloaderConfig{ sutConfig = config.Downloader{
Timeout: config.Duration(10 * time.Millisecond), Timeout: config.Duration(10 * time.Millisecond),
Attempts: 3, Attempts: 3,
Cooldown: config.Duration(time.Millisecond), Cooldown: config.Duration(time.Millisecond),
@ -191,7 +191,7 @@ var _ = Describe("Downloader", func() {
}) })
When("DNS resolution of passed URL fails", func() { When("DNS resolution of passed URL fails", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.DownloaderConfig{ sutConfig = config.Downloader{
Timeout: config.Duration(500 * time.Millisecond), Timeout: config.Duration(500 * time.Millisecond),
Attempts: 3, Attempts: 3,
Cooldown: 200 * config.Duration(time.Millisecond), Cooldown: 200 * config.Duration(time.Millisecond),

View File

@ -40,7 +40,7 @@ type ListCache struct {
groupedCache stringcache.GroupedStringCache groupedCache stringcache.GroupedStringCache
regexCache stringcache.GroupedStringCache regexCache stringcache.GroupedStringCache
cfg config.SourceLoadingConfig cfg config.SourceLoading
listType ListCacheType listType ListCacheType
groupSources map[string][]config.BytesSource groupSources map[string][]config.BytesSource
downloader FileDownloader downloader FileDownloader
@ -70,7 +70,7 @@ func (b *ListCache) LogConfig(logger *logrus.Entry) {
// NewListCache creates new list instance // NewListCache creates new list instance
func NewListCache(ctx context.Context, func NewListCache(ctx context.Context,
t ListCacheType, cfg config.SourceLoadingConfig, t ListCacheType, cfg config.SourceLoading,
groupSources map[string][]config.BytesSource, downloader FileDownloader, groupSources map[string][]config.BytesSource, downloader FileDownloader,
) (*ListCache, error) { ) (*ListCache, error) {
regexCache := stringcache.NewInMemoryGroupedRegexCache() regexCache := stringcache.NewInMemoryGroupedRegexCache()

View File

@ -15,11 +15,11 @@ func BenchmarkRefresh(b *testing.B) {
"gr1": config.NewBytesSources(file1, file2, file3), "gr1": config.NewBytesSources(file1, file2, file3),
} }
cfg := config.SourceLoadingConfig{ cfg := config.SourceLoading{
Concurrency: 5, Concurrency: 5,
RefreshPeriod: config.Duration(-1), RefreshPeriod: config.Duration(-1),
} }
downloader := NewDownloader(config.DownloaderConfig{}, nil) downloader := NewDownloader(config.Downloader{}, nil)
cache, _ := NewListCache(context.Background(), ListCacheTypeBlacklist, cfg, lists, downloader) cache, _ := NewListCache(context.Background(), ListCacheTypeBlacklist, cfg, lists, downloader)
b.ReportAllocs() b.ReportAllocs()

View File

@ -29,7 +29,7 @@ var _ = Describe("ListCache", func() {
server1, server2, server3 *httptest.Server server1, server2, server3 *httptest.Server
sut *ListCache sut *ListCache
sutConfig config.SourceLoadingConfig sutConfig config.SourceLoading
listCacheType ListCacheType listCacheType ListCacheType
lists map[string][]config.BytesSource lists map[string][]config.BytesSource
@ -48,12 +48,12 @@ var _ = Describe("ListCache", func() {
listCacheType = ListCacheTypeBlacklist listCacheType = ListCacheTypeBlacklist
sutConfig, err = config.WithDefaults[config.SourceLoadingConfig]() sutConfig, err = config.WithDefaults[config.SourceLoading]()
Expect(err).Should(Succeed()) Expect(err).Should(Succeed())
sutConfig.RefreshPeriod = -1 sutConfig.RefreshPeriod = -1
downloader = NewDownloader(config.DownloaderConfig{}, nil) downloader = NewDownloader(config.Downloader{}, nil)
mockDownloader = nil mockDownloader = nil
server1 = TestServer("blocked1.com\nblocked1a.com\n192.168.178.55") server1 = TestServer("blocked1.com\nblocked1a.com\n192.168.178.55")

View File

@ -18,7 +18,7 @@ func RegisterMetric(c prometheus.Collector) {
} }
// Start starts prometheus endpoint // Start starts prometheus endpoint
func Start(router *chi.Mux, cfg config.MetricsConfig) { func Start(router *chi.Mux, cfg config.Metrics) {
if cfg.Enable { if cfg.Enable {
_ = reg.Register(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})) _ = reg.Register(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
_ = reg.Register(collectors.NewGoCollector()) _ = reg.Register(collectors.NewGoCollector())

View File

@ -170,7 +170,7 @@ var _ = Describe("BlockingResolver", Label("blockingResolver"), func() {
ClientGroupsBlock: map[string][]string{ ClientGroupsBlock: map[string][]string{
"default": {"gr1"}, "default": {"gr1"},
}, },
Loading: config.SourceLoadingConfig{ Loading: config.SourceLoading{
Init: config.Init{Strategy: config.InitStrategyFast}, Init: config.Init{Strategy: config.InitStrategyFast},
}, },
} }
@ -1126,7 +1126,7 @@ var _ = Describe("BlockingResolver", Label("blockingResolver"), func() {
_, err := NewBlockingResolver(ctx, config.Blocking{ _, err := NewBlockingResolver(ctx, config.Blocking{
BlackLists: map[string][]config.BytesSource{"gr1": config.NewBytesSources("wrongPath")}, BlackLists: map[string][]config.BytesSource{"gr1": config.NewBytesSources("wrongPath")},
WhiteLists: map[string][]config.BytesSource{"whitelist": config.NewBytesSources("wrongPath")}, WhiteLists: map[string][]config.BytesSource{"whitelist": config.NewBytesSources("wrongPath")},
Loading: config.SourceLoadingConfig{ Loading: config.SourceLoading{
Init: config.Init{Strategy: config.InitStrategyFailOnError}, Init: config.Init{Strategy: config.InitStrategyFailOnError},
}, },
BlockType: "zeroIp", BlockType: "zeroIp",

View File

@ -26,7 +26,7 @@ var errArbitrarySystemResolverRequest = errors.New(
) )
type bootstrapConfig struct { type bootstrapConfig struct {
config.BootstrapDNSConfig config.BootstrapDNS
connectIPVersion config.IPVersion connectIPVersion config.IPVersion
timeout config.Duration timeout config.Duration
@ -34,7 +34,7 @@ type bootstrapConfig struct {
func newBootstrapConfig(cfg *config.Config) *bootstrapConfig { func newBootstrapConfig(cfg *config.Config) *bootstrapConfig {
return &bootstrapConfig{ return &bootstrapConfig{
BootstrapDNSConfig: cfg.BootstrapDNS, BootstrapDNS: cfg.BootstrapDNS,
connectIPVersion: cfg.ConnectIPVersion, connectIPVersion: cfg.ConnectIPVersion,
timeout: cfg.Upstreams.Timeout, timeout: cfg.Upstreams.Timeout,
@ -266,7 +266,7 @@ func (b *Bootstrap) resolveType(ctx context.Context, hostname string, qType dns.
type bootstrapedResolvers map[Resolver][]net.IP type bootstrapedResolvers map[Resolver][]net.IP
func newBootstrapedResolvers( func newBootstrapedResolvers(
b *Bootstrap, cfg config.BootstrapDNSConfig, upstreamsCfg config.Upstreams, b *Bootstrap, cfg config.BootstrapDNS, upstreamsCfg config.Upstreams,
) (bootstrapedResolvers, error) { ) (bootstrapedResolvers, error) {
upstreamIPs := make(bootstrapedResolvers, len(cfg)) upstreamIPs := make(bootstrapedResolvers, len(cfg))

View File

@ -34,7 +34,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.Config{ sutConfig = config.Config{
BootstrapDNS: []config.BootstrappedUpstreamConfig{ BootstrapDNS: []config.BootstrappedUpstream{
{ {
Upstream: config.Upstream{ Upstream: config.Upstream{
Net: config.NetProtocolTcpTls, Net: config.NetProtocolTcpTls,
@ -58,7 +58,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
Describe("configuration", func() { Describe("configuration", func() {
When("is not specified", func() { When("is not specified", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig.BootstrapDNS = config.BootstrapDNSConfig{} sutConfig.BootstrapDNS = config.BootstrapDNS{}
}) })
It("should use the system resolver", func() { It("should use the system resolver", func() {
@ -89,7 +89,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
When("one of multiple upstreams is invalid", func() { When("one of multiple upstreams is invalid", func() {
It("errors", func() { It("errors", func() {
cfg := config.Config{ cfg := config.Config{
BootstrapDNS: []config.BootstrappedUpstreamConfig{ BootstrapDNS: []config.BootstrappedUpstream{
{ {
Upstream: config.Upstream{ // valid Upstream: config.Upstream{ // valid
Net: config.NetProtocolTcpUdp, Net: config.NetProtocolTcpUdp,
@ -115,7 +115,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
When("hostname is an IP", func() { When("hostname is an IP", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.Config{ sutConfig = config.Config{
BootstrapDNS: []config.BootstrappedUpstreamConfig{ BootstrapDNS: []config.BootstrappedUpstream{
{ {
Upstream: config.Upstream{ Upstream: config.Upstream{
Net: config.NetProtocolTcpUdp, Net: config.NetProtocolTcpUdp,
@ -137,7 +137,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
When("using non IP hostname", func() { When("using non IP hostname", func() {
It("errors", func() { It("errors", func() {
cfg := config.Config{ cfg := config.Config{
BootstrapDNS: []config.BootstrappedUpstreamConfig{ BootstrapDNS: []config.BootstrappedUpstream{
{ {
Upstream: config.Upstream{ Upstream: config.Upstream{
Net: config.NetProtocolTcpUdp, Net: config.NetProtocolTcpUdp,
@ -156,7 +156,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
When("extra IPs are configured", func() { When("extra IPs are configured", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.Config{ sutConfig = config.Config{
BootstrapDNS: []config.BootstrappedUpstreamConfig{ BootstrapDNS: []config.BootstrappedUpstream{
{ {
Upstream: config.Upstream{ Upstream: config.Upstream{
Net: config.NetProtocolTcpUdp, Net: config.NetProtocolTcpUdp,
@ -181,7 +181,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
When("IPs are missing", func() { When("IPs are missing", func() {
It("errors", func() { It("errors", func() {
cfg := config.Config{ cfg := config.Config{
BootstrapDNS: []config.BootstrappedUpstreamConfig{ BootstrapDNS: []config.BootstrappedUpstream{
{ {
Upstream: config.Upstream{ Upstream: config.Upstream{
Net: config.NetProtocolTcpTls, Net: config.NetProtocolTcpTls,
@ -200,7 +200,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
When("hostname is IP", func() { When("hostname is IP", func() {
It("doesn't require extra IPs", func() { It("doesn't require extra IPs", func() {
cfg := config.Config{ cfg := config.Config{
BootstrapDNS: []config.BootstrappedUpstreamConfig{ BootstrapDNS: []config.BootstrappedUpstream{
{ {
Upstream: config.Upstream{ Upstream: config.Upstream{
Net: config.NetProtocolTcpTls, Net: config.NetProtocolTcpTls,
@ -223,7 +223,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
BeforeEach(func() { BeforeEach(func() {
bootstrapUpstream = &mockResolver{} bootstrapUpstream = &mockResolver{}
sutConfig.BootstrapDNS = []config.BootstrappedUpstreamConfig{ sutConfig.BootstrapDNS = []config.BootstrappedUpstream{
{ {
Upstream: config.Upstream{ Upstream: config.Upstream{
Net: config.NetProtocolTcpTls, Net: config.NetProtocolTcpTls,
@ -596,7 +596,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
mockUpstream1 = NewMockUDPUpstreamServer().WithAnswerRR("example.com 123 IN A 123.124.122.122") mockUpstream1 = NewMockUDPUpstreamServer().WithAnswerRR("example.com 123 IN A 123.124.122.122")
mockUpstream2 = NewMockUDPUpstreamServer().WithAnswerRR("example.com 123 IN A 123.124.122.122") mockUpstream2 = NewMockUDPUpstreamServer().WithAnswerRR("example.com 123 IN A 123.124.122.122")
sutConfig.BootstrapDNS = []config.BootstrappedUpstreamConfig{ sutConfig.BootstrapDNS = []config.BootstrappedUpstream{
{Upstream: mockUpstream1.Start()}, {Upstream: mockUpstream1.Start()},
{Upstream: mockUpstream2.Start()}, {Upstream: mockUpstream2.Start()},
} }

View File

@ -24,7 +24,7 @@ const defaultCachingCleanUpInterval = 5 * time.Second
// CachingResolver caches answers from dns queries with their TTL time, // CachingResolver caches answers from dns queries with their TTL time,
// to avoid external resolver calls for recurrent queries // to avoid external resolver calls for recurrent queries
type CachingResolver struct { type CachingResolver struct {
configurable[*config.CachingConfig] configurable[*config.Caching]
NextResolver NextResolver
typed typed
@ -37,14 +37,14 @@ type CachingResolver struct {
// NewCachingResolver creates a new resolver instance // NewCachingResolver creates a new resolver instance
func NewCachingResolver(ctx context.Context, func NewCachingResolver(ctx context.Context,
cfg config.CachingConfig, cfg config.Caching,
redis *redis.Client, redis *redis.Client,
) *CachingResolver { ) *CachingResolver {
return newCachingResolver(ctx, cfg, redis, true) return newCachingResolver(ctx, cfg, redis, true)
} }
func newCachingResolver(ctx context.Context, func newCachingResolver(ctx context.Context,
cfg config.CachingConfig, cfg config.Caching,
redis *redis.Client, redis *redis.Client,
emitMetricEvents bool, emitMetricEvents bool,
) *CachingResolver { ) *CachingResolver {
@ -66,7 +66,7 @@ func newCachingResolver(ctx context.Context,
return c return c
} }
func configureCaches(ctx context.Context, c *CachingResolver, cfg *config.CachingConfig) { func configureCaches(ctx context.Context, c *CachingResolver, cfg *config.Caching) {
options := expirationcache.Options{ options := expirationcache.Options{
CleanupInterval: defaultCachingCleanUpInterval, CleanupInterval: defaultCachingCleanUpInterval,
MaxSize: uint(cfg.MaxItemsCount), MaxSize: uint(cfg.MaxItemsCount),

View File

@ -25,7 +25,7 @@ import (
var _ = Describe("CachingResolver", func() { var _ = Describe("CachingResolver", func() {
var ( var (
sut *CachingResolver sut *CachingResolver
sutConfig config.CachingConfig sutConfig config.Caching
m *mockResolver m *mockResolver
mockAnswer *dns.Msg mockAnswer *dns.Msg
ctx context.Context ctx context.Context
@ -39,7 +39,7 @@ var _ = Describe("CachingResolver", func() {
}) })
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.CachingConfig{} sutConfig = config.Caching{}
if err := defaults.Set(&sutConfig); err != nil { if err := defaults.Set(&sutConfig); err != nil {
panic(err) panic(err)
} }
@ -63,7 +63,7 @@ var _ = Describe("CachingResolver", func() {
When("max caching time is negative", func() { When("max caching time is negative", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.CachingConfig{ sutConfig = config.Caching{
MaxCachingTime: config.Duration(time.Minute * -1), MaxCachingTime: config.Duration(time.Minute * -1),
} }
}) })
@ -86,7 +86,7 @@ var _ = Describe("CachingResolver", func() {
Describe("Caching responses", func() { Describe("Caching responses", func() {
When("prefetching is enabled", func() { When("prefetching is enabled", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.CachingConfig{ sutConfig = config.Caching{
Prefetching: true, Prefetching: true,
PrefetchExpires: config.Duration(time.Minute * 120), PrefetchExpires: config.Duration(time.Minute * 120),
PrefetchThreshold: 5, PrefetchThreshold: 5,
@ -198,7 +198,7 @@ var _ = Describe("CachingResolver", func() {
}) })
When("min caching time is defined", func() { When("min caching time is defined", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.CachingConfig{ sutConfig = config.Caching{
MinCachingTime: config.Duration(time.Minute * 5), MinCachingTime: config.Duration(time.Minute * 5),
} }
}) })
@ -341,7 +341,7 @@ var _ = Describe("CachingResolver", func() {
}) })
Context("max caching time is negative -> caching is disabled", func() { Context("max caching time is negative -> caching is disabled", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.CachingConfig{ sutConfig = config.Caching{
MaxCachingTime: config.Duration(time.Minute * -1), MaxCachingTime: config.Duration(time.Minute * -1),
} }
}) })
@ -378,7 +378,7 @@ var _ = Describe("CachingResolver", func() {
Context("max caching time is positive", func() { Context("max caching time is positive", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.CachingConfig{ sutConfig = config.Caching{
MaxCachingTime: config.Duration(time.Minute * 4), MaxCachingTime: config.Duration(time.Minute * 4),
} }
}) })
@ -419,7 +419,7 @@ var _ = Describe("CachingResolver", func() {
}) })
Context("max caching time is defined", func() { Context("max caching time is defined", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.CachingConfig{ sutConfig = config.Caching{
MaxCachingTime: config.Duration(time.Minute * 1), MaxCachingTime: config.Duration(time.Minute * 1),
} }
}) })
@ -500,7 +500,7 @@ var _ = Describe("CachingResolver", func() {
When("Upstream resolver returns NXDOMAIN without caching", func() { When("Upstream resolver returns NXDOMAIN without caching", func() {
BeforeEach(func() { BeforeEach(func() {
mockAnswer.Rcode = dns.RcodeNameError mockAnswer.Rcode = dns.RcodeNameError
sutConfig = config.CachingConfig{ sutConfig = config.Caching{
CacheTimeNegative: config.Duration(time.Minute * -1), CacheTimeNegative: config.Duration(time.Minute * -1),
} }
}) })
@ -758,7 +758,7 @@ var _ = Describe("CachingResolver", func() {
}) })
When("cache", func() { When("cache", func() {
JustBeforeEach(func() { JustBeforeEach(func() {
sutConfig = config.CachingConfig{ sutConfig = config.Caching{
MaxCachingTime: config.Duration(time.Second * 10), MaxCachingTime: config.Duration(time.Second * 10),
} }
mockAnswer, _ = util.NewMsgWithAnswer("example.com.", 1000, A, "1.1.1.1") mockAnswer, _ = util.NewMsgWithAnswer("example.com.", 1000, A, "1.1.1.1")

View File

@ -11,12 +11,12 @@ import (
// FilteringResolver filters DNS queries (for example can drop all AAAA query) // FilteringResolver filters DNS queries (for example can drop all AAAA query)
// returns empty ANSWER with NOERROR // returns empty ANSWER with NOERROR
type FilteringResolver struct { type FilteringResolver struct {
configurable[*config.FilteringConfig] configurable[*config.Filtering]
NextResolver NextResolver
typed typed
} }
func NewFilteringResolver(cfg config.FilteringConfig) *FilteringResolver { func NewFilteringResolver(cfg config.Filtering) *FilteringResolver {
return &FilteringResolver{ return &FilteringResolver{
configurable: withConfig(&cfg), configurable: withConfig(&cfg),
typed: withType("filtering"), typed: withType("filtering"),

View File

@ -17,7 +17,7 @@ import (
var _ = Describe("FilteringResolver", func() { var _ = Describe("FilteringResolver", func() {
var ( var (
sut *FilteringResolver sut *FilteringResolver
sutConfig config.FilteringConfig sutConfig config.Filtering
m *mockResolver m *mockResolver
mockAnswer *dns.Msg mockAnswer *dns.Msg
@ -63,7 +63,7 @@ var _ = Describe("FilteringResolver", func() {
When("Filtering query types are defined", func() { When("Filtering query types are defined", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.FilteringConfig{ sutConfig = config.Filtering{
QueryTypes: config.NewQTypeSet(AAAA, MX), QueryTypes: config.NewQTypeSet(AAAA, MX),
} }
}) })
@ -95,7 +95,7 @@ var _ = Describe("FilteringResolver", func() {
When("No filtering query types are defined", func() { When("No filtering query types are defined", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.FilteringConfig{} sutConfig = config.Filtering{}
}) })
It("Should return empty answer without error", func() { It("Should return empty answer without error", func() {
Expect(sut.Resolve(ctx, newRequest("example.com.", AAAA))). Expect(sut.Resolve(ctx, newRequest("example.com.", AAAA))).

View File

@ -26,7 +26,7 @@ const (
type HostsFileEntry = parsers.HostsFileEntry type HostsFileEntry = parsers.HostsFileEntry
type HostsFileResolver struct { type HostsFileResolver struct {
configurable[*config.HostsFileConfig] configurable[*config.HostsFile]
NextResolver NextResolver
typed typed
@ -35,7 +35,7 @@ type HostsFileResolver struct {
} }
func NewHostsFileResolver(ctx context.Context, func NewHostsFileResolver(ctx context.Context,
cfg config.HostsFileConfig, cfg config.HostsFile,
bootstrap *Bootstrap, bootstrap *Bootstrap,
) (*HostsFileResolver, error) { ) (*HostsFileResolver, error) {
r := HostsFileResolver{ r := HostsFileResolver{

View File

@ -19,7 +19,7 @@ var _ = Describe("HostsFileResolver", func() {
TTL = uint32(time.Now().Second()) TTL = uint32(time.Now().Second())
sut *HostsFileResolver sut *HostsFileResolver
sutConfig config.HostsFileConfig sutConfig config.HostsFile
m *mockResolver m *mockResolver
tmpDir *TmpFolder tmpDir *TmpFolder
tmpFile *TmpFile tmpFile *TmpFile
@ -43,11 +43,11 @@ var _ = Describe("HostsFileResolver", func() {
tmpDir = NewTmpFolder("HostsFileResolver") tmpDir = NewTmpFolder("HostsFileResolver")
tmpFile = writeHostFile(tmpDir) tmpFile = writeHostFile(tmpDir)
sutConfig = config.HostsFileConfig{ sutConfig = config.HostsFile{
Sources: config.NewBytesSources(tmpFile.Path), Sources: config.NewBytesSources(tmpFile.Path),
HostsTTL: config.Duration(time.Duration(TTL) * time.Second), HostsTTL: config.Duration(time.Duration(TTL) * time.Second),
FilterLoopback: true, FilterLoopback: true,
Loading: config.SourceLoadingConfig{ Loading: config.SourceLoading{
RefreshPeriod: -1, RefreshPeriod: -1,
MaxErrorsPerSource: 5, MaxErrorsPerSource: 5,
}, },
@ -82,7 +82,7 @@ var _ = Describe("HostsFileResolver", func() {
Describe("Using hosts file", func() { Describe("Using hosts file", func() {
When("Hosts file cannot be located", func() { When("Hosts file cannot be located", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.HostsFileConfig{ sutConfig = config.HostsFile{
Sources: config.NewBytesSources("/this/file/does/not/exist"), Sources: config.NewBytesSources("/this/file/does/not/exist"),
HostsTTL: config.Duration(time.Duration(TTL) * time.Second), HostsTTL: config.Duration(time.Duration(TTL) * time.Second),
} }

View File

@ -15,7 +15,7 @@ import (
// MetricsResolver resolver that records metrics about requests/response // MetricsResolver resolver that records metrics about requests/response
type MetricsResolver struct { type MetricsResolver struct {
configurable[*config.MetricsConfig] configurable[*config.Metrics]
NextResolver NextResolver
typed typed
@ -59,7 +59,7 @@ func (r *MetricsResolver) Resolve(ctx context.Context, request *model.Request) (
} }
// NewMetricsResolver creates a new intance of the MetricsResolver type // NewMetricsResolver creates a new intance of the MetricsResolver type
func NewMetricsResolver(cfg config.MetricsConfig) *MetricsResolver { func NewMetricsResolver(cfg config.Metrics) *MetricsResolver {
m := MetricsResolver{ m := MetricsResolver{
configurable: withConfig(&cfg), configurable: withConfig(&cfg),
typed: withType("metrics"), typed: withType("metrics"),

View File

@ -37,7 +37,7 @@ var _ = Describe("MetricResolver", func() {
ctx, cancelFn = context.WithCancel(context.Background()) ctx, cancelFn = context.WithCancel(context.Background())
DeferCleanup(cancelFn) DeferCleanup(cancelFn)
sut = NewMetricsResolver(config.MetricsConfig{Enable: true}) sut = NewMetricsResolver(config.Metrics{Enable: true})
m = &mockResolver{} m = &mockResolver{}
m.On("Resolve", mock.Anything).Return(&Response{Res: new(dns.Msg)}, nil) m.On("Resolve", mock.Anything).Return(&Response{Res: new(dns.Msg)}, nil)
sut.Next(m) sut.Next(m)

View File

@ -128,7 +128,7 @@ ips:
bootstrapUpstream := &mockResolver{} bootstrapUpstream := &mockResolver{}
var bCfg config.BootstrapDNSConfig var bCfg config.BootstrapDNS
err := yaml.UnmarshalStrict([]byte(cfgTxt), &bCfg) err := yaml.UnmarshalStrict([]byte(cfgTxt), &bCfg)
util.FatalOnError("test bootstrap config is broken, did you change the struct?", err) util.FatalOnError("test bootstrap config is broken, did you change the struct?", err)

View File

@ -21,7 +21,7 @@ const (
// QueryLoggingResolver writes query information (question, answer, duration, ...) // QueryLoggingResolver writes query information (question, answer, duration, ...)
type QueryLoggingResolver struct { type QueryLoggingResolver struct {
configurable[*config.QueryLogConfig] configurable[*config.QueryLog]
NextResolver NextResolver
typed typed
@ -30,7 +30,7 @@ type QueryLoggingResolver struct {
} }
// NewQueryLoggingResolver returns a new resolver instance // NewQueryLoggingResolver returns a new resolver instance
func NewQueryLoggingResolver(ctx context.Context, cfg config.QueryLogConfig) *QueryLoggingResolver { func NewQueryLoggingResolver(ctx context.Context, cfg config.QueryLog) *QueryLoggingResolver {
logger := log.PrefixedLog(queryLoggingResolverType) logger := log.PrefixedLog(queryLoggingResolverType)
var writer querylog.Writer var writer querylog.Writer

View File

@ -40,7 +40,7 @@ func (m *SlowMockWriter) CleanUp() {
var _ = Describe("QueryLoggingResolver", func() { var _ = Describe("QueryLoggingResolver", func() {
var ( var (
sut *QueryLoggingResolver sut *QueryLoggingResolver
sutConfig config.QueryLogConfig sutConfig config.QueryLog
m *mockResolver m *mockResolver
tmpDir *TmpFolder tmpDir *TmpFolder
mockAnswer *dns.Msg mockAnswer *dns.Msg
@ -93,7 +93,7 @@ var _ = Describe("QueryLoggingResolver", func() {
Describe("Process request", func() { Describe("Process request", func() {
When("Resolver has no configuration", func() { When("Resolver has no configuration", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.QueryLogConfig{ sutConfig = config.QueryLog{
CreationAttempts: 1, CreationAttempts: 1,
CreationCooldown: config.Duration(time.Millisecond), CreationCooldown: config.Duration(time.Millisecond),
} }
@ -111,7 +111,7 @@ var _ = Describe("QueryLoggingResolver", func() {
}) })
When("Configuration with logging per client", func() { When("Configuration with logging per client", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.QueryLogConfig{ sutConfig = config.QueryLog{
Target: tmpDir.Path, Target: tmpDir.Path,
Type: config.QueryLogTypeCsvClient, Type: config.QueryLogTypeCsvClient,
CreationAttempts: 1, CreationAttempts: 1,
@ -179,7 +179,7 @@ var _ = Describe("QueryLoggingResolver", func() {
}) })
When("Configuration with logging in one file for all clients", func() { When("Configuration with logging in one file for all clients", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.QueryLogConfig{ sutConfig = config.QueryLog{
Target: tmpDir.Path, Target: tmpDir.Path,
Type: config.QueryLogTypeCsv, Type: config.QueryLogTypeCsv,
CreationAttempts: 1, CreationAttempts: 1,
@ -239,7 +239,7 @@ var _ = Describe("QueryLoggingResolver", func() {
}) })
When("Configuration with specific fields to log", func() { When("Configuration with specific fields to log", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.QueryLogConfig{ sutConfig = config.QueryLog{
Target: tmpDir.Path, Target: tmpDir.Path,
Type: config.QueryLogTypeCsv, Type: config.QueryLogTypeCsv,
CreationAttempts: 1, CreationAttempts: 1,
@ -287,7 +287,7 @@ var _ = Describe("QueryLoggingResolver", func() {
Describe("Slow writer", func() { Describe("Slow writer", func() {
When("writer is too slow", func() { When("writer is too slow", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.QueryLogConfig{ sutConfig = config.QueryLog{
Type: config.QueryLogTypeNone, Type: config.QueryLogTypeNone,
CreationAttempts: 1, CreationAttempts: 1,
CreationCooldown: config.Duration(time.Millisecond), CreationCooldown: config.Duration(time.Millisecond),
@ -310,7 +310,7 @@ var _ = Describe("QueryLoggingResolver", func() {
Describe("Clean up of query log directory", func() { Describe("Clean up of query log directory", func() {
When("fallback logger is enabled, log retention is enabled", func() { When("fallback logger is enabled, log retention is enabled", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.QueryLogConfig{ sutConfig = config.QueryLog{
LogRetentionDays: 7, LogRetentionDays: 7,
Type: config.QueryLogTypeConsole, Type: config.QueryLogTypeConsole,
CreationAttempts: 1, CreationAttempts: 1,
@ -323,7 +323,7 @@ var _ = Describe("QueryLoggingResolver", func() {
}) })
When("log directory contains old files", func() { When("log directory contains old files", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.QueryLogConfig{ sutConfig = config.QueryLog{
Target: tmpDir.Path, Target: tmpDir.Path,
Type: config.QueryLogTypeCsv, Type: config.QueryLogTypeCsv,
LogRetentionDays: 7, LogRetentionDays: 7,
@ -352,7 +352,7 @@ var _ = Describe("QueryLoggingResolver", func() {
Describe("Wrong target configuration", func() { Describe("Wrong target configuration", func() {
When("mysql database path is wrong", func() { When("mysql database path is wrong", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.QueryLogConfig{ sutConfig = config.QueryLog{
Target: "dummy", Target: "dummy",
Type: config.QueryLogTypeMysql, Type: config.QueryLogTypeMysql,
CreationAttempts: 1, CreationAttempts: 1,
@ -366,7 +366,7 @@ var _ = Describe("QueryLoggingResolver", func() {
When("postgresql database path is wrong", func() { When("postgresql database path is wrong", func() {
BeforeEach(func() { BeforeEach(func() {
sutConfig = config.QueryLogConfig{ sutConfig = config.QueryLog{
Target: "dummy", Target: "dummy",
Type: config.QueryLogTypePostgresql, Type: config.QueryLogTypePostgresql,
CreationAttempts: 1, CreationAttempts: 1,

View File

@ -148,7 +148,7 @@ var _ = BeforeSuite(func() {
Upstream: upstreamClient, Upstream: upstreamClient,
}, },
Ports: config.PortsConfig{ Ports: config.Ports{
DNS: config.ListenConfig{GetStringPort(dnsBasePort)}, DNS: config.ListenConfig{GetStringPort(dnsBasePort)},
TLS: config.ListenConfig{GetStringPort(tlsBasePort)}, TLS: config.ListenConfig{GetStringPort(tlsBasePort)},
HTTP: config.ListenConfig{GetStringPort(httpBasePort)}, HTTP: config.ListenConfig{GetStringPort(httpBasePort)},
@ -156,7 +156,7 @@ var _ = BeforeSuite(func() {
}, },
CertFile: certPem.Path, CertFile: certPem.Path,
KeyFile: keyPem.Path, KeyFile: keyPem.Path,
Prometheus: config.MetricsConfig{ Prometheus: config.Metrics{
Enable: true, Enable: true,
Path: "/metrics", Path: "/metrics",
}, },
@ -603,7 +603,7 @@ var _ = Describe("Running DNS server", func() {
}, },
}, },
Blocking: config.Blocking{BlockType: "zeroIp"}, Blocking: config.Blocking{BlockType: "zeroIp"},
Ports: config.PortsConfig{ Ports: config.Ports{
DNS: config.ListenConfig{"127.0.0.1:" + GetStringPort(dnsBasePort2)}, DNS: config.ListenConfig{"127.0.0.1:" + GetStringPort(dnsBasePort2)},
}, },
}) })
@ -649,7 +649,7 @@ var _ = Describe("Running DNS server", func() {
}, },
}, },
Blocking: config.Blocking{BlockType: "zeroIp"}, Blocking: config.Blocking{BlockType: "zeroIp"},
Ports: config.PortsConfig{ Ports: config.Ports{
DNS: config.ListenConfig{"127.0.0.1:" + GetStringPort(dnsBasePort2)}, DNS: config.ListenConfig{"127.0.0.1:" + GetStringPort(dnsBasePort2)},
}, },
}) })
@ -712,7 +712,7 @@ var _ = Describe("Running DNS server", func() {
It("should create self-signed certificate if key/cert files are not provided", func() { It("should create self-signed certificate if key/cert files are not provided", func() {
cfg.KeyFile = "" cfg.KeyFile = ""
cfg.CertFile = "" cfg.CertFile = ""
cfg.Ports = config.PortsConfig{ cfg.Ports = config.Ports{
HTTPS: []string{fmt.Sprintf(":%d", GetIntPort(httpsBasePort)+100)}, HTTPS: []string{fmt.Sprintf(":%d", GetIntPort(httpsBasePort)+100)},
} }
sut, err := NewServer(ctx, &cfg) sut, err := NewServer(ctx, &cfg)