conf.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package conf
  2. import (
  3. "errors"
  4. "flag"
  5. "net"
  6. "go-common/library/conf"
  7. "go-common/library/log"
  8. bm "go-common/library/net/http/blademaster"
  9. xip "go-common/library/net/ip"
  10. "github.com/BurntSushi/toml"
  11. )
  12. var (
  13. confPath string
  14. client *conf.Client
  15. // Conf conf
  16. Conf = &Config{}
  17. // ConfCh for update node of server.
  18. ConfCh = make(chan struct{}, 1)
  19. configKey = "discovery-service.toml"
  20. )
  21. // Config config
  22. type Config struct {
  23. Nodes []string
  24. Zones map[string][]string // zone -> nodes
  25. BM *HTTPServers
  26. Log *log.Config
  27. HTTPClient *bm.ClientConfig
  28. }
  29. func (c *Config) fix() (err error) {
  30. // check ip
  31. host, port, err := net.SplitHostPort(c.BM.Inner.Addr)
  32. if err != nil {
  33. return
  34. }
  35. if host == "0.0.0.0" || host == "127.0.0.1" || host == "" {
  36. host = xip.InternalIP()
  37. }
  38. c.BM.Inner.Addr = host + ":" + port
  39. return
  40. }
  41. // HTTPServers Http Servers
  42. type HTTPServers struct {
  43. Inner *bm.ServerConfig
  44. }
  45. func init() {
  46. // flag.StringVar(&confPath, "conf", "discovery-example.toml", "config path")
  47. flag.StringVar(&confPath, "conf", "", "config path")
  48. }
  49. // Init init conf
  50. func Init() (err error) {
  51. if confPath != "" {
  52. if _, err = toml.DecodeFile(confPath, &Conf); err != nil {
  53. return
  54. }
  55. return Conf.fix()
  56. }
  57. err = remote()
  58. return
  59. }
  60. func remote() (err error) {
  61. if client, err = conf.New(); err != nil {
  62. return
  63. }
  64. if err = load(); err != nil {
  65. return
  66. }
  67. go func() {
  68. for range client.Event() {
  69. log.Info("config reload")
  70. if load() != nil {
  71. log.Error("config reload error (%v)", err)
  72. continue
  73. }
  74. // to change the node of server
  75. ConfCh <- struct{}{}
  76. }
  77. }()
  78. return
  79. }
  80. func load() (err error) {
  81. s, ok := client.Value(configKey)
  82. if !ok {
  83. return errors.New("load config center error")
  84. }
  85. var tmpConf *Config
  86. if _, err = toml.Decode(s, &tmpConf); err != nil {
  87. return errors.New("could not decode config")
  88. }
  89. if err = tmpConf.fix(); err != nil {
  90. return
  91. }
  92. // copy
  93. *Conf = *tmpConf
  94. return
  95. }