sqlite.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package sqlite
  2. import (
  3. "fmt"
  4. "strconv"
  5. "sync"
  6. "time"
  7. "github.com/crowdsecurity/crowdsec/pkg/types"
  8. log "github.com/sirupsen/logrus"
  9. "github.com/jinzhu/gorm"
  10. _ "github.com/jinzhu/gorm/dialects/sqlite"
  11. _ "github.com/mattn/go-sqlite3"
  12. "gopkg.in/tomb.v2"
  13. )
  14. type Context struct {
  15. Db *gorm.DB //Pointer to sqlite db
  16. tx *gorm.DB //Pointer to current transaction (flushed on a regular basis)
  17. lastCommit time.Time
  18. flush bool
  19. count int32
  20. lock sync.Mutex //booboo
  21. PusherTomb tomb.Tomb
  22. //to manage auto cleanup : max number of records *or* oldest
  23. maxEventRetention int
  24. maxDurationRetention time.Duration
  25. }
  26. func NewSQLite(cfg map[string]string) (*Context, error) {
  27. var err error
  28. c := &Context{}
  29. log.Warningf("NEW SQLITE : %+v", cfg)
  30. if _, ok := cfg["db_path"]; !ok {
  31. return nil, fmt.Errorf("please specify a 'db_path' to SQLite db in the configuration")
  32. }
  33. if cfg["db_path"] == "" {
  34. return nil, fmt.Errorf("please specify a 'db_path' to SQLite db in the configuration")
  35. }
  36. c.Db, err = gorm.Open("sqlite3", cfg["db_path"]+"?_busy_timeout=1000")
  37. if err != nil {
  38. return nil, fmt.Errorf("failed to open %s : %s", cfg["db_path"], err)
  39. }
  40. if val, ok := cfg["debug"]; ok && val == "true" {
  41. log.Infof("Enabling debug for sqlite")
  42. c.Db.LogMode(true)
  43. }
  44. c.Db.LogMode(true)
  45. c.flush, _ = strconv.ParseBool(cfg["flush"])
  46. // Migrate the schema
  47. c.Db.AutoMigrate(&types.EventSequence{}, &types.SignalOccurence{}, &types.BanApplication{})
  48. c.Db.Model(&types.SignalOccurence{}).Related(&types.EventSequence{})
  49. c.Db.Model(&types.SignalOccurence{}).Related(&types.BanApplication{})
  50. c.tx = c.Db.Begin()
  51. c.lastCommit = time.Now()
  52. ret := c.tx.Commit()
  53. if ret.Error != nil {
  54. return nil, fmt.Errorf("failed to commit records : %v", ret.Error)
  55. }
  56. c.tx = c.Db.Begin()
  57. if c.tx == nil {
  58. return nil, fmt.Errorf("failed to begin sqlite transac : %s", err)
  59. }
  60. //random attempt
  61. c.maxEventRetention = 100
  62. c.PusherTomb.Go(func() error {
  63. c.AutoCommit()
  64. return nil
  65. })
  66. return c, nil
  67. }