config.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "github.com/BurntSushi/toml"
  6. "go-common/library/conf"
  7. "go-common/library/log"
  8. xtime "go-common/library/time"
  9. )
  10. func init() {
  11. flag.StringVar(&confPath, "conf", "", "config file")
  12. }
  13. var (
  14. confPath string
  15. // Conf conf
  16. Conf = &Config{}
  17. client *conf.Client
  18. )
  19. // Config config.
  20. type Config struct {
  21. Log *log.Config `toml:"log"`
  22. HBase *HBaseConfig `toml:"hbase"`
  23. InfluxDB *InfluxDBConfig `toml:"influx_db"`
  24. OpsLog *OpsLog `toml:"ops_log"`
  25. Collectors *Collectors `toml:"collectors"`
  26. }
  27. // InfluxDBConfig InfluxDBConfig
  28. type InfluxDBConfig struct {
  29. Addr string `toml:"addr"`
  30. Username string `toml:"username"`
  31. Password string `toml:"password"`
  32. Database string `toml:"database"`
  33. }
  34. // HBaseConfig hbase config
  35. type HBaseConfig struct {
  36. Namespace string `toml:"namespace"`
  37. Addrs string `toml:"addrs"`
  38. RPCQueueSize int `toml:"rpc_queue_size"`
  39. FlushInterval xtime.Duration `toml:"flush_interval"`
  40. EffectiveUser string `toml:"effective_user"`
  41. RegionLookupTimeout xtime.Duration `toml:"region_lookup_timeout"`
  42. RegionReadTimeout xtime.Duration `toml:"region_read_timeout"`
  43. }
  44. // OpsLog .
  45. type OpsLog struct {
  46. API string `toml:"api"`
  47. }
  48. // Collectors collector config
  49. type Collectors struct {
  50. Nodes []string `toml:"nodes"`
  51. }
  52. // Init config
  53. func Init() (err error) {
  54. if confPath != "" {
  55. return local()
  56. }
  57. return remote()
  58. }
  59. func local() (err error) {
  60. _, err = toml.DecodeFile(confPath, &Conf)
  61. return
  62. }
  63. func remote() (err error) {
  64. if client, err = conf.New(); err != nil {
  65. return
  66. }
  67. if err = load(); err != nil {
  68. return
  69. }
  70. go func() {
  71. for range client.Event() {
  72. log.Info("config reload")
  73. if err := load(); err != nil {
  74. log.Error("config reload error (%v)", err)
  75. }
  76. }
  77. }()
  78. return
  79. }
  80. func load() (err error) {
  81. var (
  82. s string
  83. ok bool
  84. tmpConf *Config
  85. )
  86. if s, ok = client.Toml2(); !ok {
  87. return errors.New("load config center error")
  88. }
  89. if _, err = toml.Decode(s, &tmpConf); err != nil {
  90. return errors.New("could not decode config")
  91. }
  92. *Conf = *tmpConf
  93. return
  94. }