Skip to content

Instantly share code, notes, and snippets.

@apocas
Last active February 3, 2018 19:48
Show Gist options
  • Save apocas/5701011 to your computer and use it in GitHub Desktop.
Save apocas/5701011 to your computer and use it in GitHub Desktop.
Node,js SSH2 connection pool
var ConnectionPool = function (connection) {
this.connection = connection;
this.queue = [];
this.counter = 0;
this.running = false;
};
ConnectionPool.prototype.start = function () {
var self = this;
if (!this.running) {
this.running = true;
this.interval = setInterval(function () {
if(self.counter < 8) {
var saux = self.queue.shift();
if (saux !== undefined) {
self.counter--;
self.connection.exec(saux.cmd, function (err, stream) {
if (err) {
self.counter++;
} else {
stream.on('data', function (data, extended) {
if (extended !== 'stderr' && saux.callback !== undefined) {
saux.callback(data);
}
});
stream.on('exit', function (code, signal) {
stream.destroy();
self.counter++;
});
}
});
} else {
self.stop();
}
}
}, 50);
}
};
ConnectionPool.prototype.flush = function () {
this.queue.length = 0;
};
ConnectionPool.prototype.stop = function () {
this.running = false;
clearInterval(this.interval);
};
ConnectionPool.prototype.send = function (cmd, callback) {
this.queue.push({'cmd': cmd, 'callback': callback});
if (!this.running) {
this.start();
}
};
module.exports = ConnectionPool;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment