github.com/crowdsecurity/crowdsec@v1.6.1/pkg/database/lock.go (about)

     1  package database
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/pkg/errors"
     7  	log "github.com/sirupsen/logrus"
     8  
     9  	"github.com/crowdsecurity/crowdsec/pkg/database/ent"
    10  	"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
    11  	"github.com/crowdsecurity/crowdsec/pkg/types"
    12  )
    13  
    14  const (
    15  	CAPIPullLockTimeout = 10
    16  	CapiPullLockName    = "pullCAPI"
    17  )
    18  
    19  func (c *Client) AcquireLock(name string) error {
    20  	log.Debugf("acquiring lock %s", name)
    21  	_, err := c.Ent.Lock.Create().
    22  		SetName(name).
    23  		SetCreatedAt(types.UtcNow()).
    24  		Save(c.CTX)
    25  	if ent.IsConstraintError(err) {
    26  		return err
    27  	}
    28  	if err != nil {
    29  		return errors.Wrapf(InsertFail, "insert lock: %s", err)
    30  	}
    31  	return nil
    32  }
    33  
    34  func (c *Client) ReleaseLock(name string) error {
    35  	log.Debugf("releasing lock %s", name)
    36  	_, err := c.Ent.Lock.Delete().Where(lock.NameEQ(name)).Exec(c.CTX)
    37  	if err != nil {
    38  		return errors.Wrapf(DeleteFail, "delete lock: %s", err)
    39  	}
    40  	return nil
    41  }
    42  
    43  func (c *Client) ReleaseLockWithTimeout(name string, timeout int) error {
    44  	log.Debugf("releasing lock %s with timeout of %d minutes", name, timeout)
    45  	_, err := c.Ent.Lock.Delete().Where(
    46  		lock.NameEQ(name),
    47  		lock.CreatedAtLT(time.Now().UTC().Add(-time.Duration(timeout)*time.Minute)),
    48  	).Exec(c.CTX)
    49  
    50  	if err != nil {
    51  		return errors.Wrapf(DeleteFail, "delete lock: %s", err)
    52  	}
    53  	return nil
    54  }
    55  
    56  func (c *Client) IsLocked(err error) bool {
    57  	return ent.IsConstraintError(err)
    58  }
    59  
    60  func (c *Client) AcquirePullCAPILock() error {
    61  
    62  	/*delete orphan "old" lock if present*/
    63  	err := c.ReleaseLockWithTimeout(CapiPullLockName, CAPIPullLockTimeout)
    64  	if err != nil {
    65  		log.Errorf("unable to release pullCAPI lock: %s", err)
    66  	}
    67  	return c.AcquireLock(CapiPullLockName)
    68  }
    69  
    70  func (c *Client) ReleasePullCAPILock() error {
    71  	log.Debugf("deleting lock %s", CapiPullLockName)
    72  	_, err := c.Ent.Lock.Delete().Where(
    73  		lock.NameEQ(CapiPullLockName),
    74  	).Exec(c.CTX)
    75  	if err != nil {
    76  		return errors.Wrapf(DeleteFail, "delete lock: %s", err)
    77  	}
    78  	return nil
    79  }