cgistatus.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package importer
  2. import (
  3. "encoding/json"
  4. "os"
  5. "path/filepath"
  6. "sync"
  7. "time"
  8. "git.wecise.com/wecise/cgimport/odbc"
  9. "git.wecise.com/wecise/util/rc"
  10. )
  11. type ImportStatus struct {
  12. RecordsCount int64
  13. }
  14. type CGIStatus struct {
  15. filepath string
  16. //
  17. TotalUseTime time.Duration
  18. ImportStatus map[string]*ImportStatus
  19. //
  20. mutex sync.RWMutex
  21. rc *rc.RoutinesController
  22. lasterror error
  23. lastsavetime time.Time
  24. waitdone chan any
  25. }
  26. func NewCGIStatus() *CGIStatus {
  27. return &CGIStatus{
  28. filepath: mcfg.GetString("cgi.statusfile", "/opt/matrix/var/cgimport/"+odbc.Keyspace+".status.txt"),
  29. ImportStatus: map[string]*ImportStatus{},
  30. rc: rc.NewRoutinesController("", 1),
  31. waitdone: make(chan any, 1),
  32. }
  33. }
  34. func (cgistatus *CGIStatus) Load() error {
  35. cgistatusbs, e := os.ReadFile(cgistatus.filepath)
  36. if e != nil && !os.IsNotExist(e) {
  37. return e
  38. }
  39. if len(cgistatusbs) > 0 {
  40. e = json.Unmarshal(cgistatusbs, &cgistatus)
  41. if e != nil {
  42. logger.Warn(e)
  43. }
  44. }
  45. return nil
  46. }
  47. func (cgistatus *CGIStatus) WaitSaveDone() {
  48. cgistatus.waitdone <- 1
  49. cgistatus.rc.WaitDone()
  50. }
  51. func (cgistatus *CGIStatus) Save() (err error) {
  52. cgistatus.rc.CallLast2Only(func() {
  53. if !cgistatus.lastsavetime.Equal(time.Time{}) {
  54. interval := time.Since(cgistatus.lastsavetime)
  55. if interval < 1*time.Second {
  56. t := time.NewTimer(1*time.Second - interval)
  57. select {
  58. case <-t.C:
  59. case v := <-cgistatus.waitdone:
  60. cgistatus.waitdone <- v
  61. }
  62. }
  63. }
  64. cgistatus.mutex.RLock()
  65. cgistatusbs, e := json.MarshalIndent(cgistatus, "", " ")
  66. cgistatus.mutex.RUnlock()
  67. if e != nil {
  68. cgistatus.lasterror = e
  69. return
  70. }
  71. e = os.MkdirAll(filepath.Dir(cgistatus.filepath), os.ModePerm)
  72. if e != nil {
  73. cgistatus.lasterror = e
  74. return
  75. }
  76. e = os.WriteFile(cgistatus.filepath, cgistatusbs, os.ModePerm)
  77. if e != nil {
  78. cgistatus.lasterror = e
  79. return
  80. }
  81. cgistatus.lastsavetime = time.Now()
  82. // fmt.Println(cgistatus.lastsavetime)
  83. })
  84. return cgistatus.lasterror
  85. }