Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Health Monitor #30

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions src/health-monitor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
'use strict';

/**
* Module dependencies.
*/

const log = require('debugnyan')('process-manager:health-monitor');
const utils = require('./utils');

/**
* `HealthMonitor`.
*/

class HealthMonitor {
/**
* Constructor.
*/

constructor() {
this.checks = {};
this.globalState = HealthMonitor.states.UNKNOWN;
this.states = {};
}

/**
* Add health check.
*/

addCheck({ handler, id, interval = 5000 }) {
if (this.states[id]) {
throw new Error('Cannot add handler since it would overwrite an existing one');
}

this.states[id] = HealthMonitor.states.UNKNOWN;

const check = async () => {
let state;

try {
state = (await Promise.race([handler(), utils.timeout(5000, false)]))
? HealthMonitor.states.HEALTHY
: HealthMonitor.states.UNHEALTHY;
} catch (e) {
state = HealthMonitor.states.UNHEALTHY;
}

this.updateState({ id, state });

this.checks[id] = setTimeout(check, interval);
};

this.checks[id] = setTimeout(check, 0);

log.info(`New health monitor check added with id '${id}'`);
}

/**
* Cleanup health monitor by clearing all timers and resetting the internal state.
*/

cleanup() {
Object.values(this.checks).forEach(clearTimeout);

this.checks = {};
this.globalState = HealthMonitor.states.UNKNOWN;
this.states = {};
}

/**
* Handles state changes.
*/

updateState({ id, state }) {
if (this.states[id] === state) {
return;
}

log.info({ id, newState: state, oldState: this.states[id] }, 'Component health status has changed');

this.states[id] = state;

// The sorted states array makes it so that the state at the end of the array is the relevant one.
// The global state is:
// - UNKNOWN if one exists.
// - UNHEALTHY if one exists and there are no UNKNOWN states.
// - HEALTHY if there are no UNKNOWN and UNHEALTHY states.
const [globalState] = Object.values(this.states).sort((left, right) => {
return left < right ? 1 : -1;
});

if (this.globalState === globalState) {
return;
}

log.info({ newState: globalState, oldState: this.globalState }, 'Global health status has changed');

this.globalState = globalState;
}
}

/**
* Health states.
*/

HealthMonitor.states = {
HEALTHY: 'healthy',
UNHEALTHY: 'unhealthy',
UNKNOWN: 'unknown'
};

/**
* Export `HealthMonitor` class.
*/

module.exports = HealthMonitor;
22 changes: 22 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* Module dependencies.
*/

const HealthMonitor = require('./health-monitor');
const utils = require('./utils');

/**
Expand All @@ -24,13 +25,22 @@ class ProcessManager {
constructor() {
this.errors = [];
this.forceShutdown = utils.deferred();
this.healthMonitor = new HealthMonitor();
Americas marked this conversation as resolved.
Show resolved Hide resolved
this.hooks = [];
this.log = utils.getDefaultLogger();
this.running = [];
this.terminating = false;
this.timeout = 30000;
}

/**
* Add health monitor check.
*/

addHealthCheck(...args) {
this.healthMonitor.addCheck(...args);
}

/**
* Add hook.
*/
Expand Down Expand Up @@ -79,6 +89,17 @@ class ProcessManager {
process.exit();
}

/**
* Get health monitor status.
*/

getHealthStatus() {
return {
global: this.healthMonitor.globalState,
individual: this.healthMonitor.states
};
}

/**
* Call all handlers for a hook.
*/
Expand Down Expand Up @@ -190,6 +211,7 @@ class ProcessManager {
.then(() => this.log.info('All running instances have stopped'))
.then(() => this.hook('drain'))
.then(() => this.log.info(`${this.hooks.filter(hook => hook.type === 'drain').length} server(s) drained`))
.then(() => this.healthMonitor.cleanup())
.then(() => this.hook('disconnect'))
.then(() =>
this.log.info(`${this.hooks.filter(hook => hook.type === 'disconnect').length} service(s) disconnected`)
Expand Down
Loading
Loading