class VagrantPlugins::ProviderLibvirt::Action::ClearForwardedPorts

Cleans up ssh-forwarded ports on VM halt/destroy.

Public Class Methods

new(app, _env) click to toggle source
# File lib/vagrant-libvirt/action/forward_ports.rb, line 166
def initialize(app, _env)
  @app = app
  @logger = Log4r::Logger.new(
    'vagrant_libvirt::action::clear_forward_ports'
  )
end

Public Instance Methods

call(env) click to toggle source
# File lib/vagrant-libvirt/action/forward_ports.rb, line 173
def call(env)
  pids = ssh_pids(env[:machine])
  if pids.any?
    env[:ui].info I18n.t(
      'vagrant.actions.vm.clear_forward_ports.deleting'
    )
    pids.each do |tag|
      next unless ssh_pid?(tag[:pid])
      @logger.debug "Killing pid #{tag[:pid]}"
      kill_cmd = ''

      if tag[:port] <= 1024
        kill_cmd += 'sudo ' # add sudo prefix
      end

      kill_cmd += "kill #{tag[:pid]}"
      @@lock.synchronize do
        system(kill_cmd)
      end
    end

    @logger.info 'Removing ssh pid files'
    remove_ssh_pids(env[:machine])
  else
    @logger.info 'No ssh pids found'
  end

  @app.call env
end

Protected Instance Methods

remove_ssh_pids(machine) click to toggle source
# File lib/vagrant-libvirt/action/forward_ports.rb, line 221
def remove_ssh_pids(machine)
  glob = machine.data_dir.join('pids').to_s + '/ssh_*.pid'
  Dir[glob].each do |file|
    File.delete file
  end
end
ssh_pid?(pid) click to toggle source
# File lib/vagrant-libvirt/action/forward_ports.rb, line 215
def ssh_pid?(pid)
  @logger.debug "Checking if #{pid} is an ssh process "\
                "with `ps -o command= #{pid}`"
  `ps -o command= #{pid}`.strip.chomp =~ /ssh/
end
ssh_pids(machine) click to toggle source
# File lib/vagrant-libvirt/action/forward_ports.rb, line 205
def ssh_pids(machine)
  glob = machine.data_dir.join('pids').to_s + '/ssh_*.pid'
  ssh_pids = Dir[glob].map do |file|
    {
      pid: File.read(file).strip.chomp,
      port: File.basename(file)['ssh_'.length..-1 * ('.pid'.length + 1)].to_i
    }
  end
end