You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.9 KiB

13 years ago
4 years ago
  1. package util
  2. import (
  3. "strings"
  4. "sync"
  5. "github.com/spf13/viper"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. )
  8. type Configuration interface {
  9. GetString(key string) string
  10. GetBool(key string) bool
  11. GetInt(key string) int
  12. GetStringSlice(key string) []string
  13. SetDefault(key string, value interface{})
  14. }
  15. func LoadConfiguration(configFileName string, required bool) (loaded bool) {
  16. // find a filer store
  17. viper.SetConfigName(configFileName) // name of config file (without extension)
  18. viper.AddConfigPath(".") // optionally look for config in the working directory
  19. viper.AddConfigPath("$HOME/.seaweedfs") // call multiple times to add many search paths
  20. viper.AddConfigPath("/usr/local/etc/seaweedfs/") // search path for bsd-style config directory in
  21. viper.AddConfigPath("/etc/seaweedfs/") // path to look for the config file in
  22. glog.V(1).Infof("Reading %s.toml from %s", configFileName, viper.ConfigFileUsed())
  23. if err := viper.MergeInConfig(); err != nil { // Handle errors reading the config file
  24. logLevel := glog.Level(0)
  25. if strings.Contains(err.Error(), "Not Found") {
  26. logLevel = 1
  27. }
  28. glog.V(logLevel).Infof("Reading %s: %v", viper.ConfigFileUsed(), err)
  29. if required {
  30. glog.Fatalf("Failed to load %s.toml file from current directory, or $HOME/.seaweedfs/, or /etc/seaweedfs/"+
  31. "\n\nPlease use this command to generate the default %s.toml file\n"+
  32. " weed scaffold -config=%s -output=.\n\n\n",
  33. configFileName, configFileName, configFileName)
  34. } else {
  35. return false
  36. }
  37. }
  38. return true
  39. }
  40. type ViperProxy struct {
  41. *viper.Viper
  42. sync.Mutex
  43. }
  44. func (vp *ViperProxy) SetDefault(key string, value interface{}) {
  45. vp.Lock()
  46. defer vp.Unlock()
  47. vp.Viper.SetDefault(key, value)
  48. }
  49. func GetViper() *ViperProxy {
  50. v := &ViperProxy{}
  51. v.Viper = viper.GetViper()
  52. v.AutomaticEnv()
  53. v.SetEnvPrefix("weed")
  54. v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
  55. return v
  56. }