Add action for clearing forwarded ports
This commit is contained in:
parent
0f3b99b376
commit
399ab86d60
2 changed files with 89 additions and 0 deletions
47
lib/vagrant-lxc/action/clear_forwarded_ports.rb
Normal file
47
lib/vagrant-lxc/action/clear_forwarded_ports.rb
Normal file
|
@ -0,0 +1,47 @@
|
|||
module Vagrant
|
||||
module LXC
|
||||
module Action
|
||||
class ClearForwardedPorts
|
||||
def initialize(app, env)
|
||||
@app = app
|
||||
@logger = Log4r::Logger.new("vagrant::lxc::action::clear_forwarded_ports")
|
||||
end
|
||||
|
||||
def call(env)
|
||||
@env = env
|
||||
|
||||
if redir_pids.any?
|
||||
env[:ui].info I18n.t("vagrant.actions.vm.clear_forward_ports.deleting")
|
||||
redir_pids.each do |pid|
|
||||
next unless is_redir_pid?(pid)
|
||||
@logger.debug "Killing pid #{pid}"
|
||||
system "sudo pkill -9 -P #{pid}"
|
||||
end
|
||||
|
||||
remove_redir_pids
|
||||
end
|
||||
|
||||
@app.call env
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
def redir_pids
|
||||
@redir_pids = Dir[@env[:machine].data_dir.join('pids').to_s + "/redir_*.pid"].map do |file|
|
||||
File.read(file).strip.chomp
|
||||
end
|
||||
end
|
||||
|
||||
def is_redir_pid?(pid)
|
||||
`ps -o cmd= #{pid}`.strip.chomp =~ /redir/
|
||||
end
|
||||
|
||||
def remove_redir_pids
|
||||
Dir[@env[:machine].data_dir.join('pids').to_s + "/redir_*.pid"].each do |file|
|
||||
File.delete file
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
42
spec/unit/action/clear_forwarded_ports_spec.rb
Normal file
42
spec/unit/action/clear_forwarded_ports_spec.rb
Normal file
|
@ -0,0 +1,42 @@
|
|||
require 'unit_helper'
|
||||
|
||||
require 'vagrant-lxc/action/clear_forwarded_ports'
|
||||
|
||||
describe Vagrant::LXC::Action::ClearForwardedPorts do
|
||||
let(:app) { mock(:app, call: true) }
|
||||
let(:env) { {machine: machine, ui: stub(info: true)} }
|
||||
let(:machine) { mock(:machine, data_dir: data_dir) }
|
||||
let!(:data_dir) { Pathname.new(Dir.mktmpdir) }
|
||||
let(:pids_dir) { data_dir.join('pids') }
|
||||
let(:pid) { 'a-pid' }
|
||||
let(:pid_cmd) { 'redir' }
|
||||
|
||||
subject { described_class.new(app, env) }
|
||||
|
||||
before do
|
||||
pids_dir.mkdir
|
||||
pids_dir.join('redir_1234.pid').open('w') { |f| f.write(pid) }
|
||||
subject.stub(system: true, :` => pid_cmd)
|
||||
subject.call(env)
|
||||
end
|
||||
|
||||
after { FileUtils.rm_rf data_dir.to_s }
|
||||
|
||||
it 'removes all files under pid directory' do
|
||||
Dir[pids_dir.to_s + "/redir_*.pid"].should be_empty
|
||||
end
|
||||
|
||||
context 'with a valid redir pid' do
|
||||
it 'kills known processes' do
|
||||
subject.should have_received(:system).with("sudo pkill -9 -P #{pid}")
|
||||
end
|
||||
end
|
||||
|
||||
context 'with an invalid pid' do
|
||||
let(:pid_cmd) { 'sudo ls' }
|
||||
|
||||
it 'does not kill the process' do
|
||||
subject.should_not have_received(:system).with("sudo pkill -9 -P #{pid}")
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue