service.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package service
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "go-common/app/admin/main/push/conf"
  11. "go-common/app/admin/main/push/dao"
  12. "go-common/library/log"
  13. bm "go-common/library/net/http/blademaster"
  14. "github.com/jinzhu/gorm"
  15. )
  16. // Service biz service def.
  17. type Service struct {
  18. c *conf.Config
  19. dao *dao.Dao
  20. DB *gorm.DB
  21. httpClient *bm.Client
  22. dpClient *bm.Client
  23. partitions map[int]string
  24. }
  25. // New new a Service and return.
  26. func New(c *conf.Config) (s *Service) {
  27. s = &Service{
  28. c: c,
  29. dao: dao.New(c),
  30. httpClient: bm.NewClient(c.HTTPClient),
  31. dpClient: bm.NewClient(c.DPClient),
  32. partitions: make(map[int]string),
  33. }
  34. s.DB = s.dao.DB.Scopes(func(db *gorm.DB) *gorm.DB {
  35. return db.Where("dtime = ?", 0)
  36. })
  37. s.loadPartitions()
  38. go s.loadPartitionsproc()
  39. go s.cleanDiskFilesproc()
  40. return s
  41. }
  42. func (s *Service) loadPartitions() (err error) {
  43. m, err := s.dao.Partitions(context.Background())
  44. if err != nil {
  45. return
  46. }
  47. if len(m) > 0 {
  48. s.partitions = m
  49. }
  50. return
  51. }
  52. func (s *Service) loadPartitionsproc() {
  53. for {
  54. if err := s.loadPartitions(); err != nil {
  55. time.Sleep(time.Second)
  56. continue
  57. }
  58. time.Sleep(time.Minute)
  59. }
  60. }
  61. func (s *Service) cleanDiskFilesproc() {
  62. for {
  63. fs, err := ioutil.ReadDir(conf.Conf.Cfg.MountDir)
  64. if err != nil {
  65. log.Error("s.cleanFilesproc() read dir error(%v)", err)
  66. time.Sleep(time.Minute)
  67. continue
  68. }
  69. divDate := time.Now().Add(-time.Duration(24*conf.Conf.Cfg.DiskFileExpireDay) * time.Hour).Format("20060102")
  70. div, _ := strconv.ParseInt(divDate, 10, 64)
  71. for _, f := range fs {
  72. if !f.IsDir() {
  73. continue
  74. }
  75. d, _ := strconv.ParseInt(f.Name(), 10, 64)
  76. if d < div {
  77. dir := fmt.Sprintf("%s/%s", strings.TrimSuffix(conf.Conf.Cfg.MountDir, "/"), f.Name())
  78. if err = os.RemoveAll(dir); err != nil {
  79. log.Error("s.cleanFilesproc() remove dir(%s) error(%v)", dir, err)
  80. time.Sleep(time.Minute)
  81. }
  82. }
  83. }
  84. time.Sleep(time.Hour)
  85. }
  86. }
  87. // Ping check dao health.
  88. func (s *Service) Ping(c context.Context) (err error) {
  89. return s.dao.Ping(c)
  90. }
  91. // Wait wait all closed.
  92. func (s *Service) Wait() {}
  93. // Close close all dao.
  94. func (s *Service) Close() {
  95. s.dao.Close()
  96. }