Kaynağa Gözat

Move application config out of main package

Ask Bjørn Hansen 2 yıl önce
ebeveyn
işleme
74d0ad2505
6 değiştirilmiş dosya ile 56 ekleme ve 41 silme
  1. 14 8
      appconfig/appconfig.go
  2. 6 2
      config_test.go
  3. 21 21
      geodns.go
  4. 5 4
      http.go
  5. 2 1
      server/serve_test.go
  6. 8 5
      server/server.go

+ 14 - 8
config.go → appconfig/appconfig.go

@@ -1,4 +1,4 @@
-package main
+package appconfig
 
 import (
 	"context"
@@ -7,13 +7,17 @@ import (
 	"sync"
 	"time"
 
-	"github.com/abh/geodns/v3/targeting/geoip2"
-
 	"github.com/fsnotify/fsnotify"
-	gcfg "gopkg.in/gcfg.v1"
+	"gopkg.in/gcfg.v1"
+
+	"github.com/abh/geodns/v3/targeting/geoip2"
 )
 
 type AppConfig struct {
+	DNS struct {
+		PublicDebugQueries bool
+		DetailedMetrics    bool
+	}
 	GeoIP struct {
 		Directory string
 	}
@@ -47,7 +51,9 @@ type AppConfig struct {
 	}
 }
 
+// Singleton to keep the latest read config
 var Config = new(AppConfig)
+
 var cfgMutex sync.RWMutex
 
 func (conf *AppConfig) GeoIPDirectory() string {
@@ -59,14 +65,14 @@ func (conf *AppConfig) GeoIPDirectory() string {
 	return geoip2.FindDB()
 }
 
-func configWatcher(ctx context.Context, fileName string) error {
+func ConfigWatcher(ctx context.Context, fileName string) error {
 
 	watcher, err := fsnotify.NewWatcher()
 	if err != nil {
 		return err
 	}
 
-	if err := watcher.Add(*flagconfig); err != nil {
+	if err := watcher.Add(fileName); err != nil {
 		return err
 	}
 
@@ -83,7 +89,7 @@ func configWatcher(ctx context.Context, fileName string) error {
 					ev.Has(fsnotify.Rename) ||
 					ev.Has(fsnotify.Chmod) {
 					time.Sleep(200 * time.Millisecond)
-					err := configReader(fileName)
+					err := ConfigReader(fileName)
 					if err != nil {
 						// don't quit because we'll just keep the old config at this
 						// stage and try again next it changes
@@ -99,7 +105,7 @@ func configWatcher(ctx context.Context, fileName string) error {
 
 var lastReadConfig time.Time
 
-func configReader(fileName string) error {
+func ConfigReader(fileName string) error {
 
 	stat, err := os.Stat(fileName)
 	if err != nil {

+ 6 - 2
config_test.go

@@ -1,10 +1,14 @@
 package main
 
-import "testing"
+import (
+	"testing"
+
+	"github.com/abh/geodns/v3/appconfig"
+)
 
 func TestConfig(t *testing.T) {
 	// check that the sample config parses
-	err := configReader("dns/geodns.conf.sample")
+	err := appconfig.ConfigReader("dns/geodns.conf.sample")
 	if err != nil {
 		t.Fatalf("Could not read config: %s", err)
 	}

+ 21 - 21
geodns.go

@@ -36,6 +36,7 @@ import (
 
 	"go.ntppool.org/common/version"
 
+	"github.com/abh/geodns/v3/appconfig"
 	"github.com/abh/geodns/v3/applog"
 	"github.com/abh/geodns/v3/health"
 	"github.com/abh/geodns/v3/monitor"
@@ -51,17 +52,16 @@ var (
 )
 
 var (
-	flagconfig       = flag.String("config", "./dns/", "directory of zone files")
-	flagconfigfile   = flag.String("configfile", "geodns.conf", "filename of config file (in 'config' directory)")
-	flagcheckconfig  = flag.Bool("checkconfig", false, "check configuration and exit")
-	flagidentifier   = flag.String("identifier", "", "identifier (hostname, pop name or similar)")
-	flaginter        = flag.String("interface", "*", "set the listener address")
-	flagport         = flag.String("port", "53", "default port number")
-	flaghttp         = flag.String("http", ":8053", "http listen address (:8053)")
-	flaglog          = flag.Bool("log", false, "be more verbose")
-	flagcpus         = flag.Int("cpus", 0, "Set the maximum number of CPUs to use")
-	flagLogFile      = flag.String("logfile", "", "log to file")
-	flagPrivateDebug = flag.Bool("privatedebug", false, "Make debugging queries accepted only on loopback")
+	flagconfig      = flag.String("config", "./dns/", "directory of zone files")
+	flagconfigfile  = flag.String("configfile", "geodns.conf", "filename of config file (in 'config' directory)")
+	flagcheckconfig = flag.Bool("checkconfig", false, "check configuration and exit")
+	flagidentifier  = flag.String("identifier", "", "identifier (hostname, pop name or similar)")
+	flaginter       = flag.String("interface", "*", "set the listener address")
+	flagport        = flag.String("port", "53", "default port number")
+	flaghttp        = flag.String("http", ":8053", "http listen address (:8053)")
+	flaglog         = flag.Bool("log", false, "be more verbose")
+	flagcpus        = flag.Int("cpus", 0, "Set the maximum number of CPUs to use")
+	flagLogFile     = flag.String("logfile", "", "log to file")
 
 	flagShowVersion = flag.Bool("version", false, "Show GeoDNS version")
 
@@ -118,7 +118,7 @@ func main() {
 	}
 
 	if *flagcheckconfig {
-		err := configReader(configFileName)
+		err := appconfig.ConfigReader(configFileName)
 		if err != nil {
 			log.Println("Errors reading config", err)
 			os.Exit(2)
@@ -175,19 +175,19 @@ func main() {
 	}
 
 	// load geodns.conf config
-	err := configReader(configFileName)
+	err := appconfig.ConfigReader(configFileName)
 	if err != nil {
 		log.Printf("error reading config file %s: %s", configFileName, err)
 		os.Exit(2)
 	}
 
-	if len(Config.Health.Directory) > 0 {
-		go health.DirectoryReader(Config.Health.Directory)
+	if len(appconfig.Config.Health.Directory) > 0 {
+		go health.DirectoryReader(appconfig.Config.Health.Directory)
 	}
 
 	// load (and re-load) zone data
 	g.Go(func() error {
-		err := configWatcher(ctx, configFileName)
+		err := appconfig.ConfigWatcher(ctx, configFileName)
 		if err != nil {
 			log.Printf("config watcher error: %s", err)
 			return err
@@ -213,8 +213,8 @@ func main() {
 
 	inter := getInterfaces()
 
-	if len(Config.GeoIPDirectory()) > 0 {
-		geoProvider, err := geoip2.New(Config.GeoIPDirectory())
+	if len(appconfig.Config.GeoIPDirectory()) > 0 {
+		geoProvider, err := geoip2.New(appconfig.Config.GeoIPDirectory())
 		if err != nil {
 			log.Printf("Configuring geo provider: %s", err)
 		}
@@ -223,9 +223,9 @@ func main() {
 		}
 	}
 
-	srv := server.NewServer(serverInfo)
+	srv := server.NewServer(appconfig.Config, serverInfo)
 
-	if qlc := Config.AvroLog; len(qlc.Path) > 0 {
+	if qlc := appconfig.Config.AvroLog; len(qlc.Path) > 0 {
 
 		maxsize := qlc.MaxSize
 		if maxsize < 50000 {
@@ -245,7 +245,7 @@ func main() {
 		}
 		srv.SetQueryLogger(ql)
 
-	} else if qlc := Config.QueryLog; len(qlc.Path) > 0 {
+	} else if qlc := appconfig.Config.QueryLog; len(qlc.Path) > 0 {
 		ql, err := querylog.NewFileLogger(qlc.Path, qlc.MaxSize, qlc.Keep)
 		if err != nil {
 			log.Fatalf("Could not start file query logger: %s", err)

+ 5 - 4
http.go

@@ -10,6 +10,7 @@ import (
 	"strconv"
 	"time"
 
+	"github.com/abh/geodns/v3/appconfig"
 	"github.com/abh/geodns/v3/monitor"
 	"github.com/abh/geodns/v3/zones"
 	"github.com/prometheus/client_golang/prometheus/promhttp"
@@ -125,10 +126,10 @@ type basicauth struct {
 
 func (b *basicauth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 
-	cfgMutex.RLock()
-	user := Config.HTTP.User
-	password := Config.HTTP.Password
-	cfgMutex.RUnlock()
+	// cfgMutex.RLock()
+	user := appconfig.Config.HTTP.User
+	password := appconfig.Config.HTTP.Password
+	// cfgMutex.RUnlock()
 
 	if len(user) == 0 {
 		b.h.ServeHTTP(w, r)

+ 2 - 1
server/serve_test.go

@@ -11,6 +11,7 @@ import (
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 
+	"github.com/abh/geodns/v3/appconfig"
 	"github.com/abh/geodns/v3/monitor"
 	"github.com/abh/geodns/v3/zones"
 	"github.com/miekg/dns"
@@ -23,7 +24,7 @@ const (
 func TestServe(t *testing.T) {
 	serverInfo := &monitor.ServerInfo{}
 
-	srv := NewServer(serverInfo)
+	srv := NewServer(appconfig.Config, serverInfo)
 	ctx, cancel := context.WithCancel(context.Background())
 
 	mm, err := zones.NewMuxManager("../dns", srv)

+ 8 - 5
server/server.go

@@ -7,6 +7,7 @@ import (
 	"sync"
 	"time"
 
+	"github.com/abh/geodns/v3/appconfig"
 	"github.com/abh/geodns/v3/monitor"
 	"github.com/abh/geodns/v3/querylog"
 	"github.com/abh/geodns/v3/zones"
@@ -23,18 +24,20 @@ type serverMetrics struct {
 
 // Server ...
 type Server struct {
-	queryLogger        querylog.QueryLogger
-	mux                *dns.ServeMux
 	PublicDebugQueries bool
-	info               *monitor.ServerInfo
-	metrics            *serverMetrics
+	DetailedMetrics    bool
+
+	queryLogger querylog.QueryLogger
+	mux         *dns.ServeMux
+	info        *monitor.ServerInfo
+	metrics     *serverMetrics
 
 	lock       sync.Mutex
 	dnsServers []*dns.Server
 }
 
 // NewServer ...
-func NewServer(si *monitor.ServerInfo) *Server {
+func NewServer(config *appconfig.AppConfig, si *monitor.ServerInfo) *Server {
 	mux := dns.NewServeMux()
 
 	queries := prometheus.NewCounterVec(