database.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. package database
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "os"
  7. "time"
  8. "entgo.io/ent/dialect"
  9. entsql "entgo.io/ent/dialect/sql"
  10. "github.com/crowdsecurity/crowdsec/pkg/csconfig"
  11. "github.com/crowdsecurity/crowdsec/pkg/database/ent"
  12. "github.com/crowdsecurity/crowdsec/pkg/types"
  13. "github.com/go-co-op/gocron"
  14. _ "github.com/go-sql-driver/mysql"
  15. _ "github.com/jackc/pgx/v4/stdlib"
  16. _ "github.com/lib/pq"
  17. _ "github.com/mattn/go-sqlite3"
  18. "github.com/pkg/errors"
  19. log "github.com/sirupsen/logrus"
  20. )
  21. type Client struct {
  22. Ent *ent.Client
  23. CTX context.Context
  24. Log *log.Logger
  25. CanFlush bool
  26. }
  27. func getEntDriver(dbtype string, dbdialect string, dsn string, config *csconfig.DatabaseCfg) (*entsql.Driver, error) {
  28. db, err := sql.Open(dbtype, dsn)
  29. if err != nil {
  30. return nil, err
  31. }
  32. if config.MaxOpenConns == nil {
  33. log.Warningf("MaxOpenConns is 0, defaulting to %d", csconfig.DEFAULT_MAX_OPEN_CONNS)
  34. config.MaxOpenConns = types.IntPtr(csconfig.DEFAULT_MAX_OPEN_CONNS)
  35. }
  36. db.SetMaxOpenConns(*config.MaxOpenConns)
  37. drv := entsql.OpenDB(dbdialect, db)
  38. return drv, nil
  39. }
  40. func NewClient(config *csconfig.DatabaseCfg) (*Client, error) {
  41. var client *ent.Client
  42. var err error
  43. if config == nil {
  44. return &Client{}, fmt.Errorf("DB config is empty")
  45. }
  46. /*The logger that will be used by db operations*/
  47. clog := log.New()
  48. if err := types.ConfigureLogger(clog); err != nil {
  49. return nil, errors.Wrap(err, "while configuring db logger")
  50. }
  51. if config.LogLevel != nil {
  52. clog.SetLevel(*config.LogLevel)
  53. }
  54. entLogger := clog.WithField("context", "ent")
  55. entOpt := ent.Log(entLogger.Debug)
  56. switch config.Type {
  57. case "sqlite":
  58. /*if it's the first startup, we want to touch and chmod file*/
  59. if _, err := os.Stat(config.DbPath); os.IsNotExist(err) {
  60. f, err := os.OpenFile(config.DbPath, os.O_CREATE|os.O_RDWR, 0600)
  61. if err != nil {
  62. return &Client{}, errors.Wrapf(err, "failed to create SQLite database file %q", config.DbPath)
  63. }
  64. if err := f.Close(); err != nil {
  65. return &Client{}, errors.Wrapf(err, "failed to create SQLite database file %q", config.DbPath)
  66. }
  67. } else { /*ensure file perms*/
  68. if err := os.Chmod(config.DbPath, 0660); err != nil {
  69. return &Client{}, fmt.Errorf("unable to set perms on %s: %v", config.DbPath, err)
  70. }
  71. }
  72. if config.UseWal == nil {
  73. entLogger.Warn("you are using sqlite without WAL, this can have an impact of performance. If you do not store the database in a network share, set db_config.use_wal to true. Set to false to disable this warning")
  74. }
  75. var sqliteConnectionStringParameters string
  76. if config.UseWal != nil && *config.UseWal {
  77. sqliteConnectionStringParameters = "_busy_timeout=100000&_fk=1&_journal_mode=WAL"
  78. } else {
  79. sqliteConnectionStringParameters = "_busy_timeout=100000&_fk=1"
  80. }
  81. drv, err := getEntDriver("sqlite3", dialect.SQLite, fmt.Sprintf("file:%s?%s", config.DbPath, sqliteConnectionStringParameters), config)
  82. if err != nil {
  83. return &Client{}, errors.Wrapf(err, "failed opening connection to sqlite: %v", config.DbPath)
  84. }
  85. client = ent.NewClient(ent.Driver(drv), entOpt)
  86. case "mysql":
  87. drv, err := getEntDriver("mysql", dialect.MySQL, fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=True", config.User, config.Password, config.Host, config.Port, config.DbName), config)
  88. if err != nil {
  89. return &Client{}, fmt.Errorf("failed opening connection to mysql: %v", err)
  90. }
  91. client = ent.NewClient(ent.Driver(drv), entOpt)
  92. case "postgres", "postgresql":
  93. drv, err := getEntDriver("postgres", dialect.Postgres, fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s sslmode=%s", config.Host, config.Port, config.User, config.DbName, config.Password, config.Sslmode), config)
  94. if err != nil {
  95. return &Client{}, fmt.Errorf("failed opening connection to postgresql: %v", err)
  96. }
  97. client = ent.NewClient(ent.Driver(drv), entOpt)
  98. case "pgx":
  99. drv, err := getEntDriver("pgx", dialect.Postgres, fmt.Sprintf("postgresql://%s:%s@%s:%d/%s?sslmode=%s", config.User, config.Password, config.Host, config.Port, config.DbName, config.Sslmode), config)
  100. if err != nil {
  101. return &Client{}, fmt.Errorf("failed opening connection to pgx: %v", err)
  102. }
  103. client = ent.NewClient(ent.Driver(drv), entOpt)
  104. default:
  105. return &Client{}, fmt.Errorf("unknown database type '%s'", config.Type)
  106. }
  107. if config.LogLevel != nil && *config.LogLevel >= log.DebugLevel {
  108. clog.Debugf("Enabling request debug")
  109. client = client.Debug()
  110. }
  111. if err = client.Schema.Create(context.Background()); err != nil {
  112. return nil, fmt.Errorf("failed creating schema resources: %v", err)
  113. }
  114. return &Client{Ent: client, CTX: context.Background(), Log: clog, CanFlush: true}, nil
  115. }
  116. func (c *Client) StartFlushScheduler(config *csconfig.FlushDBCfg) (*gocron.Scheduler, error) {
  117. maxItems := 0
  118. maxAge := ""
  119. if config.MaxItems != nil && *config.MaxItems <= 0 {
  120. return nil, fmt.Errorf("max_items can't be zero or negative number")
  121. }
  122. if config.MaxItems != nil {
  123. maxItems = *config.MaxItems
  124. }
  125. if config.MaxAge != nil && *config.MaxAge != "" {
  126. maxAge = *config.MaxAge
  127. }
  128. // Init & Start cronjob every minute for alerts
  129. scheduler := gocron.NewScheduler(time.UTC)
  130. job, err := scheduler.Every(1).Minute().Do(c.FlushAlerts, maxAge, maxItems)
  131. if err != nil {
  132. return nil, errors.Wrap(err, "while starting FlushAlerts scheduler")
  133. }
  134. job.SingletonMode()
  135. // Init & Start cronjob every hour for bouncers/agents
  136. if config.AgentsGC != nil {
  137. if config.AgentsGC.Cert != nil {
  138. duration, err := types.ParseDuration(*config.AgentsGC.Cert)
  139. if err != nil {
  140. return nil, errors.Wrap(err, "while parsing agents cert auto-delete duration")
  141. }
  142. config.AgentsGC.CertDuration = &duration
  143. }
  144. if config.AgentsGC.LoginPassword != nil {
  145. duration, err := types.ParseDuration(*config.AgentsGC.LoginPassword)
  146. if err != nil {
  147. return nil, errors.Wrap(err, "while parsing agents login/password auto-delete duration")
  148. }
  149. config.AgentsGC.LoginPasswordDuration = &duration
  150. }
  151. if config.AgentsGC.Api != nil {
  152. log.Warning("agents auto-delete for API auth is not supported (use cert or login_password)")
  153. }
  154. }
  155. if config.BouncersGC != nil {
  156. if config.BouncersGC.Cert != nil {
  157. duration, err := types.ParseDuration(*config.BouncersGC.Cert)
  158. if err != nil {
  159. return nil, errors.Wrap(err, "while parsing bouncers cert auto-delete duration")
  160. }
  161. config.BouncersGC.CertDuration = &duration
  162. }
  163. if config.BouncersGC.Api != nil {
  164. duration, err := types.ParseDuration(*config.BouncersGC.Api)
  165. if err != nil {
  166. return nil, errors.Wrap(err, "while parsing bouncers api auto-delete duration")
  167. }
  168. config.BouncersGC.ApiDuration = &duration
  169. }
  170. if config.BouncersGC.LoginPassword != nil {
  171. log.Warning("bouncers auto-delete for login/password auth is not supported (use cert or api)")
  172. }
  173. }
  174. baJob, err := scheduler.Every(1).Minute().Do(c.FlushAgentsAndBouncers, config.AgentsGC, config.BouncersGC)
  175. if err != nil {
  176. return nil, errors.Wrap(err, "while starting FlushAgentsAndBouncers scheduler")
  177. }
  178. baJob.SingletonMode()
  179. scheduler.StartAsync()
  180. return scheduler, nil
  181. }