conf.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package sample
  2. import (
  3. "fmt"
  4. "errors"
  5. "time"
  6. "go-common/app/service/ops/log-agent/conf/configcenter"
  7. "go-common/library/log"
  8. "github.com/BurntSushi/toml"
  9. )
  10. const (
  11. logSample = "sample.toml"
  12. )
  13. type Config struct {
  14. Local bool `toml:"local"`
  15. SampleConfig map[string]int64 `toml:"sampleConfig"`
  16. }
  17. func (c *Config) ConfigValidate() (error) {
  18. if c == nil {
  19. return fmt.Errorf("Error can't be nil")
  20. }
  21. if c.SampleConfig == nil {
  22. c.SampleConfig = make(map[string]int64)
  23. }
  24. return nil
  25. }
  26. func DecodeConfig(md toml.MetaData, primValue toml.Primitive) (c interface{}, err error) {
  27. config := new(Config)
  28. if err = md.PrimitiveDecode(primValue, config); err != nil {
  29. return nil, err
  30. }
  31. // read config from config center
  32. if !config.Local {
  33. if err = config.readConfig(); err != nil {
  34. return nil, err
  35. }
  36. // watch update and reload config
  37. go func() {
  38. currentVersion := configcenter.Version
  39. for {
  40. if currentVersion != configcenter.Version {
  41. log.Info("sample config reload")
  42. if err := config.readConfig(); err != nil {
  43. log.Error("sample config reload error (%v", err)
  44. }
  45. currentVersion = configcenter.Version
  46. }
  47. time.Sleep(time.Second)
  48. }
  49. }()
  50. }
  51. return config, nil
  52. }
  53. func (c *Config) readConfig() (err error) {
  54. var (
  55. ok bool
  56. value string
  57. tmpSample map[string]int64
  58. )
  59. // sample config
  60. if value, ok = configcenter.Client.Value(logSample); !ok {
  61. return errors.New("failed to get sample.toml")
  62. }
  63. if _, err = toml.Decode(value, &tmpSample); err != nil {
  64. return err
  65. }
  66. c.SampleConfig = tmpSample
  67. return nil
  68. }