commit.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. package database
  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. now := time.Now()
  13. if c.flush {
  14. //retx := c.Db.Where(`strftime("%s", until) < strftime("%s", "now")`).Delete(types.BanApplication{})
  15. retx := c.Db.Delete(types.BanApplication{}, "until < ?", now)
  16. if retx.RowsAffected > 0 {
  17. log.Infof("Flushed %d expired entries from Ban Application", retx.RowsAffected)
  18. }
  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 > date('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.Debugf("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("max_records_age: deleting %d events (max age:%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.Debugf("%d < %d, don't cleanup", count, c.maxEventRetention)
  81. return nil
  82. }
  83. sos := []types.BanApplication{}
  84. now := time.Now()
  85. /*get soft deleted records oldest to youngest*/
  86. //records := c.Db.Unscoped().Table("ban_applications").Where("deleted_at is not NULL").Where(`strftime("%s", deleted_at) < strftime("%s", "now")`).Find(&sos)
  87. records := c.Db.Unscoped().Table("ban_applications").Where("deleted_at is not NULL").Where("deleted_at < ?", now).Find(&sos)
  88. if records.Error != nil {
  89. return errors.Wrap(records.Error, "failed to list expired bans for flush")
  90. }
  91. //let's do it in a single transaction
  92. delTx := c.Db.Unscoped().Begin()
  93. delRecords := 0
  94. for _, ld := range sos {
  95. copy := ld
  96. delTx.Unscoped().Table("signal_occurences").Where("ID = ?", copy.SignalOccurenceID).Delete(&types.SignalOccurence{})
  97. delTx.Unscoped().Table("event_sequences").Where("signal_occurence_id = ?", copy.SignalOccurenceID).Delete(&types.EventSequence{})
  98. delTx.Unscoped().Table("ban_applications").Delete(&copy)
  99. //we need to delete associations : event_sequences, signal_occurences
  100. delRecords++
  101. //let's delete as well the associated event_sequence
  102. if count-delRecords <= c.maxEventRetention {
  103. break
  104. }
  105. }
  106. if len(sos) > 0 {
  107. //log.Printf("Deleting %d soft-deleted results out of %d total events (%d soft-deleted)", delRecords, count, len(sos))
  108. log.Printf("max_records: deleting %d events. (%d soft-deleted)", delRecords, len(sos))
  109. ret = delTx.Unscoped().Commit()
  110. if ret.Error != nil {
  111. return errors.Wrap(ret.Error, "failed to delete records")
  112. }
  113. } else {
  114. log.Debugf("didn't find any record to clean")
  115. }
  116. return nil
  117. }
  118. func (c *Context) StartAutoCommit() error {
  119. //TBD : we shouldn't start auto-commit if we are in cli mode ?
  120. c.PusherTomb.Go(func() error {
  121. c.autoCommit()
  122. return nil
  123. })
  124. return nil
  125. }
  126. func (c *Context) autoCommit() {
  127. log.Debugf("starting autocommit")
  128. ticker := time.NewTicker(200 * time.Millisecond)
  129. cleanUpTicker := time.NewTicker(1 * time.Minute)
  130. expireTicker := time.NewTicker(1 * time.Second)
  131. if !c.flush {
  132. log.Debugf("flush is disabled")
  133. }
  134. for {
  135. select {
  136. case <-c.PusherTomb.Dying():
  137. //we need to shutdown
  138. log.Infof("database routine shutdown")
  139. if err := c.Flush(); err != nil {
  140. log.Errorf("error while flushing records: %s", err)
  141. }
  142. if ret := c.tx.Commit(); ret.Error != nil {
  143. log.Errorf("failed to commit records : %v", ret.Error)
  144. }
  145. if err := c.tx.Close(); err != nil {
  146. log.Errorf("error while closing tx : %s", err)
  147. }
  148. if err := c.Db.Close(); err != nil {
  149. log.Errorf("error while closing db : %s", err)
  150. }
  151. return
  152. case <-expireTicker.C:
  153. if err := c.DeleteExpired(); err != nil {
  154. log.Errorf("Error while deleting expired records: %s", err)
  155. }
  156. case <-ticker.C:
  157. if atomic.LoadInt32(&c.count) != 0 &&
  158. (atomic.LoadInt32(&c.count)%100 == 0 || time.Since(c.lastCommit) >= 500*time.Millisecond) {
  159. if err := c.Flush(); err != nil {
  160. log.Errorf("failed to flush : %s", err)
  161. }
  162. }
  163. case <-cleanUpTicker.C:
  164. if err := c.CleanUpRecordsByCount(); err != nil {
  165. log.Errorf("error in max records cleanup : %s", err)
  166. }
  167. if err := c.CleanUpRecordsByAge(); err != nil {
  168. log.Errorf("error in old records cleanup : %s", err)
  169. }
  170. }
  171. }
  172. }