Cleaned up config handling

- moved everything to cmd/root.go
- Sanitize all paths to full absolute ones
- Set a config key with the current config basedir
- moved default config logging to a central location
- resolve user config dir relative to config dir
- change cwd to config dir
This commit is contained in:
Torben Nehmer 2021-08-25 21:17:19 +02:00
parent a6e52d9d3d
commit 9952343cda
8 changed files with 58 additions and 45 deletions

View File

@ -1,30 +0,0 @@
package cmd
import (
"fmt"
"log"
"gitea.nehmer.net/torben/dyndns/service"
"gitea.nehmer.net/torben/dyndns/webapi"
"github.com/spf13/viper"
)
func InitializeViper() {
viper.SetConfigName("conf.yml")
viper.SetConfigType("yaml")
viper.AddConfigPath("/etc/dyndns")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Println("Could not find configfile, using defaults")
} else {
log.Fatalln(fmt.Sprintf("configuration is invalid: %s", err))
}
}
}
func setAllConfigDefaults() {
service.SetConfigDefaults()
webapi.SetConfigDefaults()
}

View File

@ -5,7 +5,6 @@ import (
"gitea.nehmer.net/torben/dyndns/service" "gitea.nehmer.net/torben/dyndns/service"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper"
) )
var cmdDNSUpdate = &cobra.Command{ var cmdDNSUpdate = &cobra.Command{
@ -26,7 +25,6 @@ func init() {
cmdDNSUpdate.MarkFlagRequired("domain") cmdDNSUpdate.MarkFlagRequired("domain")
cmdDNSUpdate.Run = func(cmd *cobra.Command, args []string) { cmdDNSUpdate.Run = func(cmd *cobra.Command, args []string) {
log.Printf("Configuration in use: %v", viper.AllSettings())
service.LoadConfig() service.LoadConfig()
err := service.DNSUpdateEntry(*domain, *name, *ip4, *ip6) err := service.DNSUpdateEntry(*domain, *name, *ip4, *ip6)

View File

@ -8,7 +8,6 @@ import (
"gitea.nehmer.net/torben/dyndns/service" "gitea.nehmer.net/torben/dyndns/service"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/crypto/ssh/terminal" "golang.org/x/crypto/ssh/terminal"
) )
@ -18,7 +17,6 @@ var cmdHashPassword = &cobra.Command{
Long: `Creates a salted hash using bcrypt for use in userconfig files, so that we don't Long: `Creates a salted hash using bcrypt for use in userconfig files, so that we don't
have to store a plaintext password.`, have to store a plaintext password.`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
log.Printf("Configuration in use: %v", viper.AllSettings())
service.LoadConfig() service.LoadConfig()
fmt.Println("Enter password:") fmt.Println("Enter password:")

View File

@ -5,7 +5,6 @@ import (
"gitea.nehmer.net/torben/dyndns/service" "gitea.nehmer.net/torben/dyndns/service"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper"
) )
var cmdNFTUpdate = &cobra.Command{ var cmdNFTUpdate = &cobra.Command{
@ -27,7 +26,6 @@ func init() {
set6 := cmdNFTUpdate.Flags().StringP("set6", "r", "", "The IPv6 NFT Set name in the given table.") set6 := cmdNFTUpdate.Flags().StringP("set6", "r", "", "The IPv6 NFT Set name in the given table.")
cmdNFTUpdate.Run = func(cmd *cobra.Command, args []string) { cmdNFTUpdate.Run = func(cmd *cobra.Command, args []string) {
log.Printf("Configuration in use: %v", viper.AllSettings())
service.LoadConfig() service.LoadConfig()
err := service.NFTUpdateSetsCmd(*table, *set4, *ip4, *set6, *ip6) err := service.NFTUpdateSetsCmd(*table, *set4, *ip4, *set6, *ip6)

View File

@ -2,11 +2,18 @@ package cmd
import ( import (
"fmt" "fmt"
"log"
"os" "os"
"path/filepath"
"gitea.nehmer.net/torben/dyndns/service"
"gitea.nehmer.net/torben/dyndns/webapi"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper"
) )
var ConfigDir string
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: "dyndns", Use: "dyndns",
Short: "Go DynDNS Server", Short: "Go DynDNS Server",
@ -14,10 +21,50 @@ var rootCmd = &cobra.Command{
NFTable Firewall and a properly configured Bind DNS Server.`, NFTable Firewall and a properly configured Bind DNS Server.`,
} }
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVarP(&ConfigDir, "config-dir", "c", ".", "base configuration directory, defaults to .")
}
func Exec() { func Exec() {
err := rootCmd.Execute() if err := os.Chdir(ConfigDir); err != nil {
if err != nil { log.Fatalf("Could not change to directory %s: %v", ConfigDir, err)
fmt.Println(err) }
os.Exit(1) if err := rootCmd.Execute(); err != nil {
log.Fatalf("Failed to execute command: %v", err)
} }
} }
func sanitizeConfigDir() {
var err error
if ConfigDir, err = filepath.Abs(ConfigDir); err != nil {
cobra.CheckErr(fmt.Sprintf("path is invalid: %v", err))
}
log.Printf("Using configuration directory %s", ConfigDir)
}
func initConfig() {
sanitizeConfigDir()
viper.SetConfigName("conf.yml")
viper.SetConfigType("yaml")
viper.AddConfigPath(ConfigDir)
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Println("Could not find configfile, using defaults")
} else {
cobra.CheckErr(fmt.Sprintf("configuration is invalid: %s", err))
}
}
viper.Set("ConfigDir", ConfigDir)
log.Printf("Configuration in use: %v", viper.AllSettings())
}
func setAllConfigDefaults() {
service.SetConfigDefaults()
webapi.SetConfigDefaults()
}

View File

@ -1,8 +1,6 @@
package cmd package cmd
import ( import (
"log"
"gitea.nehmer.net/torben/dyndns/service" "gitea.nehmer.net/torben/dyndns/service"
"gitea.nehmer.net/torben/dyndns/webapi" "gitea.nehmer.net/torben/dyndns/webapi"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -14,7 +12,6 @@ var cmdServe = &cobra.Command{
Short: "Start webserver", Short: "Start webserver",
Long: ``, Long: ``,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
log.Printf("Configuration in use: %v", viper.AllSettings())
webapi.LoadConfig() webapi.LoadConfig()
service.LoadConfig() service.LoadConfig()
webapi.Server() webapi.Server()

View File

@ -5,6 +5,5 @@ import (
) )
func main() { func main() {
cmd.InitializeViper()
cmd.Exec() cmd.Exec()
} }

View File

@ -3,6 +3,7 @@ package service
import ( import (
"encoding/json" "encoding/json"
"log" "log"
"path/filepath"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -40,7 +41,12 @@ func LoadConfig() {
// viper.UnmarshalKey("Service", &C) // viper.UnmarshalKey("Service", &C)
C.DNS.Server = viper.GetString("Service.DNS.Server") C.DNS.Server = viper.GetString("Service.DNS.Server")
C.DNS.DefaultTTL = viper.GetUint32("Service.DNS.DefaultTTL") C.DNS.DefaultTTL = viper.GetUint32("Service.DNS.DefaultTTL")
C.Users.ConfigDir = viper.GetString("Service.Users.ConfigDir") path := viper.GetString("Service.Users.ConfigDir")
if filepath.IsAbs(path) {
C.Users.ConfigDir = filepath.Clean(path)
} else {
C.Users.ConfigDir = filepath.Join(viper.GetString("ConfigDir"), path)
}
} }
func (obj *config) PrettyPrint() string { func (obj *config) PrettyPrint() string {