config_history.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package handler
  2. import (
  3. "bet24.com/log"
  4. "bet24.com/servers/common"
  5. "encoding/json"
  6. "sync"
  7. "time"
  8. )
  9. const max_change_log = 5
  10. type history struct {
  11. Key string
  12. OldContent string
  13. Content string
  14. ChangeTime string
  15. }
  16. type config_history struct {
  17. lock *sync.RWMutex
  18. changeLog map[string][]history
  19. }
  20. var configHistory *config_history
  21. func getHistoryInstance() *config_history {
  22. if configHistory == nil {
  23. configHistory = new(config_history)
  24. configHistory.ctor()
  25. }
  26. return configHistory
  27. }
  28. func (ch *config_history) ctor() {
  29. log.Debug("config_history.ctor")
  30. ch.changeLog = make(map[string][]history)
  31. ch.lock = &sync.RWMutex{}
  32. }
  33. func (ch *config_history) dump(param1, param2 string) {
  34. log.Release("-------------------------------")
  35. log.Release("config_history.dump [%s,%s]", param1, param2)
  36. log.Release("+++++++++++++++++++++++++++++++")
  37. if param1 == "" {
  38. // dump all keys
  39. log.Release(" dump all keys")
  40. ch.lock.RLock()
  41. for k, v := range ch.changeLog {
  42. log.Release(" [%s] %d changes", k, len(v))
  43. }
  44. ch.lock.RUnlock()
  45. return
  46. }
  47. ch.lock.RLock()
  48. changes, ok := ch.changeLog[param1]
  49. ch.lock.RUnlock()
  50. if !ok {
  51. log.Release(" key[%s] not found", param1)
  52. return
  53. } else {
  54. log.Release(" key[%s] changeLog:", param1)
  55. }
  56. for _, v := range changes {
  57. log.Release(" [%s][%s]->[%s]", v.ChangeTime, v.OldContent, v.Content)
  58. }
  59. }
  60. func (ch *config_history) addBackup(key, oldValue, newValue string) {
  61. ch.lock.Lock()
  62. defer ch.lock.Unlock()
  63. changes, ok := ch.changeLog[key]
  64. h := history{Key: key, OldContent: oldValue, Content: newValue, ChangeTime: common.TimeStampToShortString(time.Now().Unix())}
  65. if !ok {
  66. ch.changeLog[key] = []history{h}
  67. return
  68. }
  69. changes = append([]history{h}, changes...)
  70. if len(changes) > max_change_log {
  71. changes = changes[:max_change_log]
  72. }
  73. ch.changeLog[key] = changes
  74. }
  75. func (ch *config_history) getChangeLogs(key string) string {
  76. ch.lock.RLock()
  77. defer ch.lock.RUnlock()
  78. logs, ok := ch.changeLog[key]
  79. if !ok {
  80. return ""
  81. }
  82. d, _ := json.Marshal(logs)
  83. return string(d)
  84. }