config.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package classify
  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. logLevelMap = "logLevelMap.toml"
  12. logIdMap = "logIdMap.toml"
  13. )
  14. type Config struct {
  15. Local bool `toml:"local"`
  16. LogLevelMapConfig map[string]string `toml:"logLevelMapConfig"`
  17. LogIdMapConfig map[string]string `toml:"logIdMapConfig"`
  18. PriorityBlackList map[string]string `toml:"priorityBlackList"`
  19. }
  20. func (c *Config) ConfigValidate() (error) {
  21. if c == nil {
  22. return fmt.Errorf("Error can't be nil")
  23. }
  24. if c.LogLevelMapConfig == nil {
  25. c.LogLevelMapConfig = make(map[string]string)
  26. }
  27. if c.LogIdMapConfig == nil {
  28. return fmt.Errorf("LogIdMapConfig of classify can't be nil")
  29. }
  30. if c.PriorityBlackList == nil {
  31. c.PriorityBlackList = make(map[string]string)
  32. }
  33. return nil
  34. }
  35. func DecodeConfig(md toml.MetaData, primValue toml.Primitive) (c interface{}, err error) {
  36. config := new(Config)
  37. if err = md.PrimitiveDecode(primValue, config); err != nil {
  38. return nil, err
  39. }
  40. // read config from config center
  41. if !config.Local {
  42. if err = config.readConfig(); err != nil {
  43. return nil, err
  44. }
  45. // watch update and reload config
  46. go func() {
  47. currentVersion := configcenter.Version
  48. for {
  49. if currentVersion != configcenter.Version {
  50. log.Info("classify config reload")
  51. if err := config.readConfig(); err != nil {
  52. log.Error("classify config reload error (%v)", err)
  53. }
  54. currentVersion = configcenter.Version
  55. }
  56. time.Sleep(time.Second)
  57. }
  58. }()
  59. }
  60. return config, nil
  61. }
  62. func (c *Config) readConfig() (err error) {
  63. var (
  64. ok bool
  65. value string
  66. tmplogLevelMap map[string]string
  67. tmplogIdMap map[string]string
  68. )
  69. // logLevel config
  70. if value, ok = configcenter.Client.Value(logLevelMap); !ok {
  71. return errors.New("failed to get logLevelMap.toml")
  72. }
  73. if _, err = toml.Decode(value, &tmplogLevelMap); err != nil {
  74. return err
  75. }
  76. c.LogLevelMapConfig = tmplogLevelMap
  77. // logIdMap config
  78. if value, ok = configcenter.Client.Value(logIdMap); !ok {
  79. return errors.New("failed to get logIdMap.toml")
  80. }
  81. if _, err = toml.Decode(value, &tmplogIdMap); err != nil {
  82. return err
  83. }
  84. c.LogIdMapConfig = tmplogIdMap
  85. return nil
  86. }