fixed race condition when using SSH tunnel #110

This commit is contained in:
Jan Prochazka
2021-05-03 20:39:41 +02:00
parent 4802c36b54
commit 7d34458553

View File

@@ -4,6 +4,8 @@ const portfinder = require('portfinder');
const stableStringify = require('json-stable-stringify'); const stableStringify = require('json-stable-stringify');
const _ = require('lodash'); const _ = require('lodash');
const platformInfo = require('./platformInfo'); const platformInfo = require('./platformInfo');
const AsyncLock = require('async-lock');
const lock = new AsyncLock();
const sshConnectionCache = {}; const sshConnectionCache = {};
const sshTunnelCache = {}; const sshTunnelCache = {};
@@ -45,8 +47,10 @@ async function getSshConnection(connection) {
} }
async function getSshTunnel(connection) { async function getSshTunnel(connection) {
const sshConn = await getSshConnection(connection);
const tunnelCacheKey = stableStringify(_.pick(connection, TUNNEL_FIELDS)); const tunnelCacheKey = stableStringify(_.pick(connection, TUNNEL_FIELDS));
return await lock.acquire(tunnelCacheKey, async () => {
const sshConn = await getSshConnection(connection);
if (sshTunnelCache[tunnelCacheKey]) return sshTunnelCache[tunnelCacheKey]; if (sshTunnelCache[tunnelCacheKey]) return sshTunnelCache[tunnelCacheKey];
const localPort = await portfinder.getPortPromise({ port: 10000, stopPort: 60000 }); const localPort = await portfinder.getPortPromise({ port: 10000, stopPort: 60000 });
@@ -58,6 +62,10 @@ async function getSshTunnel(connection) {
toHost: connection.server, toHost: connection.server,
}; };
try { try {
console.log(
`Creating SSH tunnel to ${connection.sshHost}-${connection.server}:${connection.port}, using local port ${localPort}`
);
const tunnel = await sshConn.forward(tunnelConfig); const tunnel = await sshConn.forward(tunnelConfig);
console.log( console.log(
`Created SSH tunnel to ${connection.sshHost}-${connection.server}:${connection.port}, using local port ${localPort}` `Created SSH tunnel to ${connection.sshHost}-${connection.server}:${connection.port}, using local port ${localPort}`
@@ -75,6 +83,7 @@ async function getSshTunnel(connection) {
message: err.message, message: err.message,
}; };
} }
});
} }
module.exports = { module.exports = {