Просмотр исходного кода

implement highAvailability feature (#2506)

* implement highAvailability feature
---------

Co-authored-by: Marco Mariani <marco@crowdsec.net>
he2ss 1 год назад
Родитель
Сommit
97c441dab6

+ 12 - 0
pkg/apiserver/apic.go

@@ -633,6 +633,13 @@ func (a *apic) PullTop(forcePull bool) error {
 		}
 	}
 
+	log.Debug("Acquiring lock for pullCAPI")
+	err = a.dbClient.AcquirePullCAPILock()
+	if a.dbClient.IsLocked(err) {
+		log.Info("PullCAPI is already running, skipping")
+		return nil
+	}
+
 	log.Infof("Starting community-blocklist update")
 
 	data, _, err := a.apiClient.Decisions.GetStreamV3(context.Background(), apiclient.DecisionsStreamOpts{Startup: a.startup})
@@ -684,6 +691,11 @@ func (a *apic) PullTop(forcePull bool) error {
 		return fmt.Errorf("while updating blocklists: %w", err)
 	}
 
+	log.Debug("Releasing lock for pullCAPI")
+	if err := a.dbClient.ReleasePullCAPILock(); err != nil {
+		return fmt.Errorf("while releasing lock: %w", err)
+	}
+
 	return nil
 }
 

+ 4 - 4
pkg/apiserver/apic_metrics_test.go

@@ -26,15 +26,15 @@ func TestAPICSendMetrics(t *testing.T) {
 	}{
 		{
 			name:            "basic",
-			duration:        time.Millisecond * 60,
-			metricsInterval: time.Millisecond * 10,
+			duration:        time.Millisecond * 120,
+			metricsInterval: time.Millisecond * 20,
 			expectedCalls:   5,
 			setUp:           func(api *apic) {},
 		},
 		{
 			name:            "with some metrics",
-			duration:        time.Millisecond * 60,
-			metricsInterval: time.Millisecond * 10,
+			duration:        time.Millisecond * 120,
+			metricsInterval: time.Millisecond * 20,
 			expectedCalls:   5,
 			setUp: func(api *apic) {
 				api.dbClient.Ent.Machine.Delete().ExecX(context.Background())

+ 148 - 4
pkg/database/ent/client.go

@@ -20,6 +20,7 @@ import (
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/decision"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/event"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/meta"
 )
@@ -39,6 +40,8 @@ type Client struct {
 	Decision *DecisionClient
 	// Event is the client for interacting with the Event builders.
 	Event *EventClient
+	// Lock is the client for interacting with the Lock builders.
+	Lock *LockClient
 	// Machine is the client for interacting with the Machine builders.
 	Machine *MachineClient
 	// Meta is the client for interacting with the Meta builders.
@@ -61,6 +64,7 @@ func (c *Client) init() {
 	c.ConfigItem = NewConfigItemClient(c.config)
 	c.Decision = NewDecisionClient(c.config)
 	c.Event = NewEventClient(c.config)
+	c.Lock = NewLockClient(c.config)
 	c.Machine = NewMachineClient(c.config)
 	c.Meta = NewMetaClient(c.config)
 }
@@ -153,6 +157,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
 		ConfigItem: NewConfigItemClient(cfg),
 		Decision:   NewDecisionClient(cfg),
 		Event:      NewEventClient(cfg),
+		Lock:       NewLockClient(cfg),
 		Machine:    NewMachineClient(cfg),
 		Meta:       NewMetaClient(cfg),
 	}, nil
@@ -179,6 +184,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
 		ConfigItem: NewConfigItemClient(cfg),
 		Decision:   NewDecisionClient(cfg),
 		Event:      NewEventClient(cfg),
+		Lock:       NewLockClient(cfg),
 		Machine:    NewMachineClient(cfg),
 		Meta:       NewMetaClient(cfg),
 	}, nil
@@ -210,7 +216,8 @@ func (c *Client) Close() error {
 // In order to add hooks to a specific client, call: `client.Node.Use(...)`.
 func (c *Client) Use(hooks ...Hook) {
 	for _, n := range []interface{ Use(...Hook) }{
-		c.Alert, c.Bouncer, c.ConfigItem, c.Decision, c.Event, c.Machine, c.Meta,
+		c.Alert, c.Bouncer, c.ConfigItem, c.Decision, c.Event, c.Lock, c.Machine,
+		c.Meta,
 	} {
 		n.Use(hooks...)
 	}
@@ -220,7 +227,8 @@ func (c *Client) Use(hooks ...Hook) {
 // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
 func (c *Client) Intercept(interceptors ...Interceptor) {
 	for _, n := range []interface{ Intercept(...Interceptor) }{
-		c.Alert, c.Bouncer, c.ConfigItem, c.Decision, c.Event, c.Machine, c.Meta,
+		c.Alert, c.Bouncer, c.ConfigItem, c.Decision, c.Event, c.Lock, c.Machine,
+		c.Meta,
 	} {
 		n.Intercept(interceptors...)
 	}
@@ -239,6 +247,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
 		return c.Decision.mutate(ctx, m)
 	case *EventMutation:
 		return c.Event.mutate(ctx, m)
+	case *LockMutation:
+		return c.Lock.mutate(ctx, m)
 	case *MachineMutation:
 		return c.Machine.mutate(ctx, m)
 	case *MetaMutation:
@@ -1009,6 +1019,139 @@ func (c *EventClient) mutate(ctx context.Context, m *EventMutation) (Value, erro
 	}
 }
 
+// LockClient is a client for the Lock schema.
+type LockClient struct {
+	config
+}
+
+// NewLockClient returns a client for the Lock from the given config.
+func NewLockClient(c config) *LockClient {
+	return &LockClient{config: c}
+}
+
+// Use adds a list of mutation hooks to the hooks stack.
+// A call to `Use(f, g, h)` equals to `lock.Hooks(f(g(h())))`.
+func (c *LockClient) Use(hooks ...Hook) {
+	c.hooks.Lock = append(c.hooks.Lock, hooks...)
+}
+
+// Intercept adds a list of query interceptors to the interceptors stack.
+// A call to `Intercept(f, g, h)` equals to `lock.Intercept(f(g(h())))`.
+func (c *LockClient) Intercept(interceptors ...Interceptor) {
+	c.inters.Lock = append(c.inters.Lock, interceptors...)
+}
+
+// Create returns a builder for creating a Lock entity.
+func (c *LockClient) Create() *LockCreate {
+	mutation := newLockMutation(c.config, OpCreate)
+	return &LockCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// CreateBulk returns a builder for creating a bulk of Lock entities.
+func (c *LockClient) CreateBulk(builders ...*LockCreate) *LockCreateBulk {
+	return &LockCreateBulk{config: c.config, builders: builders}
+}
+
+// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
+// a builder and applies setFunc on it.
+func (c *LockClient) MapCreateBulk(slice any, setFunc func(*LockCreate, int)) *LockCreateBulk {
+	rv := reflect.ValueOf(slice)
+	if rv.Kind() != reflect.Slice {
+		return &LockCreateBulk{err: fmt.Errorf("calling to LockClient.MapCreateBulk with wrong type %T, need slice", slice)}
+	}
+	builders := make([]*LockCreate, rv.Len())
+	for i := 0; i < rv.Len(); i++ {
+		builders[i] = c.Create()
+		setFunc(builders[i], i)
+	}
+	return &LockCreateBulk{config: c.config, builders: builders}
+}
+
+// Update returns an update builder for Lock.
+func (c *LockClient) Update() *LockUpdate {
+	mutation := newLockMutation(c.config, OpUpdate)
+	return &LockUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOne returns an update builder for the given entity.
+func (c *LockClient) UpdateOne(l *Lock) *LockUpdateOne {
+	mutation := newLockMutation(c.config, OpUpdateOne, withLock(l))
+	return &LockUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// UpdateOneID returns an update builder for the given id.
+func (c *LockClient) UpdateOneID(id int) *LockUpdateOne {
+	mutation := newLockMutation(c.config, OpUpdateOne, withLockID(id))
+	return &LockUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// Delete returns a delete builder for Lock.
+func (c *LockClient) Delete() *LockDelete {
+	mutation := newLockMutation(c.config, OpDelete)
+	return &LockDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
+}
+
+// DeleteOne returns a builder for deleting the given entity.
+func (c *LockClient) DeleteOne(l *Lock) *LockDeleteOne {
+	return c.DeleteOneID(l.ID)
+}
+
+// DeleteOneID returns a builder for deleting the given entity by its id.
+func (c *LockClient) DeleteOneID(id int) *LockDeleteOne {
+	builder := c.Delete().Where(lock.ID(id))
+	builder.mutation.id = &id
+	builder.mutation.op = OpDeleteOne
+	return &LockDeleteOne{builder}
+}
+
+// Query returns a query builder for Lock.
+func (c *LockClient) Query() *LockQuery {
+	return &LockQuery{
+		config: c.config,
+		ctx:    &QueryContext{Type: TypeLock},
+		inters: c.Interceptors(),
+	}
+}
+
+// Get returns a Lock entity by its id.
+func (c *LockClient) Get(ctx context.Context, id int) (*Lock, error) {
+	return c.Query().Where(lock.ID(id)).Only(ctx)
+}
+
+// GetX is like Get, but panics if an error occurs.
+func (c *LockClient) GetX(ctx context.Context, id int) *Lock {
+	obj, err := c.Get(ctx, id)
+	if err != nil {
+		panic(err)
+	}
+	return obj
+}
+
+// Hooks returns the client hooks.
+func (c *LockClient) Hooks() []Hook {
+	return c.hooks.Lock
+}
+
+// Interceptors returns the client interceptors.
+func (c *LockClient) Interceptors() []Interceptor {
+	return c.inters.Lock
+}
+
+func (c *LockClient) mutate(ctx context.Context, m *LockMutation) (Value, error) {
+	switch m.Op() {
+	case OpCreate:
+		return (&LockCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+	case OpUpdate:
+		return (&LockUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+	case OpUpdateOne:
+		return (&LockUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
+	case OpDelete, OpDeleteOne:
+		return (&LockDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
+	default:
+		return nil, fmt.Errorf("ent: unknown Lock mutation op: %q", m.Op())
+	}
+}
+
 // MachineClient is a client for the Machine schema.
 type MachineClient struct {
 	config
@@ -1310,9 +1453,10 @@ func (c *MetaClient) mutate(ctx context.Context, m *MetaMutation) (Value, error)
 // hooks and interceptors per client, for fast access.
 type (
 	hooks struct {
-		Alert, Bouncer, ConfigItem, Decision, Event, Machine, Meta []ent.Hook
+		Alert, Bouncer, ConfigItem, Decision, Event, Lock, Machine, Meta []ent.Hook
 	}
 	inters struct {
-		Alert, Bouncer, ConfigItem, Decision, Event, Machine, Meta []ent.Interceptor
+		Alert, Bouncer, ConfigItem, Decision, Event, Lock, Machine,
+		Meta []ent.Interceptor
 	}
 )

+ 2 - 0
pkg/database/ent/ent.go

@@ -17,6 +17,7 @@ import (
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/decision"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/event"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/meta"
 )
@@ -84,6 +85,7 @@ func checkColumn(table, column string) error {
 			configitem.Table: configitem.ValidColumn,
 			decision.Table:   decision.ValidColumn,
 			event.Table:      event.ValidColumn,
+			lock.Table:       lock.ValidColumn,
 			machine.Table:    machine.ValidColumn,
 			meta.Table:       meta.ValidColumn,
 		})

+ 12 - 0
pkg/database/ent/hook/hook.go

@@ -69,6 +69,18 @@ func (f EventFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error
 	return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.EventMutation", m)
 }
 
+// The LockFunc type is an adapter to allow the use of ordinary
+// function as Lock mutator.
+type LockFunc func(context.Context, *ent.LockMutation) (ent.Value, error)
+
+// Mutate calls f(ctx, m).
+func (f LockFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
+	if mv, ok := m.(*ent.LockMutation); ok {
+		return f(ctx, mv)
+	}
+	return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LockMutation", m)
+}
+
 // The MachineFunc type is an adapter to allow the use of ordinary
 // function as Machine mutator.
 type MachineFunc func(context.Context, *ent.MachineMutation) (ent.Value, error)

+ 117 - 0
pkg/database/ent/lock.go

@@ -0,0 +1,117 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+	"fmt"
+	"strings"
+	"time"
+
+	"entgo.io/ent"
+	"entgo.io/ent/dialect/sql"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
+)
+
+// Lock is the model entity for the Lock schema.
+type Lock struct {
+	config `json:"-"`
+	// ID of the ent.
+	ID int `json:"id,omitempty"`
+	// Name holds the value of the "name" field.
+	Name string `json:"name"`
+	// CreatedAt holds the value of the "created_at" field.
+	CreatedAt    time.Time `json:"created_at"`
+	selectValues sql.SelectValues
+}
+
+// scanValues returns the types for scanning values from sql.Rows.
+func (*Lock) scanValues(columns []string) ([]any, error) {
+	values := make([]any, len(columns))
+	for i := range columns {
+		switch columns[i] {
+		case lock.FieldID:
+			values[i] = new(sql.NullInt64)
+		case lock.FieldName:
+			values[i] = new(sql.NullString)
+		case lock.FieldCreatedAt:
+			values[i] = new(sql.NullTime)
+		default:
+			values[i] = new(sql.UnknownType)
+		}
+	}
+	return values, nil
+}
+
+// assignValues assigns the values that were returned from sql.Rows (after scanning)
+// to the Lock fields.
+func (l *Lock) assignValues(columns []string, values []any) error {
+	if m, n := len(values), len(columns); m < n {
+		return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
+	}
+	for i := range columns {
+		switch columns[i] {
+		case lock.FieldID:
+			value, ok := values[i].(*sql.NullInt64)
+			if !ok {
+				return fmt.Errorf("unexpected type %T for field id", value)
+			}
+			l.ID = int(value.Int64)
+		case lock.FieldName:
+			if value, ok := values[i].(*sql.NullString); !ok {
+				return fmt.Errorf("unexpected type %T for field name", values[i])
+			} else if value.Valid {
+				l.Name = value.String
+			}
+		case lock.FieldCreatedAt:
+			if value, ok := values[i].(*sql.NullTime); !ok {
+				return fmt.Errorf("unexpected type %T for field created_at", values[i])
+			} else if value.Valid {
+				l.CreatedAt = value.Time
+			}
+		default:
+			l.selectValues.Set(columns[i], values[i])
+		}
+	}
+	return nil
+}
+
+// Value returns the ent.Value that was dynamically selected and assigned to the Lock.
+// This includes values selected through modifiers, order, etc.
+func (l *Lock) Value(name string) (ent.Value, error) {
+	return l.selectValues.Get(name)
+}
+
+// Update returns a builder for updating this Lock.
+// Note that you need to call Lock.Unwrap() before calling this method if this Lock
+// was returned from a transaction, and the transaction was committed or rolled back.
+func (l *Lock) Update() *LockUpdateOne {
+	return NewLockClient(l.config).UpdateOne(l)
+}
+
+// Unwrap unwraps the Lock entity that was returned from a transaction after it was closed,
+// so that all future queries will be executed through the driver which created the transaction.
+func (l *Lock) Unwrap() *Lock {
+	_tx, ok := l.config.driver.(*txDriver)
+	if !ok {
+		panic("ent: Lock is not a transactional entity")
+	}
+	l.config.driver = _tx.drv
+	return l
+}
+
+// String implements the fmt.Stringer.
+func (l *Lock) String() string {
+	var builder strings.Builder
+	builder.WriteString("Lock(")
+	builder.WriteString(fmt.Sprintf("id=%v, ", l.ID))
+	builder.WriteString("name=")
+	builder.WriteString(l.Name)
+	builder.WriteString(", ")
+	builder.WriteString("created_at=")
+	builder.WriteString(l.CreatedAt.Format(time.ANSIC))
+	builder.WriteByte(')')
+	return builder.String()
+}
+
+// Locks is a parsable slice of Lock.
+type Locks []*Lock

+ 62 - 0
pkg/database/ent/lock/lock.go

@@ -0,0 +1,62 @@
+// Code generated by ent, DO NOT EDIT.
+
+package lock
+
+import (
+	"time"
+
+	"entgo.io/ent/dialect/sql"
+)
+
+const (
+	// Label holds the string label denoting the lock type in the database.
+	Label = "lock"
+	// FieldID holds the string denoting the id field in the database.
+	FieldID = "id"
+	// FieldName holds the string denoting the name field in the database.
+	FieldName = "name"
+	// FieldCreatedAt holds the string denoting the created_at field in the database.
+	FieldCreatedAt = "created_at"
+	// Table holds the table name of the lock in the database.
+	Table = "locks"
+)
+
+// Columns holds all SQL columns for lock fields.
+var Columns = []string{
+	FieldID,
+	FieldName,
+	FieldCreatedAt,
+}
+
+// ValidColumn reports if the column name is valid (part of the table columns).
+func ValidColumn(column string) bool {
+	for i := range Columns {
+		if column == Columns[i] {
+			return true
+		}
+	}
+	return false
+}
+
+var (
+	// DefaultCreatedAt holds the default value on creation for the "created_at" field.
+	DefaultCreatedAt func() time.Time
+)
+
+// OrderOption defines the ordering options for the Lock queries.
+type OrderOption func(*sql.Selector)
+
+// ByID orders the results by the id field.
+func ByID(opts ...sql.OrderTermOption) OrderOption {
+	return sql.OrderByField(FieldID, opts...).ToFunc()
+}
+
+// ByName orders the results by the name field.
+func ByName(opts ...sql.OrderTermOption) OrderOption {
+	return sql.OrderByField(FieldName, opts...).ToFunc()
+}
+
+// ByCreatedAt orders the results by the created_at field.
+func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
+	return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
+}

+ 185 - 0
pkg/database/ent/lock/where.go

@@ -0,0 +1,185 @@
+// Code generated by ent, DO NOT EDIT.
+
+package lock
+
+import (
+	"time"
+
+	"entgo.io/ent/dialect/sql"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
+)
+
+// ID filters vertices based on their ID field.
+func ID(id int) predicate.Lock {
+	return predicate.Lock(sql.FieldEQ(FieldID, id))
+}
+
+// IDEQ applies the EQ predicate on the ID field.
+func IDEQ(id int) predicate.Lock {
+	return predicate.Lock(sql.FieldEQ(FieldID, id))
+}
+
+// IDNEQ applies the NEQ predicate on the ID field.
+func IDNEQ(id int) predicate.Lock {
+	return predicate.Lock(sql.FieldNEQ(FieldID, id))
+}
+
+// IDIn applies the In predicate on the ID field.
+func IDIn(ids ...int) predicate.Lock {
+	return predicate.Lock(sql.FieldIn(FieldID, ids...))
+}
+
+// IDNotIn applies the NotIn predicate on the ID field.
+func IDNotIn(ids ...int) predicate.Lock {
+	return predicate.Lock(sql.FieldNotIn(FieldID, ids...))
+}
+
+// IDGT applies the GT predicate on the ID field.
+func IDGT(id int) predicate.Lock {
+	return predicate.Lock(sql.FieldGT(FieldID, id))
+}
+
+// IDGTE applies the GTE predicate on the ID field.
+func IDGTE(id int) predicate.Lock {
+	return predicate.Lock(sql.FieldGTE(FieldID, id))
+}
+
+// IDLT applies the LT predicate on the ID field.
+func IDLT(id int) predicate.Lock {
+	return predicate.Lock(sql.FieldLT(FieldID, id))
+}
+
+// IDLTE applies the LTE predicate on the ID field.
+func IDLTE(id int) predicate.Lock {
+	return predicate.Lock(sql.FieldLTE(FieldID, id))
+}
+
+// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
+func Name(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldEQ(FieldName, v))
+}
+
+// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
+func CreatedAt(v time.Time) predicate.Lock {
+	return predicate.Lock(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// NameEQ applies the EQ predicate on the "name" field.
+func NameEQ(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldEQ(FieldName, v))
+}
+
+// NameNEQ applies the NEQ predicate on the "name" field.
+func NameNEQ(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldNEQ(FieldName, v))
+}
+
+// NameIn applies the In predicate on the "name" field.
+func NameIn(vs ...string) predicate.Lock {
+	return predicate.Lock(sql.FieldIn(FieldName, vs...))
+}
+
+// NameNotIn applies the NotIn predicate on the "name" field.
+func NameNotIn(vs ...string) predicate.Lock {
+	return predicate.Lock(sql.FieldNotIn(FieldName, vs...))
+}
+
+// NameGT applies the GT predicate on the "name" field.
+func NameGT(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldGT(FieldName, v))
+}
+
+// NameGTE applies the GTE predicate on the "name" field.
+func NameGTE(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldGTE(FieldName, v))
+}
+
+// NameLT applies the LT predicate on the "name" field.
+func NameLT(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldLT(FieldName, v))
+}
+
+// NameLTE applies the LTE predicate on the "name" field.
+func NameLTE(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldLTE(FieldName, v))
+}
+
+// NameContains applies the Contains predicate on the "name" field.
+func NameContains(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldContains(FieldName, v))
+}
+
+// NameHasPrefix applies the HasPrefix predicate on the "name" field.
+func NameHasPrefix(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldHasPrefix(FieldName, v))
+}
+
+// NameHasSuffix applies the HasSuffix predicate on the "name" field.
+func NameHasSuffix(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldHasSuffix(FieldName, v))
+}
+
+// NameEqualFold applies the EqualFold predicate on the "name" field.
+func NameEqualFold(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldEqualFold(FieldName, v))
+}
+
+// NameContainsFold applies the ContainsFold predicate on the "name" field.
+func NameContainsFold(v string) predicate.Lock {
+	return predicate.Lock(sql.FieldContainsFold(FieldName, v))
+}
+
+// CreatedAtEQ applies the EQ predicate on the "created_at" field.
+func CreatedAtEQ(v time.Time) predicate.Lock {
+	return predicate.Lock(sql.FieldEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
+func CreatedAtNEQ(v time.Time) predicate.Lock {
+	return predicate.Lock(sql.FieldNEQ(FieldCreatedAt, v))
+}
+
+// CreatedAtIn applies the In predicate on the "created_at" field.
+func CreatedAtIn(vs ...time.Time) predicate.Lock {
+	return predicate.Lock(sql.FieldIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
+func CreatedAtNotIn(vs ...time.Time) predicate.Lock {
+	return predicate.Lock(sql.FieldNotIn(FieldCreatedAt, vs...))
+}
+
+// CreatedAtGT applies the GT predicate on the "created_at" field.
+func CreatedAtGT(v time.Time) predicate.Lock {
+	return predicate.Lock(sql.FieldGT(FieldCreatedAt, v))
+}
+
+// CreatedAtGTE applies the GTE predicate on the "created_at" field.
+func CreatedAtGTE(v time.Time) predicate.Lock {
+	return predicate.Lock(sql.FieldGTE(FieldCreatedAt, v))
+}
+
+// CreatedAtLT applies the LT predicate on the "created_at" field.
+func CreatedAtLT(v time.Time) predicate.Lock {
+	return predicate.Lock(sql.FieldLT(FieldCreatedAt, v))
+}
+
+// CreatedAtLTE applies the LTE predicate on the "created_at" field.
+func CreatedAtLTE(v time.Time) predicate.Lock {
+	return predicate.Lock(sql.FieldLTE(FieldCreatedAt, v))
+}
+
+// And groups predicates with the AND operator between them.
+func And(predicates ...predicate.Lock) predicate.Lock {
+	return predicate.Lock(sql.AndPredicates(predicates...))
+}
+
+// Or groups predicates with the OR operator between them.
+func Or(predicates ...predicate.Lock) predicate.Lock {
+	return predicate.Lock(sql.OrPredicates(predicates...))
+}
+
+// Not applies the not operator on the given predicate.
+func Not(p predicate.Lock) predicate.Lock {
+	return predicate.Lock(sql.NotPredicates(p))
+}

+ 215 - 0
pkg/database/ent/lock_create.go

@@ -0,0 +1,215 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"time"
+
+	"entgo.io/ent/dialect/sql/sqlgraph"
+	"entgo.io/ent/schema/field"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
+)
+
+// LockCreate is the builder for creating a Lock entity.
+type LockCreate struct {
+	config
+	mutation *LockMutation
+	hooks    []Hook
+}
+
+// SetName sets the "name" field.
+func (lc *LockCreate) SetName(s string) *LockCreate {
+	lc.mutation.SetName(s)
+	return lc
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (lc *LockCreate) SetCreatedAt(t time.Time) *LockCreate {
+	lc.mutation.SetCreatedAt(t)
+	return lc
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (lc *LockCreate) SetNillableCreatedAt(t *time.Time) *LockCreate {
+	if t != nil {
+		lc.SetCreatedAt(*t)
+	}
+	return lc
+}
+
+// Mutation returns the LockMutation object of the builder.
+func (lc *LockCreate) Mutation() *LockMutation {
+	return lc.mutation
+}
+
+// Save creates the Lock in the database.
+func (lc *LockCreate) Save(ctx context.Context) (*Lock, error) {
+	lc.defaults()
+	return withHooks(ctx, lc.sqlSave, lc.mutation, lc.hooks)
+}
+
+// SaveX calls Save and panics if Save returns an error.
+func (lc *LockCreate) SaveX(ctx context.Context) *Lock {
+	v, err := lc.Save(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return v
+}
+
+// Exec executes the query.
+func (lc *LockCreate) Exec(ctx context.Context) error {
+	_, err := lc.Save(ctx)
+	return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (lc *LockCreate) ExecX(ctx context.Context) {
+	if err := lc.Exec(ctx); err != nil {
+		panic(err)
+	}
+}
+
+// defaults sets the default values of the builder before save.
+func (lc *LockCreate) defaults() {
+	if _, ok := lc.mutation.CreatedAt(); !ok {
+		v := lock.DefaultCreatedAt()
+		lc.mutation.SetCreatedAt(v)
+	}
+}
+
+// check runs all checks and user-defined validators on the builder.
+func (lc *LockCreate) check() error {
+	if _, ok := lc.mutation.Name(); !ok {
+		return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Lock.name"`)}
+	}
+	if _, ok := lc.mutation.CreatedAt(); !ok {
+		return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Lock.created_at"`)}
+	}
+	return nil
+}
+
+func (lc *LockCreate) sqlSave(ctx context.Context) (*Lock, error) {
+	if err := lc.check(); err != nil {
+		return nil, err
+	}
+	_node, _spec := lc.createSpec()
+	if err := sqlgraph.CreateNode(ctx, lc.driver, _spec); err != nil {
+		if sqlgraph.IsConstraintError(err) {
+			err = &ConstraintError{msg: err.Error(), wrap: err}
+		}
+		return nil, err
+	}
+	id := _spec.ID.Value.(int64)
+	_node.ID = int(id)
+	lc.mutation.id = &_node.ID
+	lc.mutation.done = true
+	return _node, nil
+}
+
+func (lc *LockCreate) createSpec() (*Lock, *sqlgraph.CreateSpec) {
+	var (
+		_node = &Lock{config: lc.config}
+		_spec = sqlgraph.NewCreateSpec(lock.Table, sqlgraph.NewFieldSpec(lock.FieldID, field.TypeInt))
+	)
+	if value, ok := lc.mutation.Name(); ok {
+		_spec.SetField(lock.FieldName, field.TypeString, value)
+		_node.Name = value
+	}
+	if value, ok := lc.mutation.CreatedAt(); ok {
+		_spec.SetField(lock.FieldCreatedAt, field.TypeTime, value)
+		_node.CreatedAt = value
+	}
+	return _node, _spec
+}
+
+// LockCreateBulk is the builder for creating many Lock entities in bulk.
+type LockCreateBulk struct {
+	config
+	err      error
+	builders []*LockCreate
+}
+
+// Save creates the Lock entities in the database.
+func (lcb *LockCreateBulk) Save(ctx context.Context) ([]*Lock, error) {
+	if lcb.err != nil {
+		return nil, lcb.err
+	}
+	specs := make([]*sqlgraph.CreateSpec, len(lcb.builders))
+	nodes := make([]*Lock, len(lcb.builders))
+	mutators := make([]Mutator, len(lcb.builders))
+	for i := range lcb.builders {
+		func(i int, root context.Context) {
+			builder := lcb.builders[i]
+			builder.defaults()
+			var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
+				mutation, ok := m.(*LockMutation)
+				if !ok {
+					return nil, fmt.Errorf("unexpected mutation type %T", m)
+				}
+				if err := builder.check(); err != nil {
+					return nil, err
+				}
+				builder.mutation = mutation
+				var err error
+				nodes[i], specs[i] = builder.createSpec()
+				if i < len(mutators)-1 {
+					_, err = mutators[i+1].Mutate(root, lcb.builders[i+1].mutation)
+				} else {
+					spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
+					// Invoke the actual operation on the latest mutation in the chain.
+					if err = sqlgraph.BatchCreate(ctx, lcb.driver, spec); err != nil {
+						if sqlgraph.IsConstraintError(err) {
+							err = &ConstraintError{msg: err.Error(), wrap: err}
+						}
+					}
+				}
+				if err != nil {
+					return nil, err
+				}
+				mutation.id = &nodes[i].ID
+				if specs[i].ID.Value != nil {
+					id := specs[i].ID.Value.(int64)
+					nodes[i].ID = int(id)
+				}
+				mutation.done = true
+				return nodes[i], nil
+			})
+			for i := len(builder.hooks) - 1; i >= 0; i-- {
+				mut = builder.hooks[i](mut)
+			}
+			mutators[i] = mut
+		}(i, ctx)
+	}
+	if len(mutators) > 0 {
+		if _, err := mutators[0].Mutate(ctx, lcb.builders[0].mutation); err != nil {
+			return nil, err
+		}
+	}
+	return nodes, nil
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (lcb *LockCreateBulk) SaveX(ctx context.Context) []*Lock {
+	v, err := lcb.Save(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return v
+}
+
+// Exec executes the query.
+func (lcb *LockCreateBulk) Exec(ctx context.Context) error {
+	_, err := lcb.Save(ctx)
+	return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (lcb *LockCreateBulk) ExecX(ctx context.Context) {
+	if err := lcb.Exec(ctx); err != nil {
+		panic(err)
+	}
+}

+ 88 - 0
pkg/database/ent/lock_delete.go

@@ -0,0 +1,88 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+	"context"
+
+	"entgo.io/ent/dialect/sql"
+	"entgo.io/ent/dialect/sql/sqlgraph"
+	"entgo.io/ent/schema/field"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
+)
+
+// LockDelete is the builder for deleting a Lock entity.
+type LockDelete struct {
+	config
+	hooks    []Hook
+	mutation *LockMutation
+}
+
+// Where appends a list predicates to the LockDelete builder.
+func (ld *LockDelete) Where(ps ...predicate.Lock) *LockDelete {
+	ld.mutation.Where(ps...)
+	return ld
+}
+
+// Exec executes the deletion query and returns how many vertices were deleted.
+func (ld *LockDelete) Exec(ctx context.Context) (int, error) {
+	return withHooks(ctx, ld.sqlExec, ld.mutation, ld.hooks)
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ld *LockDelete) ExecX(ctx context.Context) int {
+	n, err := ld.Exec(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return n
+}
+
+func (ld *LockDelete) sqlExec(ctx context.Context) (int, error) {
+	_spec := sqlgraph.NewDeleteSpec(lock.Table, sqlgraph.NewFieldSpec(lock.FieldID, field.TypeInt))
+	if ps := ld.mutation.predicates; len(ps) > 0 {
+		_spec.Predicate = func(selector *sql.Selector) {
+			for i := range ps {
+				ps[i](selector)
+			}
+		}
+	}
+	affected, err := sqlgraph.DeleteNodes(ctx, ld.driver, _spec)
+	if err != nil && sqlgraph.IsConstraintError(err) {
+		err = &ConstraintError{msg: err.Error(), wrap: err}
+	}
+	ld.mutation.done = true
+	return affected, err
+}
+
+// LockDeleteOne is the builder for deleting a single Lock entity.
+type LockDeleteOne struct {
+	ld *LockDelete
+}
+
+// Where appends a list predicates to the LockDelete builder.
+func (ldo *LockDeleteOne) Where(ps ...predicate.Lock) *LockDeleteOne {
+	ldo.ld.mutation.Where(ps...)
+	return ldo
+}
+
+// Exec executes the deletion query.
+func (ldo *LockDeleteOne) Exec(ctx context.Context) error {
+	n, err := ldo.ld.Exec(ctx)
+	switch {
+	case err != nil:
+		return err
+	case n == 0:
+		return &NotFoundError{lock.Label}
+	default:
+		return nil
+	}
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (ldo *LockDeleteOne) ExecX(ctx context.Context) {
+	if err := ldo.Exec(ctx); err != nil {
+		panic(err)
+	}
+}

+ 526 - 0
pkg/database/ent/lock_query.go

@@ -0,0 +1,526 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+	"context"
+	"fmt"
+	"math"
+
+	"entgo.io/ent/dialect/sql"
+	"entgo.io/ent/dialect/sql/sqlgraph"
+	"entgo.io/ent/schema/field"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
+)
+
+// LockQuery is the builder for querying Lock entities.
+type LockQuery struct {
+	config
+	ctx        *QueryContext
+	order      []lock.OrderOption
+	inters     []Interceptor
+	predicates []predicate.Lock
+	// intermediate query (i.e. traversal path).
+	sql  *sql.Selector
+	path func(context.Context) (*sql.Selector, error)
+}
+
+// Where adds a new predicate for the LockQuery builder.
+func (lq *LockQuery) Where(ps ...predicate.Lock) *LockQuery {
+	lq.predicates = append(lq.predicates, ps...)
+	return lq
+}
+
+// Limit the number of records to be returned by this query.
+func (lq *LockQuery) Limit(limit int) *LockQuery {
+	lq.ctx.Limit = &limit
+	return lq
+}
+
+// Offset to start from.
+func (lq *LockQuery) Offset(offset int) *LockQuery {
+	lq.ctx.Offset = &offset
+	return lq
+}
+
+// Unique configures the query builder to filter duplicate records on query.
+// By default, unique is set to true, and can be disabled using this method.
+func (lq *LockQuery) Unique(unique bool) *LockQuery {
+	lq.ctx.Unique = &unique
+	return lq
+}
+
+// Order specifies how the records should be ordered.
+func (lq *LockQuery) Order(o ...lock.OrderOption) *LockQuery {
+	lq.order = append(lq.order, o...)
+	return lq
+}
+
+// First returns the first Lock entity from the query.
+// Returns a *NotFoundError when no Lock was found.
+func (lq *LockQuery) First(ctx context.Context) (*Lock, error) {
+	nodes, err := lq.Limit(1).All(setContextOp(ctx, lq.ctx, "First"))
+	if err != nil {
+		return nil, err
+	}
+	if len(nodes) == 0 {
+		return nil, &NotFoundError{lock.Label}
+	}
+	return nodes[0], nil
+}
+
+// FirstX is like First, but panics if an error occurs.
+func (lq *LockQuery) FirstX(ctx context.Context) *Lock {
+	node, err := lq.First(ctx)
+	if err != nil && !IsNotFound(err) {
+		panic(err)
+	}
+	return node
+}
+
+// FirstID returns the first Lock ID from the query.
+// Returns a *NotFoundError when no Lock ID was found.
+func (lq *LockQuery) FirstID(ctx context.Context) (id int, err error) {
+	var ids []int
+	if ids, err = lq.Limit(1).IDs(setContextOp(ctx, lq.ctx, "FirstID")); err != nil {
+		return
+	}
+	if len(ids) == 0 {
+		err = &NotFoundError{lock.Label}
+		return
+	}
+	return ids[0], nil
+}
+
+// FirstIDX is like FirstID, but panics if an error occurs.
+func (lq *LockQuery) FirstIDX(ctx context.Context) int {
+	id, err := lq.FirstID(ctx)
+	if err != nil && !IsNotFound(err) {
+		panic(err)
+	}
+	return id
+}
+
+// Only returns a single Lock entity found by the query, ensuring it only returns one.
+// Returns a *NotSingularError when more than one Lock entity is found.
+// Returns a *NotFoundError when no Lock entities are found.
+func (lq *LockQuery) Only(ctx context.Context) (*Lock, error) {
+	nodes, err := lq.Limit(2).All(setContextOp(ctx, lq.ctx, "Only"))
+	if err != nil {
+		return nil, err
+	}
+	switch len(nodes) {
+	case 1:
+		return nodes[0], nil
+	case 0:
+		return nil, &NotFoundError{lock.Label}
+	default:
+		return nil, &NotSingularError{lock.Label}
+	}
+}
+
+// OnlyX is like Only, but panics if an error occurs.
+func (lq *LockQuery) OnlyX(ctx context.Context) *Lock {
+	node, err := lq.Only(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return node
+}
+
+// OnlyID is like Only, but returns the only Lock ID in the query.
+// Returns a *NotSingularError when more than one Lock ID is found.
+// Returns a *NotFoundError when no entities are found.
+func (lq *LockQuery) OnlyID(ctx context.Context) (id int, err error) {
+	var ids []int
+	if ids, err = lq.Limit(2).IDs(setContextOp(ctx, lq.ctx, "OnlyID")); err != nil {
+		return
+	}
+	switch len(ids) {
+	case 1:
+		id = ids[0]
+	case 0:
+		err = &NotFoundError{lock.Label}
+	default:
+		err = &NotSingularError{lock.Label}
+	}
+	return
+}
+
+// OnlyIDX is like OnlyID, but panics if an error occurs.
+func (lq *LockQuery) OnlyIDX(ctx context.Context) int {
+	id, err := lq.OnlyID(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return id
+}
+
+// All executes the query and returns a list of Locks.
+func (lq *LockQuery) All(ctx context.Context) ([]*Lock, error) {
+	ctx = setContextOp(ctx, lq.ctx, "All")
+	if err := lq.prepareQuery(ctx); err != nil {
+		return nil, err
+	}
+	qr := querierAll[[]*Lock, *LockQuery]()
+	return withInterceptors[[]*Lock](ctx, lq, qr, lq.inters)
+}
+
+// AllX is like All, but panics if an error occurs.
+func (lq *LockQuery) AllX(ctx context.Context) []*Lock {
+	nodes, err := lq.All(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return nodes
+}
+
+// IDs executes the query and returns a list of Lock IDs.
+func (lq *LockQuery) IDs(ctx context.Context) (ids []int, err error) {
+	if lq.ctx.Unique == nil && lq.path != nil {
+		lq.Unique(true)
+	}
+	ctx = setContextOp(ctx, lq.ctx, "IDs")
+	if err = lq.Select(lock.FieldID).Scan(ctx, &ids); err != nil {
+		return nil, err
+	}
+	return ids, nil
+}
+
+// IDsX is like IDs, but panics if an error occurs.
+func (lq *LockQuery) IDsX(ctx context.Context) []int {
+	ids, err := lq.IDs(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return ids
+}
+
+// Count returns the count of the given query.
+func (lq *LockQuery) Count(ctx context.Context) (int, error) {
+	ctx = setContextOp(ctx, lq.ctx, "Count")
+	if err := lq.prepareQuery(ctx); err != nil {
+		return 0, err
+	}
+	return withInterceptors[int](ctx, lq, querierCount[*LockQuery](), lq.inters)
+}
+
+// CountX is like Count, but panics if an error occurs.
+func (lq *LockQuery) CountX(ctx context.Context) int {
+	count, err := lq.Count(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return count
+}
+
+// Exist returns true if the query has elements in the graph.
+func (lq *LockQuery) Exist(ctx context.Context) (bool, error) {
+	ctx = setContextOp(ctx, lq.ctx, "Exist")
+	switch _, err := lq.FirstID(ctx); {
+	case IsNotFound(err):
+		return false, nil
+	case err != nil:
+		return false, fmt.Errorf("ent: check existence: %w", err)
+	default:
+		return true, nil
+	}
+}
+
+// ExistX is like Exist, but panics if an error occurs.
+func (lq *LockQuery) ExistX(ctx context.Context) bool {
+	exist, err := lq.Exist(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return exist
+}
+
+// Clone returns a duplicate of the LockQuery builder, including all associated steps. It can be
+// used to prepare common query builders and use them differently after the clone is made.
+func (lq *LockQuery) Clone() *LockQuery {
+	if lq == nil {
+		return nil
+	}
+	return &LockQuery{
+		config:     lq.config,
+		ctx:        lq.ctx.Clone(),
+		order:      append([]lock.OrderOption{}, lq.order...),
+		inters:     append([]Interceptor{}, lq.inters...),
+		predicates: append([]predicate.Lock{}, lq.predicates...),
+		// clone intermediate query.
+		sql:  lq.sql.Clone(),
+		path: lq.path,
+	}
+}
+
+// GroupBy is used to group vertices by one or more fields/columns.
+// It is often used with aggregate functions, like: count, max, mean, min, sum.
+//
+// Example:
+//
+//	var v []struct {
+//		Name string `json:"name"`
+//		Count int `json:"count,omitempty"`
+//	}
+//
+//	client.Lock.Query().
+//		GroupBy(lock.FieldName).
+//		Aggregate(ent.Count()).
+//		Scan(ctx, &v)
+func (lq *LockQuery) GroupBy(field string, fields ...string) *LockGroupBy {
+	lq.ctx.Fields = append([]string{field}, fields...)
+	grbuild := &LockGroupBy{build: lq}
+	grbuild.flds = &lq.ctx.Fields
+	grbuild.label = lock.Label
+	grbuild.scan = grbuild.Scan
+	return grbuild
+}
+
+// Select allows the selection one or more fields/columns for the given query,
+// instead of selecting all fields in the entity.
+//
+// Example:
+//
+//	var v []struct {
+//		Name string `json:"name"`
+//	}
+//
+//	client.Lock.Query().
+//		Select(lock.FieldName).
+//		Scan(ctx, &v)
+func (lq *LockQuery) Select(fields ...string) *LockSelect {
+	lq.ctx.Fields = append(lq.ctx.Fields, fields...)
+	sbuild := &LockSelect{LockQuery: lq}
+	sbuild.label = lock.Label
+	sbuild.flds, sbuild.scan = &lq.ctx.Fields, sbuild.Scan
+	return sbuild
+}
+
+// Aggregate returns a LockSelect configured with the given aggregations.
+func (lq *LockQuery) Aggregate(fns ...AggregateFunc) *LockSelect {
+	return lq.Select().Aggregate(fns...)
+}
+
+func (lq *LockQuery) prepareQuery(ctx context.Context) error {
+	for _, inter := range lq.inters {
+		if inter == nil {
+			return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
+		}
+		if trv, ok := inter.(Traverser); ok {
+			if err := trv.Traverse(ctx, lq); err != nil {
+				return err
+			}
+		}
+	}
+	for _, f := range lq.ctx.Fields {
+		if !lock.ValidColumn(f) {
+			return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
+		}
+	}
+	if lq.path != nil {
+		prev, err := lq.path(ctx)
+		if err != nil {
+			return err
+		}
+		lq.sql = prev
+	}
+	return nil
+}
+
+func (lq *LockQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Lock, error) {
+	var (
+		nodes = []*Lock{}
+		_spec = lq.querySpec()
+	)
+	_spec.ScanValues = func(columns []string) ([]any, error) {
+		return (*Lock).scanValues(nil, columns)
+	}
+	_spec.Assign = func(columns []string, values []any) error {
+		node := &Lock{config: lq.config}
+		nodes = append(nodes, node)
+		return node.assignValues(columns, values)
+	}
+	for i := range hooks {
+		hooks[i](ctx, _spec)
+	}
+	if err := sqlgraph.QueryNodes(ctx, lq.driver, _spec); err != nil {
+		return nil, err
+	}
+	if len(nodes) == 0 {
+		return nodes, nil
+	}
+	return nodes, nil
+}
+
+func (lq *LockQuery) sqlCount(ctx context.Context) (int, error) {
+	_spec := lq.querySpec()
+	_spec.Node.Columns = lq.ctx.Fields
+	if len(lq.ctx.Fields) > 0 {
+		_spec.Unique = lq.ctx.Unique != nil && *lq.ctx.Unique
+	}
+	return sqlgraph.CountNodes(ctx, lq.driver, _spec)
+}
+
+func (lq *LockQuery) querySpec() *sqlgraph.QuerySpec {
+	_spec := sqlgraph.NewQuerySpec(lock.Table, lock.Columns, sqlgraph.NewFieldSpec(lock.FieldID, field.TypeInt))
+	_spec.From = lq.sql
+	if unique := lq.ctx.Unique; unique != nil {
+		_spec.Unique = *unique
+	} else if lq.path != nil {
+		_spec.Unique = true
+	}
+	if fields := lq.ctx.Fields; len(fields) > 0 {
+		_spec.Node.Columns = make([]string, 0, len(fields))
+		_spec.Node.Columns = append(_spec.Node.Columns, lock.FieldID)
+		for i := range fields {
+			if fields[i] != lock.FieldID {
+				_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
+			}
+		}
+	}
+	if ps := lq.predicates; len(ps) > 0 {
+		_spec.Predicate = func(selector *sql.Selector) {
+			for i := range ps {
+				ps[i](selector)
+			}
+		}
+	}
+	if limit := lq.ctx.Limit; limit != nil {
+		_spec.Limit = *limit
+	}
+	if offset := lq.ctx.Offset; offset != nil {
+		_spec.Offset = *offset
+	}
+	if ps := lq.order; len(ps) > 0 {
+		_spec.Order = func(selector *sql.Selector) {
+			for i := range ps {
+				ps[i](selector)
+			}
+		}
+	}
+	return _spec
+}
+
+func (lq *LockQuery) sqlQuery(ctx context.Context) *sql.Selector {
+	builder := sql.Dialect(lq.driver.Dialect())
+	t1 := builder.Table(lock.Table)
+	columns := lq.ctx.Fields
+	if len(columns) == 0 {
+		columns = lock.Columns
+	}
+	selector := builder.Select(t1.Columns(columns...)...).From(t1)
+	if lq.sql != nil {
+		selector = lq.sql
+		selector.Select(selector.Columns(columns...)...)
+	}
+	if lq.ctx.Unique != nil && *lq.ctx.Unique {
+		selector.Distinct()
+	}
+	for _, p := range lq.predicates {
+		p(selector)
+	}
+	for _, p := range lq.order {
+		p(selector)
+	}
+	if offset := lq.ctx.Offset; offset != nil {
+		// limit is mandatory for offset clause. We start
+		// with default value, and override it below if needed.
+		selector.Offset(*offset).Limit(math.MaxInt32)
+	}
+	if limit := lq.ctx.Limit; limit != nil {
+		selector.Limit(*limit)
+	}
+	return selector
+}
+
+// LockGroupBy is the group-by builder for Lock entities.
+type LockGroupBy struct {
+	selector
+	build *LockQuery
+}
+
+// Aggregate adds the given aggregation functions to the group-by query.
+func (lgb *LockGroupBy) Aggregate(fns ...AggregateFunc) *LockGroupBy {
+	lgb.fns = append(lgb.fns, fns...)
+	return lgb
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (lgb *LockGroupBy) Scan(ctx context.Context, v any) error {
+	ctx = setContextOp(ctx, lgb.build.ctx, "GroupBy")
+	if err := lgb.build.prepareQuery(ctx); err != nil {
+		return err
+	}
+	return scanWithInterceptors[*LockQuery, *LockGroupBy](ctx, lgb.build, lgb, lgb.build.inters, v)
+}
+
+func (lgb *LockGroupBy) sqlScan(ctx context.Context, root *LockQuery, v any) error {
+	selector := root.sqlQuery(ctx).Select()
+	aggregation := make([]string, 0, len(lgb.fns))
+	for _, fn := range lgb.fns {
+		aggregation = append(aggregation, fn(selector))
+	}
+	if len(selector.SelectedColumns()) == 0 {
+		columns := make([]string, 0, len(*lgb.flds)+len(lgb.fns))
+		for _, f := range *lgb.flds {
+			columns = append(columns, selector.C(f))
+		}
+		columns = append(columns, aggregation...)
+		selector.Select(columns...)
+	}
+	selector.GroupBy(selector.Columns(*lgb.flds...)...)
+	if err := selector.Err(); err != nil {
+		return err
+	}
+	rows := &sql.Rows{}
+	query, args := selector.Query()
+	if err := lgb.build.driver.Query(ctx, query, args, rows); err != nil {
+		return err
+	}
+	defer rows.Close()
+	return sql.ScanSlice(rows, v)
+}
+
+// LockSelect is the builder for selecting fields of Lock entities.
+type LockSelect struct {
+	*LockQuery
+	selector
+}
+
+// Aggregate adds the given aggregation functions to the selector query.
+func (ls *LockSelect) Aggregate(fns ...AggregateFunc) *LockSelect {
+	ls.fns = append(ls.fns, fns...)
+	return ls
+}
+
+// Scan applies the selector query and scans the result into the given value.
+func (ls *LockSelect) Scan(ctx context.Context, v any) error {
+	ctx = setContextOp(ctx, ls.ctx, "Select")
+	if err := ls.prepareQuery(ctx); err != nil {
+		return err
+	}
+	return scanWithInterceptors[*LockQuery, *LockSelect](ctx, ls.LockQuery, ls, ls.inters, v)
+}
+
+func (ls *LockSelect) sqlScan(ctx context.Context, root *LockQuery, v any) error {
+	selector := root.sqlQuery(ctx)
+	aggregation := make([]string, 0, len(ls.fns))
+	for _, fn := range ls.fns {
+		aggregation = append(aggregation, fn(selector))
+	}
+	switch n := len(*ls.selector.flds); {
+	case n == 0 && len(aggregation) > 0:
+		selector.Select(aggregation...)
+	case n != 0 && len(aggregation) > 0:
+		selector.AppendSelect(aggregation...)
+	}
+	rows := &sql.Rows{}
+	query, args := selector.Query()
+	if err := ls.driver.Query(ctx, query, args, rows); err != nil {
+		return err
+	}
+	defer rows.Close()
+	return sql.ScanSlice(rows, v)
+}

+ 228 - 0
pkg/database/ent/lock_update.go

@@ -0,0 +1,228 @@
+// Code generated by ent, DO NOT EDIT.
+
+package ent
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"time"
+
+	"entgo.io/ent/dialect/sql"
+	"entgo.io/ent/dialect/sql/sqlgraph"
+	"entgo.io/ent/schema/field"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
+)
+
+// LockUpdate is the builder for updating Lock entities.
+type LockUpdate struct {
+	config
+	hooks    []Hook
+	mutation *LockMutation
+}
+
+// Where appends a list predicates to the LockUpdate builder.
+func (lu *LockUpdate) Where(ps ...predicate.Lock) *LockUpdate {
+	lu.mutation.Where(ps...)
+	return lu
+}
+
+// SetName sets the "name" field.
+func (lu *LockUpdate) SetName(s string) *LockUpdate {
+	lu.mutation.SetName(s)
+	return lu
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (lu *LockUpdate) SetCreatedAt(t time.Time) *LockUpdate {
+	lu.mutation.SetCreatedAt(t)
+	return lu
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (lu *LockUpdate) SetNillableCreatedAt(t *time.Time) *LockUpdate {
+	if t != nil {
+		lu.SetCreatedAt(*t)
+	}
+	return lu
+}
+
+// Mutation returns the LockMutation object of the builder.
+func (lu *LockUpdate) Mutation() *LockMutation {
+	return lu.mutation
+}
+
+// Save executes the query and returns the number of nodes affected by the update operation.
+func (lu *LockUpdate) Save(ctx context.Context) (int, error) {
+	return withHooks(ctx, lu.sqlSave, lu.mutation, lu.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (lu *LockUpdate) SaveX(ctx context.Context) int {
+	affected, err := lu.Save(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return affected
+}
+
+// Exec executes the query.
+func (lu *LockUpdate) Exec(ctx context.Context) error {
+	_, err := lu.Save(ctx)
+	return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (lu *LockUpdate) ExecX(ctx context.Context) {
+	if err := lu.Exec(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func (lu *LockUpdate) sqlSave(ctx context.Context) (n int, err error) {
+	_spec := sqlgraph.NewUpdateSpec(lock.Table, lock.Columns, sqlgraph.NewFieldSpec(lock.FieldID, field.TypeInt))
+	if ps := lu.mutation.predicates; len(ps) > 0 {
+		_spec.Predicate = func(selector *sql.Selector) {
+			for i := range ps {
+				ps[i](selector)
+			}
+		}
+	}
+	if value, ok := lu.mutation.Name(); ok {
+		_spec.SetField(lock.FieldName, field.TypeString, value)
+	}
+	if value, ok := lu.mutation.CreatedAt(); ok {
+		_spec.SetField(lock.FieldCreatedAt, field.TypeTime, value)
+	}
+	if n, err = sqlgraph.UpdateNodes(ctx, lu.driver, _spec); err != nil {
+		if _, ok := err.(*sqlgraph.NotFoundError); ok {
+			err = &NotFoundError{lock.Label}
+		} else if sqlgraph.IsConstraintError(err) {
+			err = &ConstraintError{msg: err.Error(), wrap: err}
+		}
+		return 0, err
+	}
+	lu.mutation.done = true
+	return n, nil
+}
+
+// LockUpdateOne is the builder for updating a single Lock entity.
+type LockUpdateOne struct {
+	config
+	fields   []string
+	hooks    []Hook
+	mutation *LockMutation
+}
+
+// SetName sets the "name" field.
+func (luo *LockUpdateOne) SetName(s string) *LockUpdateOne {
+	luo.mutation.SetName(s)
+	return luo
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (luo *LockUpdateOne) SetCreatedAt(t time.Time) *LockUpdateOne {
+	luo.mutation.SetCreatedAt(t)
+	return luo
+}
+
+// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
+func (luo *LockUpdateOne) SetNillableCreatedAt(t *time.Time) *LockUpdateOne {
+	if t != nil {
+		luo.SetCreatedAt(*t)
+	}
+	return luo
+}
+
+// Mutation returns the LockMutation object of the builder.
+func (luo *LockUpdateOne) Mutation() *LockMutation {
+	return luo.mutation
+}
+
+// Where appends a list predicates to the LockUpdate builder.
+func (luo *LockUpdateOne) Where(ps ...predicate.Lock) *LockUpdateOne {
+	luo.mutation.Where(ps...)
+	return luo
+}
+
+// Select allows selecting one or more fields (columns) of the returned entity.
+// The default is selecting all fields defined in the entity schema.
+func (luo *LockUpdateOne) Select(field string, fields ...string) *LockUpdateOne {
+	luo.fields = append([]string{field}, fields...)
+	return luo
+}
+
+// Save executes the query and returns the updated Lock entity.
+func (luo *LockUpdateOne) Save(ctx context.Context) (*Lock, error) {
+	return withHooks(ctx, luo.sqlSave, luo.mutation, luo.hooks)
+}
+
+// SaveX is like Save, but panics if an error occurs.
+func (luo *LockUpdateOne) SaveX(ctx context.Context) *Lock {
+	node, err := luo.Save(ctx)
+	if err != nil {
+		panic(err)
+	}
+	return node
+}
+
+// Exec executes the query on the entity.
+func (luo *LockUpdateOne) Exec(ctx context.Context) error {
+	_, err := luo.Save(ctx)
+	return err
+}
+
+// ExecX is like Exec, but panics if an error occurs.
+func (luo *LockUpdateOne) ExecX(ctx context.Context) {
+	if err := luo.Exec(ctx); err != nil {
+		panic(err)
+	}
+}
+
+func (luo *LockUpdateOne) sqlSave(ctx context.Context) (_node *Lock, err error) {
+	_spec := sqlgraph.NewUpdateSpec(lock.Table, lock.Columns, sqlgraph.NewFieldSpec(lock.FieldID, field.TypeInt))
+	id, ok := luo.mutation.ID()
+	if !ok {
+		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Lock.id" for update`)}
+	}
+	_spec.Node.ID.Value = id
+	if fields := luo.fields; len(fields) > 0 {
+		_spec.Node.Columns = make([]string, 0, len(fields))
+		_spec.Node.Columns = append(_spec.Node.Columns, lock.FieldID)
+		for _, f := range fields {
+			if !lock.ValidColumn(f) {
+				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
+			}
+			if f != lock.FieldID {
+				_spec.Node.Columns = append(_spec.Node.Columns, f)
+			}
+		}
+	}
+	if ps := luo.mutation.predicates; len(ps) > 0 {
+		_spec.Predicate = func(selector *sql.Selector) {
+			for i := range ps {
+				ps[i](selector)
+			}
+		}
+	}
+	if value, ok := luo.mutation.Name(); ok {
+		_spec.SetField(lock.FieldName, field.TypeString, value)
+	}
+	if value, ok := luo.mutation.CreatedAt(); ok {
+		_spec.SetField(lock.FieldCreatedAt, field.TypeTime, value)
+	}
+	_node = &Lock{config: luo.config}
+	_spec.Assign = _node.assignValues
+	_spec.ScanValues = _node.scanValues
+	if err = sqlgraph.UpdateNode(ctx, luo.driver, _spec); err != nil {
+		if _, ok := err.(*sqlgraph.NotFoundError); ok {
+			err = &NotFoundError{lock.Label}
+		} else if sqlgraph.IsConstraintError(err) {
+			err = &ConstraintError{msg: err.Error(), wrap: err}
+		}
+		return nil, err
+	}
+	luo.mutation.done = true
+	return _node, nil
+}

+ 13 - 0
pkg/database/ent/migrate/schema.go

@@ -178,6 +178,18 @@ var (
 			},
 		},
 	}
+	// LocksColumns holds the columns for the "locks" table.
+	LocksColumns = []*schema.Column{
+		{Name: "id", Type: field.TypeInt, Increment: true},
+		{Name: "name", Type: field.TypeString, Unique: true},
+		{Name: "created_at", Type: field.TypeTime},
+	}
+	// LocksTable holds the schema information for the "locks" table.
+	LocksTable = &schema.Table{
+		Name:       "locks",
+		Columns:    LocksColumns,
+		PrimaryKey: []*schema.Column{LocksColumns[0]},
+	}
 	// MachinesColumns holds the columns for the "machines" table.
 	MachinesColumns = []*schema.Column{
 		{Name: "id", Type: field.TypeInt, Increment: true},
@@ -237,6 +249,7 @@ var (
 		ConfigItemsTable,
 		DecisionsTable,
 		EventsTable,
+		LocksTable,
 		MachinesTable,
 		MetaTable,
 	}

+ 382 - 0
pkg/database/ent/mutation.go

@@ -16,6 +16,7 @@ import (
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/decision"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/event"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/meta"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
@@ -35,6 +36,7 @@ const (
 	TypeConfigItem = "ConfigItem"
 	TypeDecision   = "Decision"
 	TypeEvent      = "Event"
+	TypeLock       = "Lock"
 	TypeMachine    = "Machine"
 	TypeMeta       = "Meta"
 )
@@ -6165,6 +6167,386 @@ func (m *EventMutation) ResetEdge(name string) error {
 	return fmt.Errorf("unknown Event edge %s", name)
 }
 
+// LockMutation represents an operation that mutates the Lock nodes in the graph.
+type LockMutation struct {
+	config
+	op            Op
+	typ           string
+	id            *int
+	name          *string
+	created_at    *time.Time
+	clearedFields map[string]struct{}
+	done          bool
+	oldValue      func(context.Context) (*Lock, error)
+	predicates    []predicate.Lock
+}
+
+var _ ent.Mutation = (*LockMutation)(nil)
+
+// lockOption allows management of the mutation configuration using functional options.
+type lockOption func(*LockMutation)
+
+// newLockMutation creates new mutation for the Lock entity.
+func newLockMutation(c config, op Op, opts ...lockOption) *LockMutation {
+	m := &LockMutation{
+		config:        c,
+		op:            op,
+		typ:           TypeLock,
+		clearedFields: make(map[string]struct{}),
+	}
+	for _, opt := range opts {
+		opt(m)
+	}
+	return m
+}
+
+// withLockID sets the ID field of the mutation.
+func withLockID(id int) lockOption {
+	return func(m *LockMutation) {
+		var (
+			err   error
+			once  sync.Once
+			value *Lock
+		)
+		m.oldValue = func(ctx context.Context) (*Lock, error) {
+			once.Do(func() {
+				if m.done {
+					err = errors.New("querying old values post mutation is not allowed")
+				} else {
+					value, err = m.Client().Lock.Get(ctx, id)
+				}
+			})
+			return value, err
+		}
+		m.id = &id
+	}
+}
+
+// withLock sets the old Lock of the mutation.
+func withLock(node *Lock) lockOption {
+	return func(m *LockMutation) {
+		m.oldValue = func(context.Context) (*Lock, error) {
+			return node, nil
+		}
+		m.id = &node.ID
+	}
+}
+
+// Client returns a new `ent.Client` from the mutation. If the mutation was
+// executed in a transaction (ent.Tx), a transactional client is returned.
+func (m LockMutation) Client() *Client {
+	client := &Client{config: m.config}
+	client.init()
+	return client
+}
+
+// Tx returns an `ent.Tx` for mutations that were executed in transactions;
+// it returns an error otherwise.
+func (m LockMutation) Tx() (*Tx, error) {
+	if _, ok := m.driver.(*txDriver); !ok {
+		return nil, errors.New("ent: mutation is not running in a transaction")
+	}
+	tx := &Tx{config: m.config}
+	tx.init()
+	return tx, nil
+}
+
+// ID returns the ID value in the mutation. Note that the ID is only available
+// if it was provided to the builder or after it was returned from the database.
+func (m *LockMutation) ID() (id int, exists bool) {
+	if m.id == nil {
+		return
+	}
+	return *m.id, true
+}
+
+// IDs queries the database and returns the entity ids that match the mutation's predicate.
+// That means, if the mutation is applied within a transaction with an isolation level such
+// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
+// or updated by the mutation.
+func (m *LockMutation) IDs(ctx context.Context) ([]int, error) {
+	switch {
+	case m.op.Is(OpUpdateOne | OpDeleteOne):
+		id, exists := m.ID()
+		if exists {
+			return []int{id}, nil
+		}
+		fallthrough
+	case m.op.Is(OpUpdate | OpDelete):
+		return m.Client().Lock.Query().Where(m.predicates...).IDs(ctx)
+	default:
+		return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
+	}
+}
+
+// SetName sets the "name" field.
+func (m *LockMutation) SetName(s string) {
+	m.name = &s
+}
+
+// Name returns the value of the "name" field in the mutation.
+func (m *LockMutation) Name() (r string, exists bool) {
+	v := m.name
+	if v == nil {
+		return
+	}
+	return *v, true
+}
+
+// OldName returns the old "name" field's value of the Lock entity.
+// If the Lock object wasn't provided to the builder, the object is fetched from the database.
+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
+func (m *LockMutation) OldName(ctx context.Context) (v string, err error) {
+	if !m.op.Is(OpUpdateOne) {
+		return v, errors.New("OldName is only allowed on UpdateOne operations")
+	}
+	if m.id == nil || m.oldValue == nil {
+		return v, errors.New("OldName requires an ID field in the mutation")
+	}
+	oldValue, err := m.oldValue(ctx)
+	if err != nil {
+		return v, fmt.Errorf("querying old value for OldName: %w", err)
+	}
+	return oldValue.Name, nil
+}
+
+// ResetName resets all changes to the "name" field.
+func (m *LockMutation) ResetName() {
+	m.name = nil
+}
+
+// SetCreatedAt sets the "created_at" field.
+func (m *LockMutation) SetCreatedAt(t time.Time) {
+	m.created_at = &t
+}
+
+// CreatedAt returns the value of the "created_at" field in the mutation.
+func (m *LockMutation) CreatedAt() (r time.Time, exists bool) {
+	v := m.created_at
+	if v == nil {
+		return
+	}
+	return *v, true
+}
+
+// OldCreatedAt returns the old "created_at" field's value of the Lock entity.
+// If the Lock object wasn't provided to the builder, the object is fetched from the database.
+// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
+func (m *LockMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
+	if !m.op.Is(OpUpdateOne) {
+		return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
+	}
+	if m.id == nil || m.oldValue == nil {
+		return v, errors.New("OldCreatedAt requires an ID field in the mutation")
+	}
+	oldValue, err := m.oldValue(ctx)
+	if err != nil {
+		return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
+	}
+	return oldValue.CreatedAt, nil
+}
+
+// ResetCreatedAt resets all changes to the "created_at" field.
+func (m *LockMutation) ResetCreatedAt() {
+	m.created_at = nil
+}
+
+// Where appends a list predicates to the LockMutation builder.
+func (m *LockMutation) Where(ps ...predicate.Lock) {
+	m.predicates = append(m.predicates, ps...)
+}
+
+// WhereP appends storage-level predicates to the LockMutation builder. Using this method,
+// users can use type-assertion to append predicates that do not depend on any generated package.
+func (m *LockMutation) WhereP(ps ...func(*sql.Selector)) {
+	p := make([]predicate.Lock, len(ps))
+	for i := range ps {
+		p[i] = ps[i]
+	}
+	m.Where(p...)
+}
+
+// Op returns the operation name.
+func (m *LockMutation) Op() Op {
+	return m.op
+}
+
+// SetOp allows setting the mutation operation.
+func (m *LockMutation) SetOp(op Op) {
+	m.op = op
+}
+
+// Type returns the node type of this mutation (Lock).
+func (m *LockMutation) Type() string {
+	return m.typ
+}
+
+// Fields returns all fields that were changed during this mutation. Note that in
+// order to get all numeric fields that were incremented/decremented, call
+// AddedFields().
+func (m *LockMutation) Fields() []string {
+	fields := make([]string, 0, 2)
+	if m.name != nil {
+		fields = append(fields, lock.FieldName)
+	}
+	if m.created_at != nil {
+		fields = append(fields, lock.FieldCreatedAt)
+	}
+	return fields
+}
+
+// Field returns the value of a field with the given name. The second boolean
+// return value indicates that this field was not set, or was not defined in the
+// schema.
+func (m *LockMutation) Field(name string) (ent.Value, bool) {
+	switch name {
+	case lock.FieldName:
+		return m.Name()
+	case lock.FieldCreatedAt:
+		return m.CreatedAt()
+	}
+	return nil, false
+}
+
+// OldField returns the old value of the field from the database. An error is
+// returned if the mutation operation is not UpdateOne, or the query to the
+// database failed.
+func (m *LockMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
+	switch name {
+	case lock.FieldName:
+		return m.OldName(ctx)
+	case lock.FieldCreatedAt:
+		return m.OldCreatedAt(ctx)
+	}
+	return nil, fmt.Errorf("unknown Lock field %s", name)
+}
+
+// SetField sets the value of a field with the given name. It returns an error if
+// the field is not defined in the schema, or if the type mismatched the field
+// type.
+func (m *LockMutation) SetField(name string, value ent.Value) error {
+	switch name {
+	case lock.FieldName:
+		v, ok := value.(string)
+		if !ok {
+			return fmt.Errorf("unexpected type %T for field %s", value, name)
+		}
+		m.SetName(v)
+		return nil
+	case lock.FieldCreatedAt:
+		v, ok := value.(time.Time)
+		if !ok {
+			return fmt.Errorf("unexpected type %T for field %s", value, name)
+		}
+		m.SetCreatedAt(v)
+		return nil
+	}
+	return fmt.Errorf("unknown Lock field %s", name)
+}
+
+// AddedFields returns all numeric fields that were incremented/decremented during
+// this mutation.
+func (m *LockMutation) AddedFields() []string {
+	return nil
+}
+
+// AddedField returns the numeric value that was incremented/decremented on a field
+// with the given name. The second boolean return value indicates that this field
+// was not set, or was not defined in the schema.
+func (m *LockMutation) AddedField(name string) (ent.Value, bool) {
+	return nil, false
+}
+
+// AddField adds the value to the field with the given name. It returns an error if
+// the field is not defined in the schema, or if the type mismatched the field
+// type.
+func (m *LockMutation) AddField(name string, value ent.Value) error {
+	switch name {
+	}
+	return fmt.Errorf("unknown Lock numeric field %s", name)
+}
+
+// ClearedFields returns all nullable fields that were cleared during this
+// mutation.
+func (m *LockMutation) ClearedFields() []string {
+	return nil
+}
+
+// FieldCleared returns a boolean indicating if a field with the given name was
+// cleared in this mutation.
+func (m *LockMutation) FieldCleared(name string) bool {
+	_, ok := m.clearedFields[name]
+	return ok
+}
+
+// ClearField clears the value of the field with the given name. It returns an
+// error if the field is not defined in the schema.
+func (m *LockMutation) ClearField(name string) error {
+	return fmt.Errorf("unknown Lock nullable field %s", name)
+}
+
+// ResetField resets all changes in the mutation for the field with the given name.
+// It returns an error if the field is not defined in the schema.
+func (m *LockMutation) ResetField(name string) error {
+	switch name {
+	case lock.FieldName:
+		m.ResetName()
+		return nil
+	case lock.FieldCreatedAt:
+		m.ResetCreatedAt()
+		return nil
+	}
+	return fmt.Errorf("unknown Lock field %s", name)
+}
+
+// AddedEdges returns all edge names that were set/added in this mutation.
+func (m *LockMutation) AddedEdges() []string {
+	edges := make([]string, 0, 0)
+	return edges
+}
+
+// AddedIDs returns all IDs (to other nodes) that were added for the given edge
+// name in this mutation.
+func (m *LockMutation) AddedIDs(name string) []ent.Value {
+	return nil
+}
+
+// RemovedEdges returns all edge names that were removed in this mutation.
+func (m *LockMutation) RemovedEdges() []string {
+	edges := make([]string, 0, 0)
+	return edges
+}
+
+// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
+// the given name in this mutation.
+func (m *LockMutation) RemovedIDs(name string) []ent.Value {
+	return nil
+}
+
+// ClearedEdges returns all edge names that were cleared in this mutation.
+func (m *LockMutation) ClearedEdges() []string {
+	edges := make([]string, 0, 0)
+	return edges
+}
+
+// EdgeCleared returns a boolean which indicates if the edge with the given name
+// was cleared in this mutation.
+func (m *LockMutation) EdgeCleared(name string) bool {
+	return false
+}
+
+// ClearEdge clears the value of the edge with the given name. It returns an error
+// if that edge is not defined in the schema.
+func (m *LockMutation) ClearEdge(name string) error {
+	return fmt.Errorf("unknown Lock unique edge %s", name)
+}
+
+// ResetEdge resets all changes to the edge with the given name in this mutation.
+// It returns an error if the edge is not defined in the schema.
+func (m *LockMutation) ResetEdge(name string) error {
+	return fmt.Errorf("unknown Lock edge %s", name)
+}
+
 // MachineMutation represents an operation that mutates the Machine nodes in the graph.
 type MachineMutation struct {
 	config

+ 3 - 0
pkg/database/ent/predicate/predicate.go

@@ -21,6 +21,9 @@ type Decision func(*sql.Selector)
 // Event is the predicate function for event builders.
 type Event func(*sql.Selector)
 
+// Lock is the predicate function for lock builders.
+type Lock func(*sql.Selector)
+
 // Machine is the predicate function for machine builders.
 type Machine func(*sql.Selector)
 

+ 7 - 0
pkg/database/ent/runtime.go

@@ -10,6 +10,7 @@ import (
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/decision"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/event"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/meta"
 	"github.com/crowdsecurity/crowdsec/pkg/database/ent/schema"
@@ -137,6 +138,12 @@ func init() {
 	eventDescSerialized := eventFields[3].Descriptor()
 	// event.SerializedValidator is a validator for the "serialized" field. It is called by the builders before save.
 	event.SerializedValidator = eventDescSerialized.Validators[0].(func(string) error)
+	lockFields := schema.Lock{}.Fields()
+	_ = lockFields
+	// lockDescCreatedAt is the schema descriptor for created_at field.
+	lockDescCreatedAt := lockFields[1].Descriptor()
+	// lock.DefaultCreatedAt holds the default value on creation for the created_at field.
+	lock.DefaultCreatedAt = lockDescCreatedAt.Default.(func() time.Time)
 	machineFields := schema.Machine{}.Fields()
 	_ = machineFields
 	// machineDescCreatedAt is the schema descriptor for created_at field.

+ 22 - 0
pkg/database/ent/schema/lock.go

@@ -0,0 +1,22 @@
+package schema
+
+import (
+	"entgo.io/ent"
+	"entgo.io/ent/schema/field"
+	"github.com/crowdsecurity/crowdsec/pkg/types"
+)
+
+type Lock struct {
+	ent.Schema
+}
+
+func (Lock) Fields() []ent.Field {
+	return []ent.Field{
+		field.String("name").Unique().StructTag(`json:"name"`),
+		field.Time("created_at").Default(types.UtcNow).StructTag(`json:"created_at"`),
+	}
+}
+
+func (Lock) Edges() []ent.Edge {
+	return nil
+}

+ 3 - 0
pkg/database/ent/tx.go

@@ -22,6 +22,8 @@ type Tx struct {
 	Decision *DecisionClient
 	// Event is the client for interacting with the Event builders.
 	Event *EventClient
+	// Lock is the client for interacting with the Lock builders.
+	Lock *LockClient
 	// Machine is the client for interacting with the Machine builders.
 	Machine *MachineClient
 	// Meta is the client for interacting with the Meta builders.
@@ -162,6 +164,7 @@ func (tx *Tx) init() {
 	tx.ConfigItem = NewConfigItemClient(tx.config)
 	tx.Decision = NewDecisionClient(tx.config)
 	tx.Event = NewEventClient(tx.config)
+	tx.Lock = NewLockClient(tx.config)
 	tx.Machine = NewMachineClient(tx.config)
 	tx.Meta = NewMetaClient(tx.config)
 }

+ 67 - 0
pkg/database/lock.go

@@ -0,0 +1,67 @@
+package database
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+	log "github.com/sirupsen/logrus"
+
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent"
+	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
+	"github.com/crowdsecurity/crowdsec/pkg/types"
+)
+
+const (
+	CAPIPullLockTimeout = 120
+)
+
+func (c *Client) AcquireLock(name string) error {
+	_, err := c.Ent.Lock.Create().
+		SetName(name).
+		SetCreatedAt(types.UtcNow()).
+		Save(c.CTX)
+	if ent.IsConstraintError(err) {
+		return err
+	}
+	if err != nil {
+		return errors.Wrapf(InsertFail, "insert lock: %s", err)
+	}
+	return nil
+}
+
+func (c *Client) ReleaseLock(name string) error {
+	_, err := c.Ent.Lock.Delete().Where(lock.NameEQ(name)).Exec(c.CTX)
+	if err != nil {
+		return errors.Wrapf(DeleteFail, "delete lock: %s", err)
+	}
+	return nil
+}
+
+func (c *Client) ReleaseLockWithTimeout(name string, timeout int) error {
+	log.Debugf("(%s) releasing orphin locks", name)
+	_, err := c.Ent.Lock.Delete().Where(
+		lock.NameEQ(name),
+		lock.CreatedAtLT(time.Now().Add(-time.Duration(timeout)*time.Minute)),
+	).Exec(c.CTX)
+	if err != nil {
+		return errors.Wrapf(DeleteFail, "delete lock: %s", err)
+	}
+	return nil
+}
+
+func (c *Client) IsLocked(err error) bool {
+	return ent.IsConstraintError(err)
+}
+
+func (c *Client) AcquirePullCAPILock() error {
+	lockName := "pullCAPI"
+	err := c.ReleaseLockWithTimeout(lockName, CAPIPullLockTimeout)
+	if err != nil {
+		log.Errorf("unable to release pullCAPI lock: %s", err)
+	}
+	return c.AcquireLock(lockName)
+}
+
+func (c *Client) ReleasePullCAPILock() error {
+	return c.ReleaseLockWithTimeout("pullCAPI", CAPIPullLockTimeout)
+}