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);
|
2015-12-29 22:46:04 +08:00
|
|
|
consume(queue);
|
2015-12-29 17:19:10 +08:00
|
|
|
}
|
2015-12-22 02:57:10 +08:00
|
|
|
|
2015-12-29 22:46:04 +08:00
|
|
|
function consume(queue) {
|
2015-12-29 17:19:10 +08:00
|
|
|
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);
|
2015-12-31 03:16:18 +08:00
|
|
|
self.emit('job:done', job.job_id);
|
2015-12-29 22:46:04 +08:00
|
|
|
consume(queue); // recursive call
|
2015-12-29 17:19:10 +08:00
|
|
|
})
|
|
|
|
.on('failed', function (job) {
|
|
|
|
console.log('Job %s done in %s', job_id, host);
|
2015-12-31 03:16:18 +08:00
|
|
|
self.emit('job:failed', job.job_id);
|
2015-12-29 22:46:04 +08:00
|
|
|
consume(queue); // recursive call
|
2015-12-29 17:19:10 +08:00
|
|
|
})
|
|
|
|
.on('error', function (err) {
|
2015-12-31 03:16:18 +08:00
|
|
|
console.error('Error in job ', err.message || err);
|
2015-12-29 17:19:10 +08:00
|
|
|
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;
|