2015-12-09 07:02:08 +08:00
|
|
|
'use strict';
|
|
|
|
|
2015-12-23 06:13:33 +08:00
|
|
|
var util = require('util');
|
|
|
|
var EventEmitter = require('events').EventEmitter;
|
2015-12-22 02:57:10 +08:00
|
|
|
var JobRunner = require('./job_runner');
|
2015-12-16 22:57:58 +08:00
|
|
|
var JobQueuePool = require('./job_queue_pool');
|
|
|
|
var JobSubscriber = require('./job_subscriber');
|
|
|
|
var UserDatabaseMetadataService = require('./user_database_metadata_service');
|
2015-12-09 07:02:08 +08:00
|
|
|
|
2015-12-23 03:12:10 +08:00
|
|
|
function Batch(metadataBackend) {
|
|
|
|
EventEmitter.call(this);
|
|
|
|
this.jobSubscriber = new JobSubscriber();
|
2015-12-29 17:19:10 +08:00
|
|
|
this.jobQueuePool = new JobQueuePool(metadataBackend);
|
|
|
|
this.jobRunner = new JobRunner(metadataBackend, new UserDatabaseMetadataService(metadataBackend));
|
2015-12-23 03:12:10 +08:00
|
|
|
}
|
|
|
|
util.inherits(Batch, EventEmitter);
|
|
|
|
|
|
|
|
Batch.prototype.start = function () {
|
|
|
|
var self = this;
|
2015-12-09 07:02:08 +08:00
|
|
|
|
2015-12-29 17:19:10 +08:00
|
|
|
this.jobSubscriber.subscribe(function (channel, host) {
|
|
|
|
var queue = self.jobQueuePool.get(host);
|
2015-12-16 22:57:58 +08:00
|
|
|
|
2015-12-29 17:19:10 +08:00
|
|
|
if (!queue) {
|
|
|
|
queue = self.jobQueuePool.add(host);
|
|
|
|
run(queue);
|
|
|
|
}
|
2015-12-22 02:57:10 +08:00
|
|
|
|
2015-12-29 17:19:10 +08:00
|
|
|
function run(queue) {
|
|
|
|
queue.dequeue(host, function (err, job_id) {
|
|
|
|
if (err) {
|
|
|
|
self.jobQueuePool.remove(host);
|
|
|
|
return console.error(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!job_id) {
|
|
|
|
self.jobQueuePool.remove(host);
|
|
|
|
return console.log('Queue %s is empty', host);
|
|
|
|
}
|
|
|
|
|
|
|
|
self.jobRunner.run(job_id)
|
|
|
|
.on('done', function (job) {
|
|
|
|
console.log('Job %s done in %s', job_id, host);
|
|
|
|
self.emit('job:done', job_id);
|
|
|
|
run(queue);
|
|
|
|
})
|
|
|
|
.on('failed', function (job) {
|
|
|
|
console.log('Job %s done in %s', job_id, host);
|
|
|
|
self.emit('job:failed', job_id);
|
|
|
|
run(queue);
|
|
|
|
})
|
|
|
|
.on('error', function (err) {
|
|
|
|
self.emit('job:failed', job_id);
|
|
|
|
self.jobQueuePool.remove(host);
|
|
|
|
});
|
2015-12-16 22:57:58 +08:00
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
2015-12-23 03:12:10 +08:00
|
|
|
};
|
2015-12-17 01:13:48 +08:00
|
|
|
|
2015-12-23 03:12:10 +08:00
|
|
|
module.exports = Batch;
|