A node package for distributed locks using etcd. It required ES6 support, so node >=4.0.0 should be used.

Usage

Instantiation

Use the exported constructor to instantiate new locks. The constructor has the signature function Lock(etcd, key, id, ttl) , where etcd is a node-etcd client, key is the etcd key to use for locking, id is a unique node identifier and ttl is the TTL of the lock in seconds.

var Lock = require ( " etcd-lock " ) ; var Etcd = require ( " node-etcd " ) ; var os = require ( " os " ) ; var key = " /example/lock " , id = os . hostname ( ) , ttl = 60 var lock = new Lock ( new Etcd ( ) , key , id , ttl ) ;

Locking and unlocking

Each lock instance has the methods lock() and unlock() , both of which return a promise that will be fulfilled or rejected when the action is complete

lock . lock ( ) . then ( ( ) => { console . log ( " locked " ) ; ; return lock . unlock ( ) ; } ) . then ( ( ) => { console . log ( " unlocked " ) ; } ) ;

Note that the example above has no error handling: lock() will return a rejected promise if, for example, the etcd cluster is not reachable. The lock instance itself will also emit error events in case the lock is lost for whatever reason. Ignoring the error events is a bad idea, as you have no idea what state the lock is in.

Calling lock() multiple times will simply refresh the lock: you only need to unlock() once. The lock will automatically refresh itself at intervals of (lock.ttl*1000) / 2 . To change the refresh interval or TTL after construction, change lock.refreshInterval or lock.ttl before calling lock() .

Calling unlock() when you don't hold the lock will return a rejected promise.

etcdlocker

etcd-lock comes with a command line tool called etcdlocker (do e.g. npm install -g etcd-lock to get it in your path.)