Skip to content

Instantly share code, notes, and snippets.

@dwaligora
Created October 31, 2014 14:08
Show Gist options
  • Select an option

  • Save dwaligora/108e6629edcea13d834e to your computer and use it in GitHub Desktop.

Select an option

Save dwaligora/108e6629edcea13d834e to your computer and use it in GitHub Desktop.
node cli
/*jshint node: true*/
'use strict';
var util = require('util'),
_ = require('lodash'),
CronJob = require('cron').CronJob,
STATUS = require('../app/statuses.json'),
config = require('../config.json'),
logger = require('../app/services/logger'),
running = require('is-running'),
jobManager = require('../app/managers/job');
if (!config.jobs || !config.jobs.monitor) {
throw new Error('Monitor: Missing monitor job configuration in config.json!');
}
var jobConfig = config.jobs.monitor;
/**
* Monitoring & dispatching new jobs
*
* @type {CronJob}
*/
var job = new CronJob({
cronTime: jobConfig.time,
onTick: function() {
/**
* check if any of jobs is being processed by Brain
*/
jobManager.find({status: STATUS.RUNNING})
.then(function(rows) {
if(!(rows.length > 0)) {
throw new Error('Monitor: No jobs are processed by Brain now.');
}
logger.info('Monitor: %s jobs are processed by Brain now.', rows.length);
return rows;
})
/**
* if yes compare their running time with their TTL
*/
.then(function(processes) {
_.forEach(processes, function(job) {
running(job.brain_pid, function(err, live) {
if (err) {
logger.error('Monitor: ' + err.toString());
}
var status = null;
// is job alive?
if (live) {
// if so, check if it doesn't exceed its own TTL
var nowTimestamp = parseInt(Date.now() / 1000, 10);
if (nowTimestamp > (job.created_at + job.job_ttl)) {
logger.info('Monitor: Job with id "%s", created at "%s" exceeded its TTL "%s", timeout!',
job.id, job.created_at, job.job_ttl
);
status = STATUS.ERROR;
} else {
logger.info('Monitor: Job with id "%s", created at "%s" is still processed by Brain...',
job.id, job.created_at
);
}
} else {
// if no, it mean it was processed successfully
logger.info('Monitor: Job [id: %s] was processed successfully.', job.id);
status = STATUS.SUCCESS;
}
if (status) {
jobManager.update(job.id, {
status: status,
updated_at: parseInt(Date.now() / 1000, 10)
})
.then(function(rowsAffected) {
if (!(rowsAffected > 0)) {
throw new Error(
util.format('Monitor: Job with id "%s" had not been updated successfully!', job.id)
);
}
logger.info('Monitor: Job with id "%s" and status "%s" updated successfully.', job.id, status);
})
}
})
});
})
.catch(function(err) {
logger.error(err.toString());
});
},
start: false
});
job.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment