Destroy unused network interfaces on VM destroy

This commit is contained in:
Mitchell Hashimoto 2010-06-03 19:59:39 -07:00
parent 7a093340bf
commit 50262cfb66
4 changed files with 51 additions and 2 deletions

View File

@ -6,6 +6,7 @@ module Vagrant
# The true as the 2nd parameter always forces the shutdown so its
# fast (since we're destroying anyways)
@runner.add_action(Halt, :force => true) if @runner.vm.running?
@runner.add_action(Network)
@runner.add_action(Destroy)
end

View File

@ -2,6 +2,25 @@ module Vagrant
module Actions
module VM
class Network < Base
def before_destroy
# We need to check if the host only network specified by any
# of the adapters would not have any more clients if it was
# destroyed. And if so, then destroy the host only network
# itself.
interfaces = runner.vm.network_adapters.collect do |adapter|
adapter.host_interface_object
end
interfaces.compact.uniq.each do |interface|
# Destroy the network interface if there is only one
# attached VM (which must be this VM)
if interface.attached_vms.length == 1
logger.info "Destroying unused network interface..."
interface.destroy
end
end
end
def before_boot
assign_network if enable_network?
end

View File

@ -19,13 +19,13 @@ class DownActionTest < Test::Unit::TestCase
end
should "add the destroy action alone if VM is not running" do
setup_action_expectations([Vagrant::Actions::VM::Destroy])
setup_action_expectations([Vagrant::Actions::VM::Network, Vagrant::Actions::VM::Destroy])
@action.prepare
end
should "add the halt action if the VM is running" do
@vm.expects(:running?).returns(true)
setup_action_expectations([[Vagrant::Actions::VM::Halt, {:force => true}], Vagrant::Actions::VM::Destroy])
setup_action_expectations([[Vagrant::Actions::VM::Halt, {:force => true}], Vagrant::Actions::VM::Network, Vagrant::Actions::VM::Destroy])
@action.prepare
end
end

View File

@ -6,6 +6,35 @@ class NetworkTest < Test::Unit::TestCase
@runner.stubs(:system).returns(linux_system(@vm))
end
context "before destroy" do
setup do
@network_adapters = []
@vm.stubs(:network_adapters).returns(@network_adapters)
end
def stub_interface(length=5)
interface = mock("interface")
adapter = mock("adapter")
adapter.stubs(:host_interface_object).returns(interface)
interface.stubs(:attached_vms).returns(Array.new(length))
@network_adapters << adapter
interface
end
should "destroy only the unused network interfaces" do
stub_interface(5)
stub_interface(7)
results = [stub_interface(1), stub_interface(1)]
results.each do |result|
result.expects(:destroy).once
end
@action.before_destroy
end
end
context "before boot" do
setup do
@action.stubs(:enable_network?).returns(false)