write.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package database
  2. import (
  3. "fmt"
  4. "sync/atomic"
  5. "github.com/crowdsecurity/crowdsec/pkg/types"
  6. log "github.com/sirupsen/logrus"
  7. )
  8. //we simply append the event to the transaction
  9. func (c *Context) WriteBanApplication(ban types.BanApplication) error {
  10. atomic.AddInt32(&c.count, 1)
  11. c.lock.Lock()
  12. defer c.lock.Unlock()
  13. log.Debugf("Ban application being called : %s %s", ban.Scenario, ban.IpText)
  14. ret := c.Db.Where(types.BanApplication{IpText: ban.IpText}).Assign(types.BanApplication{Until: ban.Until}).Assign(types.BanApplication{Reason: ban.Reason}).Assign(types.BanApplication{MeasureType: ban.MeasureType}).FirstOrCreate(&ban)
  15. if ret.Error != nil {
  16. return fmt.Errorf("failed to write ban record : %v", ret.Error)
  17. }
  18. return nil
  19. }
  20. func (c *Context) WriteSignal(sig types.SignalOccurence) error {
  21. atomic.AddInt32(&c.count, 1)
  22. c.lock.Lock()
  23. defer c.lock.Unlock()
  24. /*let's ensure we only have one ban active for a given scope*/
  25. for _, ba := range sig.BanApplications {
  26. ret := c.Db.Where("ip_text = ?", ba.IpText).Delete(types.BanApplication{})
  27. if ret.Error != nil {
  28. log.Errorf("While delete overlaping bans : %s", ret.Error)
  29. return fmt.Errorf("failed to write signal occurrence : %v", ret.Error)
  30. }
  31. }
  32. /*and add the new one(s)*/
  33. ret := c.Db.Create(&sig)
  34. if ret.Error != nil {
  35. log.Errorf("While creating new bans : %s", ret.Error)
  36. return fmt.Errorf("failed to write signal occurrence : %s", ret.Error)
  37. }
  38. return nil
  39. }