From c08946cc2420efe6ae427d069e70b343d0a56d9c Mon Sep 17 00:00:00 2001 From: Zachary Boyd Date: Fri, 24 Mar 2017 20:11:06 -0400 Subject: [PATCH] allows instances to be removed from pool --- src/ControlServer.js | 1 + src/TorPool.js | 7 +++++++ src/TorProcess.js | 6 +++++- test/test.js | 16 +++++++++++++--- 4 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/ControlServer.js b/src/ControlServer.js index 123a6c3..589e7bf 100644 --- a/src/ControlServer.js +++ b/src/ControlServer.js @@ -25,6 +25,7 @@ class ControlServer { socket.on('createInstances', (instances, callback) => { this.torPool.create(instances, (error, instances) => { callback(error) }); }); + socket.on('removeInstances', (instances, callback) => { this.torPool.remove(instances, callback); }); socket.on('newIps', () => { this.torPool.new_ips(); }); socket.on('nextInstance', () => { this.torPool.next(); }); socket.on('closeInstances', () => { this.torPool.exit(); }); diff --git a/src/TorPool.js b/src/TorPool.js index b8a2c71..95340f7 100644 --- a/src/TorPool.js +++ b/src/TorPool.js @@ -60,6 +60,13 @@ class TorPool extends EventEmitter { }, (callback || (() => {}))); } + remove(instances, callback) { + let instances_to_remove = this._instances.splice(0, instances); + async.each(instances_to_remove, (instance, next) => { + instance.exit(next); + }, callback); + } + next() { this._instances = this._instances.rotate(1); return this.instances[0]; diff --git a/src/TorProcess.js b/src/TorProcess.js index d969df8..f1a0b01 100644 --- a/src/TorProcess.js +++ b/src/TorProcess.js @@ -22,8 +22,12 @@ class TorProcess extends EventEmitter { }, (config || { })); } - exit() { + exit(callback) { + this.process.once('exit', (code) => { + callback && callback(null, code); + }); this.process.kill('SIGKILL'); + } new_ip() { diff --git a/test/test.js b/test/test.js index e46500c..bd8b137 100644 --- a/test/test.js +++ b/test/test.js @@ -184,8 +184,8 @@ describe('TorProcess', function () { describe('TorPool', function () { var TorPool = TorRouter.TorPool; var pool = new TorPool('tor'); + this.timeout(Infinity); describe('#create', function () { - this.timeout(Infinity); it('should create two instances without any problems', function (done) { pool.create(2, function (error) { if (error) return done(error); @@ -193,9 +193,19 @@ describe('TorPool', function () { }); }); - after(function () { - pool.exit(); + }); + + describe('#remove', function () { + it('should remove 2 instances from the pool', function (done) { + pool.remove(2, function (error) { + if (error) return done(error); + done((pool.instances.length) && new Error('pool has two instances')); + }) }); + }) + + after(function () { + pool.exit(); }); })