From e334e545ef0fd07a3c5598606b80277cd8604941 Mon Sep 17 00:00:00 2001 From: Kevin Menard Date: Fri, 1 Nov 2013 15:28:37 -0400 Subject: [PATCH] [vsphere|compute] Implemented idiomatic interface creation. --- lib/fog/vsphere/models/compute/interface.rb | 30 +++++++++++++++++++ lib/fog/vsphere/models/compute/interfaces.rb | 2 +- .../requests/compute/modify_vm_interface.rb | 2 +- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/fog/vsphere/models/compute/interface.rb b/lib/fog/vsphere/models/compute/interface.rb index 08054355e..cd099774e 100644 --- a/lib/fog/vsphere/models/compute/interface.rb +++ b/lib/fog/vsphere/models/compute/interface.rb @@ -4,6 +4,8 @@ module Fog class Interface < Fog::Model + SAVE_MUTEX = Mutex.new + identity :mac alias :id :mac @@ -44,6 +46,34 @@ module Fog service.destroy_vm_interface(server_id, :key => key, :type => type) end + def save + raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? + requires :server_id, :type, :network + + # Our approach of finding the newly created interface is rough. We assume that the :key value always increments + # and thus the highest :key value must correspond to the created interface. Since this has an inherent race + # condition we need to gate the saves. + SAVE_MUTEX.synchronize do + data = service.add_vm_interface(server_id, attributes) + + if data['task_state'] == 'success' + # We have to query vSphere to get the interface attributes since the task handle doesn't include that info. + created = server.interfaces.all.sort_by(&:key).last + + self.mac = created.mac + self.name = created.name + self.status = created.status + self.summary = created.summary + self.key = created.key + self.virtualswitch = created.virtualswitch + + true + else + false + end + end + end + private def defaults diff --git a/lib/fog/vsphere/models/compute/interfaces.rb b/lib/fog/vsphere/models/compute/interfaces.rb index 7c0d8b412..2e2b4f9b1 100644 --- a/lib/fog/vsphere/models/compute/interfaces.rb +++ b/lib/fog/vsphere/models/compute/interfaces.rb @@ -48,7 +48,7 @@ module Fog def new(attributes = {}) if server - super({ :server => server }.merge(attributes)) + super({ :server_id => server.id }.merge(attributes)) else super end diff --git a/lib/fog/vsphere/requests/compute/modify_vm_interface.rb b/lib/fog/vsphere/requests/compute/modify_vm_interface.rb index 8c601b440..4067fbb92 100644 --- a/lib/fog/vsphere/requests/compute/modify_vm_interface.rb +++ b/lib/fog/vsphere/requests/compute/modify_vm_interface.rb @@ -6,7 +6,7 @@ module Fog def add_vm_interface(vmid, options = {}) raise ArgumentError, "instance id is a required parameter" unless vmid - interface = get_interface_from_options(vmid, options) + interface = get_interface_from_options(vmid, options.merge(:server_id => vmid)) vm_reconfig_hardware('instance_uuid' => vmid, 'hardware_spec' => {'deviceChange'=>[create_interface(interface)]}) end