Skip to content

Commit 6159adc

Browse files
committed
fix: use dynamic wait for establishing ssh tunnel to database server
1 parent e911a38 commit 6159adc

2 files changed

Lines changed: 14 additions & 5 deletions

File tree

src/Command/Database/AbstractDatabaseCommand.php

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace Ymir\Cli\Command\Database;
1515

16+
use Carbon\Carbon;
1617
use Symfony\Component\Console\Exception\RuntimeException;
1718
use Ymir\Cli\Command\AbstractCommand;
1819
use Ymir\Cli\Command\Network\AddBastionHostCommand;
@@ -92,11 +93,19 @@ protected function startSshTunnel(array $databaseServer): Process
9293
throw new RuntimeException(sprintf('The database server network does\'t have a bastion host to connect to. You can add one to the network with the "%s" command.', AddBastionHostCommand::NAME));
9394
}
9495

95-
$tunnel = Ssh::tunnelBastionHost($network->get('bastion_host'), 3305, $databaseServer['endpoint'], 3306);
96+
$bastionHost = $network->get('bastion_host');
97+
$tunnel = Ssh::tunnelBastionHost($bastionHost, 3305, $databaseServer['endpoint'], 3306);
9698

97-
// Need to wait a bit while SSH connection opens
98-
sleep(1);
99+
$timeout = Carbon::now()->addSeconds(10);
99100

100-
return $tunnel;
101+
while ($tunnel->isRunning() && Carbon::now()->lessThan($timeout)) {
102+
if (str_contains($tunnel->getIncrementalErrorOutput(), sprintf('Authenticated to %s', $bastionHost['endpoint']))) {
103+
return $tunnel;
104+
}
105+
106+
usleep(100000);
107+
}
108+
109+
throw new RuntimeException('Attempt to create a SSH tunnel to the bastion host timed out after 10 seconds');
101110
}
102111
}

src/Tool/Ssh.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public static function tunnelBastionHost(array $bastionHost, int $localPort, str
4141
$filesystem->dumpFile($identityFilePath, $bastionHost['private_key']);
4242
$filesystem->chmod($identityFilePath, 0600);
4343

44-
$command = sprintf('ec2-user@%s -i %s -o LogLevel=error -L %s:%s:%s -N', $bastionHost['endpoint'], $identityFilePath, $localPort, $remoteHost, $remotePort);
44+
$command = sprintf('ec2-user@%s -i %s -o LogLevel=debug -L %s:%s:%s -N', $bastionHost['endpoint'], $identityFilePath, $localPort, $remoteHost, $remotePort);
4545

4646
$process = self::getProcess($command, $cwd, null);
4747
$process->start(function ($type, $buffer) use ($localPort) {

0 commit comments

Comments
 (0)