Help us shape the future of Go! Take the 2026 Go Developer Survey

nsfilelock

package module
v0.0.0-...-90eff0e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 15, 2016 License: Apache-2.0 Imports: 7 Imported by: 2

README

NSFileLock

File lock (flock) in another namespace.

Motivation:

I am working on various projects rely on a privileged container(Docker), in which case the process running inside the container will have the ability to switch namespace to the host. Sometimes, we want to make sure certain thing won't happen simultaneously on the host in the case of multiple instances of the container is running. But bind-mount an additional directory just for this purpose seems unnecessarily cumbersome, and especially we already have the ability to switch to the host namespace (especially mount namespace) for certain operations.

But as a Go program, it's hard to hold a file descriptor in another namespace to perform flock operation, since nsenter, which is the easiest way to switch namespace, is a bash program. Of course, you can call setns syscall used by nsenter to get the process into the new namespace, though that means you got to rewrite the nsenter just for grabbing a lock.

This library provides a reliable way to do so without rewrite nsenter.

Target

The target is simply: simulate the behavior of flock in another namespace.

The most import behavior of flock is:

The lock will expire immediately when the process holding file descriptor exits.

It's the key reason why we don't want to create a file in the other namespace to simulate the lock. In that case, the crash of process holding the lock will result in infinitely blocking all the following processes.

For flock, since it's only related to opened file descriptor, as soon as the file descriptor is closed (e.g. unlock, or process crashed so OS release all its resources), the lock will expire.

Documentation

Index

Constants

View Source
const (
	MountNamespaceFD   = "mnt"
	MaximumMessageSize = 255

	SuccessResponse = "NSFileLock LOCKED"
)

Variables

View Source
var (
	DefaultTimeout = 15 * time.Second
)

Functions

This section is empty.

Types

type NSFileLock

type NSFileLock struct {
	Namespace string
	FilePath  string
	Timeout   time.Duration
	// contains filtered or unexported fields
}

func NewLock

func NewLock(ns string, filepath string) *NSFileLock

func NewLockWithTimeout

func NewLockWithTimeout(ns string, filepath string, timeout time.Duration) *NSFileLock

func (*NSFileLock) Lock

func (l *NSFileLock) Lock() error

func (*NSFileLock) Unlock

func (l *NSFileLock) Unlock()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL