commit.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package sqlite
  2. import (
  3. "fmt"
  4. "sync/atomic"
  5. "time"
  6. "github.com/crowdsecurity/crowdsec/pkg/types"
  7. "github.com/pkg/errors"
  8. log "github.com/sirupsen/logrus"
  9. )
  10. func (c *Context) DeleteExpired() error {
  11. //Delete the expired records
  12. if c.flush {
  13. retx := c.Db.Where(`strftime("%s", until) < strftime("%s", "now")`).Delete(types.BanApplication{})
  14. if retx.RowsAffected > 0 {
  15. log.Infof("Flushed %d expired entries from Ban Application", retx.RowsAffected)
  16. }
  17. } else {
  18. log.Infof("flush is disabled")
  19. }
  20. return nil
  21. }
  22. func (c *Context) Flush() error {
  23. c.lock.Lock()
  24. defer c.lock.Unlock()
  25. ret := c.tx.Commit()
  26. if ret.Error != nil {
  27. c.tx = c.Db.Begin()
  28. return fmt.Errorf("failed to commit records : %v", ret.Error)
  29. }
  30. c.tx = c.Db.Begin()
  31. c.lastCommit = time.Now()
  32. return nil
  33. }
  34. func (c *Context) CleanUpRecordsByAge() error {
  35. //let's fetch all expired records that are more than XX days olds
  36. sos := []types.BanApplication{}
  37. if c.maxDurationRetention == 0 {
  38. return nil
  39. }
  40. //look for soft-deleted events that are OLDER than maxDurationRetention
  41. ret := c.Db.Unscoped().Table("ban_applications").Where("deleted_at is not NULL").
  42. Where(fmt.Sprintf("deleted_at > data('now','-%d minutes')", int(c.maxDurationRetention.Minutes()))).
  43. Order("updated_at desc").Find(&sos)
  44. if ret.Error != nil {
  45. return errors.Wrap(ret.Error, "failed to get count of old records")
  46. }
  47. //no events elligible
  48. if len(sos) == 0 || ret.RowsAffected == 0 {
  49. log.Infof("no event older than %s", c.maxDurationRetention.String())
  50. return nil
  51. }
  52. //let's do it in a single transaction
  53. delTx := c.Db.Unscoped().Begin()
  54. delRecords := 0
  55. for _, record := range sos {
  56. copy := record
  57. delTx.Unscoped().Table("signal_occurences").Where("ID = ?", copy.SignalOccurenceID).Delete(&types.SignalOccurence{})
  58. delTx.Unscoped().Table("event_sequences").Where("signal_occurence_id = ?", copy.SignalOccurenceID).Delete(&types.EventSequence{})
  59. delTx.Unscoped().Table("ban_applications").Delete(&copy)
  60. //we need to delete associations : event_sequences, signal_occurences
  61. delRecords++
  62. }
  63. ret = delTx.Unscoped().Commit()
  64. if ret.Error != nil {
  65. return errors.Wrap(ret.Error, "failed to delete records")
  66. }
  67. log.Printf("Deleted %d expired records older than %s", delRecords, c.maxDurationRetention)
  68. return nil
  69. }
  70. func (c *Context) CleanUpRecordsByCount() error {
  71. var count int
  72. if c.maxEventRetention <= 0 {
  73. return nil
  74. }
  75. ret := c.Db.Unscoped().Table("ban_applications").Order("updated_at desc").Count(&count)
  76. if ret.Error != nil {
  77. return errors.Wrap(ret.Error, "failed to get bans count")
  78. }
  79. if count < c.maxEventRetention {
  80. log.Infof("%d < %d, don't cleanup", count, c.maxEventRetention)
  81. return nil
  82. }
  83. sos := []types.BanApplication{}
  84. /*get soft deleted records oldest to youngest*/
  85. records := c.Db.Unscoped().Table("ban_applications").Where("deleted_at is not NULL").Where(`strftime("%s", deleted_at) < strftime("%s", "now")`).Find(&sos)
  86. if records.Error != nil {
  87. return errors.Wrap(records.Error, "failed to list expired bans for flush")
  88. }
  89. //let's do it in a single transaction
  90. delTx := c.Db.Unscoped().Begin()
  91. delRecords := 0
  92. for _, ld := range sos {
  93. copy := ld
  94. delTx.Unscoped().Table("signal_occurences").Where("ID = ?", copy.SignalOccurenceID).Delete(&types.SignalOccurence{})
  95. delTx.Unscoped().Table("event_sequences").Where("signal_occurence_id = ?", copy.SignalOccurenceID).Delete(&types.EventSequence{})
  96. delTx.Unscoped().Table("ban_applications").Delete(&copy)
  97. //we need to delete associations : event_sequences, signal_occurences
  98. delRecords++
  99. //let's delete as well the associated event_sequence
  100. if count-delRecords <= c.maxEventRetention {
  101. break
  102. }
  103. }
  104. if len(sos) > 0 {
  105. log.Printf("Deleting %d soft-deleted results out of %d total events (%d soft-deleted)", delRecords, count, len(sos))
  106. ret = delTx.Unscoped().Commit()
  107. if ret.Error != nil {
  108. return errors.Wrap(ret.Error, "failed to delete records")
  109. }
  110. } else {
  111. log.Debugf("didn't find any record to clean")
  112. }
  113. return nil
  114. }
  115. func (c *Context) AutoCommit() {
  116. log.Warningf("starting autocommit")
  117. ticker := time.NewTicker(200 * time.Millisecond)
  118. cleanUpTicker := time.NewTicker(1 * time.Minute)
  119. expireTicker := time.NewTicker(1 * time.Second)
  120. for {
  121. select {
  122. case <-c.PusherTomb.Dying():
  123. //we need to shutdown
  124. log.Infof("sqlite routine shutdown")
  125. if err := c.Flush(); err != nil {
  126. log.Errorf("error while flushing records: %s", err)
  127. }
  128. if ret := c.tx.Commit(); ret.Error != nil {
  129. log.Errorf("failed to commit records : %v", ret.Error)
  130. }
  131. if err := c.tx.Close(); err != nil {
  132. log.Errorf("error while closing tx : %s", err)
  133. }
  134. if err := c.Db.Close(); err != nil {
  135. log.Errorf("error while closing db : %s", err)
  136. }
  137. return
  138. case <-expireTicker.C:
  139. if err := c.DeleteExpired(); err != nil {
  140. log.Errorf("Error while deleting expired records: %s", err)
  141. }
  142. case <-ticker.C:
  143. if atomic.LoadInt32(&c.count) != 0 &&
  144. (atomic.LoadInt32(&c.count)%100 == 0 || time.Since(c.lastCommit) >= 500*time.Millisecond) {
  145. if err := c.Flush(); err != nil {
  146. log.Errorf("failed to flush : %s", err)
  147. }
  148. }
  149. case <-cleanUpTicker.C:
  150. if err := c.CleanUpRecordsByCount(); err != nil {
  151. log.Errorf("error in max records cleanup : %s", err)
  152. }
  153. if err := c.CleanUpRecordsByAge(); err != nil {
  154. log.Errorf("error in old records cleanup : %s", err)
  155. }
  156. }
  157. }
  158. }