diff --git a/plugins/providers/virtualbox/cap.rb b/plugins/providers/virtualbox/cap.rb new file mode 100644 index 000000000..315c02c01 --- /dev/null +++ b/plugins/providers/virtualbox/cap.rb @@ -0,0 +1,20 @@ +module VagrantPlugins + module ProviderVirtualBox + module Cap + # Reads the forwarded ports that currently exist on the machine + # itself. This raises an exception if the machine isn't running. + # + # This also may not match up with configured forwarded ports, because + # Vagrant auto port collision fixing may have taken place. + # + # @return [Hash] Host => Guest port mappings. + def self.forwarded_ports(machine) + {}.tap do |result| + machine.provider.driver.read_forwarded_ports.each do |_, _, h, g| + result[h] = g + end + end + end + end + end +end diff --git a/plugins/providers/virtualbox/plugin.rb b/plugins/providers/virtualbox/plugin.rb index 4b9146f9e..66781f440 100644 --- a/plugins/providers/virtualbox/plugin.rb +++ b/plugins/providers/virtualbox/plugin.rb @@ -23,6 +23,11 @@ module VagrantPlugins require File.expand_path("../synced_folder", __FILE__) SyncedFolder end + + provider_capability(:virtualbox, :forwarded_ports) do + require_relative "cap" + Cap + end end autoload :Action, File.expand_path("../action", __FILE__) diff --git a/test/unit/plugins/providers/virtualbox/cap_test.rb b/test/unit/plugins/providers/virtualbox/cap_test.rb new file mode 100644 index 000000000..5513f18a1 --- /dev/null +++ b/test/unit/plugins/providers/virtualbox/cap_test.rb @@ -0,0 +1,36 @@ +require_relative "base" + +require Vagrant.source_root.join("plugins/providers/virtualbox/cap") + +describe VagrantPlugins::ProviderVirtualBox::Cap do + include_context "unit" + + let(:iso_env) do + # We have to create a Vagrantfile so there is a root path + env = isolated_environment + env.vagrantfile("") + env.create_vagrant_env + end + + let(:machine) do + iso_env.machine(iso_env.machine_names[0], :dummy).tap do |m| + m.provider.stub(driver: driver) + end + end + + let(:driver) { double("driver") } + + describe "#forwarded_ports" do + it "returns all the forwarded ports" do + driver.should_receive(:read_forwarded_ports).and_return([ + [nil, nil, 123, 456], + [nil, nil, 245, 245], + ]) + + expect(described_class.forwarded_ports(machine)).to eq({ + 123 => 456, + 245 => 245, + }) + end + end +end