From b4925261fa0108651fa4af4724de718af9436256 Mon Sep 17 00:00:00 2001 From: sophia Date: Mon, 23 Jan 2023 16:38:11 -0800 Subject: [PATCH] Use netssh builtin keep alive functionality --- plugins/communicators/ssh/communicator.rb | 23 ++++------------ .../communicators/ssh/communicator_test.rb | 26 +++++++++++++++++++ 2 files changed, 31 insertions(+), 18 deletions(-) diff --git a/plugins/communicators/ssh/communicator.rb b/plugins/communicators/ssh/communicator.rb index fd15804c6..3e660710e 100644 --- a/plugins/communicators/ssh/communicator.rb +++ b/plugins/communicators/ssh/communicator.rb @@ -456,6 +456,11 @@ module VagrantPlugins connect_opts[:remote_user] = ssh_info[:remote_user] end + if @machine.config.ssh.keep_alive + connect_opts[:keepalive] = true + connect_opts[:keepalive_interval] = 5 + end + @logger.info("Attempting to connect to SSH...") @logger.info(" - Host: #{ssh_info[:host]}") @logger.info(" - Port: #{ssh_info[:port]}") @@ -683,21 +688,6 @@ module VagrantPlugins end begin - keep_alive = nil - - if machine_config_ssh.keep_alive - # Begin sending keep-alive packets while we wait for the script - # to complete. This avoids connections closing on long-running - # scripts. - keep_alive = Thread.new do - loop do - sleep 5 - @logger.debug("Sending SSH keep-alive...") - connection.send_global_request("keep-alive@openssh.com") - end - end - end - # Wait for the channel to complete begin channel.wait @@ -711,9 +701,6 @@ module VagrantPlugins rescue Net::SSH::Disconnect raise Vagrant::Errors::SSHDisconnected end - ensure - # Kill the keep-alive thread - keep_alive.kill if keep_alive end # If we're in a PTY, we now finally parse the output diff --git a/test/unit/plugins/communicators/ssh/communicator_test.rb b/test/unit/plugins/communicators/ssh/communicator_test.rb index a2c929cd4..314bceb66 100644 --- a/test/unit/plugins/communicators/ssh/communicator_test.rb +++ b/test/unit/plugins/communicators/ssh/communicator_test.rb @@ -669,6 +669,32 @@ describe VagrantPlugins::CommunicatorSSH::Communicator do ).and_return(true) communicator.send(:connect) end + + context "keep ssh connection alive" do + let(:ssh) do + double("ssh", + timeout: 1, + host: nil, + port: 5986, + guest_port: 5986, + pty: false, + keep_alive: true, + insert_key: insert_ssh_key, + export_command_template: export_command_template, + shell: 'bash -l' + ) + end + + it "sets keepalive settings" do + expect(Net::SSH).to receive(:start).with( + nil, nil, hash_including( + keepalive: true, + keepalive_interval: 5 + ) + ).and_return(true) + communicator.send(:connect) + end + end end context "with keys_only disabled and verify_host_key enabled" do