github.com/flower-corp/rosedb@v1.1.2-0.20230117132829-21dc4f7b319a/flock/flock_plan9.go (about)

     1  package flock
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  )
     7  
     8  // FileLockGuard holds a lock of file on a directory.
     9  type FileLockGuard struct {
    10  	// file descriptor on directory.
    11  	fd *os.File
    12  }
    13  
    14  // AcquireFileLock acquire the lock on the directory by syscall.Flock.
    15  // Return a FileLockGuard or an error, if any.
    16  func AcquireFileLock(path string, readOnly bool) (*FileLockGuard, error) {
    17  	var (
    18  		flag int
    19  		mode os.FileMode
    20  	)
    21  	if readOnly {
    22  		flag = os.O_RDONLY
    23  	} else {
    24  		flag = os.O_RDWR
    25  		mode = os.ModeExclusive
    26  	}
    27  
    28  	file, err := os.OpenFile(path, flag, mode)
    29  	if os.IsNotExist(err) {
    30  		file, err = os.OpenFile(path, flag|os.O_CREATE, mode|0644)
    31  	}
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	return &FileLockGuard{fd: file}, nil
    36  }
    37  
    38  // SyncDir commits the current contents of the directory to stable storage.
    39  func SyncDir(path string) error {
    40  	fd, err := os.Open(path)
    41  	if err != nil {
    42  		return err
    43  	}
    44  	err = fd.Sync()
    45  	closeErr := fd.Close()
    46  	if err != nil {
    47  		return fmt.Errorf("sync dir err: %+v", err)
    48  	}
    49  	if closeErr != nil {
    50  		return fmt.Errorf("close dir err: %+v", err)
    51  	}
    52  	return nil
    53  }
    54  
    55  // Release release the file lock.
    56  func (fl *FileLockGuard) Release() error {
    57  	return fl.fd.Close()
    58  }