2016-10-11 01:51:11 +08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var _ = require('underscore');
|
|
|
|
var RedisPool = require('redis-mpool');
|
|
|
|
var RedisDistlockLocker = require('./provider/redis-distlock');
|
|
|
|
var debug = require('../util/debug')('leader-locker');
|
|
|
|
|
2016-10-12 19:11:20 +08:00
|
|
|
var LOCK = {
|
|
|
|
TTL: 5000
|
|
|
|
};
|
|
|
|
|
|
|
|
function Locker(locker, ttl) {
|
2016-10-11 01:51:11 +08:00
|
|
|
this.locker = locker;
|
2016-10-12 19:11:20 +08:00
|
|
|
this.ttl = (Number.isFinite(ttl) && ttl > 0) ? ttl : LOCK.TTL;
|
|
|
|
this.renewInterval = this.ttl / 5;
|
2016-10-12 18:30:13 +08:00
|
|
|
this.intervalIds = {};
|
2016-10-11 01:51:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = Locker;
|
|
|
|
|
2016-10-12 19:11:20 +08:00
|
|
|
Locker.prototype.lock = function(host, callback) {
|
2016-10-12 18:30:13 +08:00
|
|
|
var self = this;
|
2016-10-12 19:11:20 +08:00
|
|
|
debug('Locker.lock(%s, %d)', host, this.ttl);
|
|
|
|
this.locker.lock(host, this.ttl, function (err, lock) {
|
2016-10-12 18:30:13 +08:00
|
|
|
self.startRenewal(host);
|
|
|
|
return callback(err, lock);
|
|
|
|
});
|
2016-10-11 01:51:11 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
Locker.prototype.unlock = function(host, callback) {
|
2016-10-12 18:30:13 +08:00
|
|
|
var self = this;
|
2016-10-11 01:51:11 +08:00
|
|
|
debug('Locker.unlock(%s)', host);
|
2016-10-12 18:30:13 +08:00
|
|
|
this.locker.unlock(host, function(err) {
|
|
|
|
self.stopRenewal(host);
|
|
|
|
return callback(err);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
Locker.prototype.startRenewal = function(host) {
|
|
|
|
var self = this;
|
|
|
|
if (!this.intervalIds.hasOwnProperty(host)) {
|
|
|
|
this.intervalIds[host] = setInterval(function() {
|
|
|
|
debug('Trying to extend lock host=%s', host);
|
2016-10-12 19:11:20 +08:00
|
|
|
self.locker.lock(host, self.ttl, function(err, _lock) {
|
2016-10-12 18:30:13 +08:00
|
|
|
if (err) {
|
|
|
|
return self.stopRenewal(host);
|
|
|
|
}
|
|
|
|
if (_lock) {
|
|
|
|
debug('Extended lock host=%s', host);
|
|
|
|
}
|
|
|
|
});
|
2016-10-12 19:11:20 +08:00
|
|
|
}, this.renewInterval);
|
2016-10-12 18:30:13 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Locker.prototype.stopRenewal = function(host) {
|
|
|
|
if (this.intervalIds.hasOwnProperty(host)) {
|
|
|
|
clearInterval(this.intervalIds[host]);
|
|
|
|
delete this.intervalIds[host];
|
|
|
|
}
|
2016-10-11 01:51:11 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports.create = function createLocker(type, config) {
|
|
|
|
if (type !== 'redis-distlock') {
|
|
|
|
throw new Error('Invalid type Locker type. Valid types are: "redis-distlock"');
|
|
|
|
}
|
|
|
|
var redisPool = new RedisPool(_.extend({ name: 'batch-distlock' }, config.redisConfig));
|
|
|
|
var locker = new RedisDistlockLocker(redisPool);
|
2016-10-12 19:11:20 +08:00
|
|
|
return new Locker(locker, config.ttl);
|
2016-10-11 01:51:11 +08:00
|
|
|
};
|