Middleware to destroy unused network interfaces

This commit is contained in:
Mitchell Hashimoto 2010-07-05 17:18:16 +02:00
parent 7d6c0db4ae
commit f258746384
2 changed files with 79 additions and 0 deletions

View File

@ -0,0 +1,33 @@
module Vagrant
class Action
module VM
class DestroyUnusedNetworkInterfaces
def initialize(app, env)
@app = app
end
def call(env)
# 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 = env["vm"].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
env.logger.info "Destroying unused network interface..."
interface.destroy
end
end
# Continue along
@app.call(env)
end
end
end
end
end

View File

@ -0,0 +1,46 @@
require File.join(File.dirname(__FILE__), '..', '..', '..', 'test_helper')
class DestroyUnusedNetworkInterfacesVMActionTest < Test::Unit::TestCase
setup do
@klass = Vagrant::Action::VM::DestroyUnusedNetworkInterfaces
@app, @env = mock_action_data
@vm = mock("vm")
@env["vm"] = @vm
@internal_vm = mock("internal")
@vm.stubs(:vm).returns(@internal_vm)
@instance = @klass.new(@app, @env)
end
context "calling" do
setup do
@network_adapters = []
@internal_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
@app.expects(:call).with(@env).once
@instance.call(@env)
end
end
end