github.com/netdata/go.d.plugin@v0.58.1/agent/filelock/filelock.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package filelock
     4  
     5  import (
     6  	"path/filepath"
     7  
     8  	"github.com/gofrs/flock"
     9  )
    10  
    11  func New(dir string) *Locker {
    12  	return &Locker{
    13  		suffix: ".collector.lock",
    14  		dir:    dir,
    15  		locks:  make(map[string]*flock.Flock),
    16  	}
    17  }
    18  
    19  type Locker struct {
    20  	suffix string
    21  	dir    string
    22  	locks  map[string]*flock.Flock
    23  }
    24  
    25  func (l *Locker) Lock(name string) (bool, error) {
    26  	name = filepath.Join(l.dir, name+l.suffix)
    27  
    28  	if _, ok := l.locks[name]; ok {
    29  		return true, nil
    30  	}
    31  
    32  	locker := flock.New(name)
    33  
    34  	ok, err := locker.TryLock()
    35  	if ok {
    36  		l.locks[name] = locker
    37  	} else {
    38  		_ = locker.Close()
    39  	}
    40  
    41  	return ok, err
    42  }
    43  
    44  func (l *Locker) Unlock(name string) error {
    45  	name = filepath.Join(l.dir, name+l.suffix)
    46  
    47  	locker, ok := l.locks[name]
    48  	if !ok {
    49  		return nil
    50  	}
    51  
    52  	delete(l.locks, name)
    53  
    54  	return locker.Close()
    55  }