Add proper shutdown and state handling to ProcessGroup

This commit is contained in:
Ryan Huffman 2015-12-03 15:16:20 -08:00
parent edda1c6d1c
commit 5da948d634

View file

@ -5,6 +5,12 @@ var util = require('util');
var events = require('events');
var childProcess = require('child_process');
const ProcessGroupStates = {
STOPPED: 'stopped',
STARTED: 'started',
STOPPING: 'stopping'
};
const ProcessStates = {
STOPPED: 'stopped',
STARTED: 'started',
@ -12,23 +18,58 @@ const ProcessStates = {
};
function ProcessGroup(name, processes) {
events.EventEmitter.call(this);
this.name = name;
this.processes = processes;
this.state = ProcessGroupStates.STOPPED;
this.processes = [];
for (let process of processes) {
this.addProcess(process);
}
};
util.inherits(ProcessGroup, events.EventEmitter);
ProcessGroup.prototype = extend(ProcessGroup.prototype, {
addProcess: function(process) {
this.processes.push(process);
process.on('state-update', this.onProcessStateUpdate.bind(this));
},
start: function() {
if (this.state != ProcessGroupStates.STOPPED) {
console.warn("Can't start process group that is not stopped.");
return;
}
for (let process of this.processes) {
process.start();
}
this.state = ProcessGroupStates.STARTED;
},
stop: function() {
if (this.state != ProcessGroupStates.STARTED) {
console.warn("Can't stop process group that is not started.");
return;
}
for (let process of this.processes) {
process.stop();
}
this.state = ProcessGroupStates.STOPPING;
},
// Event handlers
onProcessStateUpdate: function(process) {
var processesStillRunning = false;
for (let process of this.processes) {
if (process.state != ProcessStates.STOPPED) {
processesStillRunning = true;
break;
}
}
if (!processesStillRunning) {
this.state = ProcessGroupStates.STOPPED;
}
this.emit('state-update', this, process);
}
});
@ -36,6 +77,7 @@ var ID = 0;
function Process(name, command, commandArgs) {
events.EventEmitter.call(this);
this.blah = 'adsf';
this.id = ++ID;
this.name = name;
this.command = command;
@ -67,7 +109,7 @@ Process.prototype = extend(Process.prototype, {
this.state = ProcessStates.STOPPED;
}
this.emit('state-update');
this.emit('state-update', this);
},
stop: function() {
if (this.state != ProcessStates.STARTED) {
@ -82,12 +124,12 @@ Process.prototype = extend(Process.prototype, {
onChildStartError: function(error) {
console.log("Child process error ", error);
this.state = ProcessStates.STOPPED;
this.emit('state-update');
this.emit('state-update', this);
},
onChildClose: function(code) {
console.log("Child process closed with code ", code);
this.state = ProcessStates.STOPPED;
this.emit('state-update');
this.emit('state-update', this);
}
});