conf.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package conf
  2. import (
  3. "flag"
  4. "os"
  5. "go-common/library/conf"
  6. "go-common/library/log"
  7. "github.com/BurntSushi/toml"
  8. "github.com/pkg/errors"
  9. )
  10. // Runner ...
  11. type Runner struct {
  12. URL string
  13. Token string
  14. Name string
  15. }
  16. type config struct {
  17. Offline bool
  18. Runner []Runner
  19. }
  20. // Conf ...
  21. var (
  22. confPath string
  23. client *conf.Client
  24. filename string
  25. reload chan bool
  26. Conf config
  27. RunnerMap map[string]Runner
  28. HostName string
  29. )
  30. func load() (err error) {
  31. var (
  32. s string
  33. ok bool
  34. )
  35. if s, ok = client.Value(filename); !ok {
  36. err = errors.Errorf("load config center error [%s]", filename)
  37. return
  38. }
  39. log.Info("config data: %s", s)
  40. Conf = config{}
  41. if _, err = toml.Decode(s, &Conf); err != nil {
  42. err = errors.Wrapf(err, "could not decode config err(%+v)", err)
  43. return
  44. }
  45. return
  46. }
  47. func configCenter() (err error) {
  48. if filename == "" {
  49. return errors.New("filename is null,please set the environment(RUNNER_REPONAME)")
  50. }
  51. if client, err = conf.New(); err != nil {
  52. panic(err)
  53. }
  54. if err = load(); err != nil {
  55. return
  56. }
  57. client.Watch(filename)
  58. go func() {
  59. for range client.Event() {
  60. log.Info("config reload")
  61. if load() != nil {
  62. log.Error("config reload error (%v)", err)
  63. } else {
  64. reload <- true
  65. }
  66. }
  67. }()
  68. return
  69. }
  70. func osHostName() string {
  71. var (
  72. host string
  73. err error
  74. )
  75. if host, err = os.Hostname(); err != nil {
  76. host = "unKown-Hostname"
  77. log.Error("%+v", errors.WithStack(err))
  78. }
  79. return host
  80. }
  81. func init() {
  82. flag.StringVar(&confPath, "conf", "", "config path")
  83. }
  84. // Init ...
  85. func Init() (err error) {
  86. filename = os.Getenv("CONF_FILENAME")
  87. RunnerMap = make(map[string]Runner)
  88. HostName = osHostName()
  89. reload = make(chan bool, 1)
  90. if confPath == "" {
  91. err = configCenter()
  92. return
  93. }
  94. if _, err = toml.DecodeFile(confPath, &Conf); err != nil {
  95. log.Error("toml.DecodeFile(%s) err(%+v)", confPath, err)
  96. return
  97. }
  98. return
  99. }
  100. // ReloadEvent ...
  101. func ReloadEvent() <-chan bool {
  102. return reload
  103. }