commit.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package sqlite
  2. import (
  3. "fmt"
  4. "sync/atomic"
  5. "time"
  6. "github.com/crowdsecurity/crowdsec/pkg/types"
  7. log "github.com/sirupsen/logrus"
  8. )
  9. func (c *Context) Flush() error {
  10. c.lock.Lock()
  11. defer c.lock.Unlock()
  12. ret := c.tx.Commit()
  13. if ret.Error != nil {
  14. c.tx = c.Db.Begin()
  15. return fmt.Errorf("failed to commit records : %v", ret.Error)
  16. }
  17. c.tx = c.Db.Begin()
  18. c.lastCommit = time.Now()
  19. //Delete the expired records
  20. if c.flush {
  21. retx := c.Db.Where(`strftime("%s", until) < strftime("%s", "now")`).Delete(types.BanApplication{})
  22. if retx.RowsAffected > 0 {
  23. log.Infof("Flushed %d expired entries from Ban Application", retx.RowsAffected)
  24. }
  25. }
  26. return nil
  27. }
  28. func (c *Context) AutoCommit() {
  29. ticker := time.NewTicker(200 * time.Millisecond)
  30. for {
  31. select {
  32. case <-c.PusherTomb.Dying():
  33. //we need to shutdown
  34. log.Infof("sqlite routine shutdown")
  35. if err := c.Flush(); err != nil {
  36. log.Warningf("error while flushing records: %s", err)
  37. }
  38. if err := c.Db.Close(); err != nil {
  39. log.Warningf("error while closing db : %s", err)
  40. }
  41. return
  42. case <-ticker.C:
  43. if atomic.LoadInt32(&c.count) != 0 &&
  44. (atomic.LoadInt32(&c.count)%100 == 0 || time.Since(c.lastCommit) >= 500*time.Millisecond) {
  45. if err := c.Flush(); err != nil {
  46. log.Errorf("failed to flush : %s", err)
  47. }
  48. }
  49. }
  50. }
  51. }