forked from taskcluster/taskcluster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshared_file_lock.js
59 lines (53 loc) · 1.65 KB
/
shared_file_lock.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const assert = require('assert');
const Debug = require('debug');
const fs = require('fs-ext');
const util = require('util');
let debug = Debug('docker-worker:lib:shared_file_lock');
const flock = util.promisify(fs.flock);
class SharedFileLock {
/* This acts as a semaphore which locks a file if one or more locks
* are acquired on this object until they are released.
*
* @param lockFile Fd of file to be locked. Must already exist and not be exclusively locked.
*/
constructor(lockFd) {
this.count = 0;
this.lockFd = lockFd;
this.locked = false;
}
//acquires a lock, at >=1 locks it will flock the lockfile
async acquire() {
if(this.count === 0 || !this.locked) {
let err = await flock(this.lockFd, 'shnb');
if(err) {
debug('[alert-operator] couldn\'t acquire lock, this is probably bad');
debug(err);
} else {
this.locked = true;
debug('locked');
}
}
this.count += 1;
debug('acquire; count is %s', this.count);
}
//releases a lock after some delay, at 0 locks it will unlock the lockfile
async release(delay = 0) {
if(delay > 0) {
return setTimeout(() => {this.release();}, delay);
}
assert(this.count > 0, 'Has been released more times than acquired');
this.count -= 1;
if(this.count === 0 && this.locked) {
let err = await fs.flock(this.lockFd, 'un');
if(err) {
debug('[alert-operator] couldn\'t unlock, this is probably bad');
debug(err);
} else {
this.locked = false;
debug('unlocked');
}
}
debug('released; count is %s', this.count);
}
}
module.exports = SharedFileLock;