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 158
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 165
def call(env)
  @env = env

  if ssh_pids.any?
    env[:ui].info I18n.t(
      'vagrant.actions.vm.clear_forward_ports.deleting'
    )
    ssh_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
  else
    @logger.info 'No ssh pids found'
  end

  @app.call env
end

Protected Instance Methods

remove_ssh_pids() click to toggle source
# File lib/vagrant-libvirt/action/forward_ports.rb, line 214
def remove_ssh_pids
  glob = @env[: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 208
def ssh_pid?(pid)
  @logger.debug 'Checking if #{pid} is an ssh process '                         'with `ps -o cmd= #{pid}`'
  %x`ps -o cmd= #{pid}`.strip.chomp =~ /ssh/
end
ssh_pids() click to toggle source
# File lib/vagrant-libvirt/action/forward_ports.rb, line 198
def ssh_pids
  glob = @env[: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