Class: Fog::Compute::Vsphere::Real

Inherits:
Object
  • Object
show all
Includes:
Shared
Defined in:
lib/fog/vsphere/requests/compute/find_vm_by_ref.rb,
lib/fog/vsphere/compute.rb,
lib/fog/vsphere/requests/compute/vm_clone.rb,
lib/fog/vsphere/requests/compute/vm_reboot.rb,
lib/fog/vsphere/requests/compute/vm_destroy.rb,
lib/fog/vsphere/requests/compute/datacenters.rb,
lib/fog/vsphere/requests/compute/vm_power_on.rb,
lib/fog/vsphere/requests/compute/current_time.rb,
lib/fog/vsphere/requests/compute/vm_power_off.rb,
lib/fog/vsphere/requests/compute/list_virtual_machines.rb

Overview

The Real and Mock classes share the same method because list_virtual_machines will be properly mocked for us

Constant Summary

Constants included from Shared

Shared::ATTR_TO_PROP

Instance Attribute Summary

Attributes included from Shared

#vsphere_is_vcenter, #vsphere_rev, #vsphere_server, #vsphere_username

Instance Method Summary collapse

Methods included from Shared

#convert_vm_mob_ref_to_attr_hash, #find_vm_by_ref

Constructor Details

#initialize(options = {}) ⇒ Real

Returns a new instance of Real.



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/fog/vsphere/compute.rb', line 103

def initialize(options={})
  require 'rbvmomi'
  @vsphere_username = options[:vsphere_username]
  @vsphere_password = options[:vsphere_password]
  @vsphere_server   = options[:vsphere_server]
  @vsphere_port     = options[:vsphere_port] || 443
  @vsphere_path     = options[:vsphere_path] || '/sdk'
  @vsphere_ns       = options[:vsphere_ns] || 'urn:vim25'
  @vsphere_rev      = options[:vsphere_rev] || '4.0'
  @vsphere_ssl      = options[:vsphere_ssl] || true
  @vsphere_expected_pubkey_hash = options[:vsphere_expected_pubkey_hash]
  @vsphere_must_reauthenticate = false

  @connection = nil
  # This is a state variable to allow digest validation of the SSL cert
  bad_cert = false
  loop do
    begin
      @connection = RbVmomi::VIM.new :host => @vsphere_server,
                                     :port => @vsphere_port,
                                     :path => @vsphere_path,
                                     :ns   => @vsphere_ns,
                                     :rev  => @vsphere_rev,
                                     :ssl  => @vsphere_ssl,
                                     :insecure => bad_cert
      break
    rescue OpenSSL::SSL::SSLError
      raise if bad_cert
      bad_cert = true
    end
  end

  if bad_cert then
    validate_ssl_connection
  end

  # Negotiate the API revision
  if not options[:vsphere_rev]
    rev = @connection.serviceContent.about.apiVersion
    @connection.rev = [ rev, ENV['FOG_VSPHERE_REV'] || '4.1' ].min
  end

  @vsphere_is_vcenter = @connection.serviceContent.about.apiType == "VirtualCenter"
  @vsphere_rev = @connection.rev

  authenticate
end

Instance Method Details

#current_timeObject



6
7
8
9
# File 'lib/fog/vsphere/requests/compute/current_time.rb', line 6

def current_time
  current_time = @connection.serviceInstance.CurrentTime
  { 'current_time' => current_time }
end

#datacentersObject



5
6
7
8
9
# File 'lib/fog/vsphere/requests/compute/datacenters.rb', line 5

def datacenters
  @datacenters ||= datacenters_reload
  # Hide the values which are the RbVmomi instances
  @datacenters.keys
end

#list_virtual_machines(options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/fog/vsphere/requests/compute/list_virtual_machines.rb', line 5

def list_virtual_machines(options = {})
  # Listing all VM's can be quite slow and expensive.  Try and optimize
  # based on the available options we have.  These conditions are in
  # ascending order of  time to complete for large deployments.
  if options['instance_uuid'] then
    list_all_virtual_machines_by_instance_uuid(options)
  elsif options['folder'] then
    list_all_virtual_machines_in_folder(options)
  else
    list_all_virtual_machines
  end
end

#vm_clone(options = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/fog/vsphere/requests/compute/vm_clone.rb', line 29

def vm_clone(options = {})
  # Option handling
  options = vm_clone_check_options(options)

  notfound = lambda { raise Fog::Compute::Vsphere::NotFound, "Could not find VM template" }

  # Find the template in the folder.  This is more efficient than
  # searching ALL VM's looking for the template.
  # Tap gets rid of the leading empty string and "Datacenters" element
  # and returns the array.
  path_elements = options['path'].split('/').tap { |ary| ary.shift 2 }
  # The DC name itself.
  template_dc = path_elements.shift
  # If the first path element contains "vm" this denotes the vmFolder
  # and needs to be shifted out
  path_elements.shift if path_elements[0] = 'vm'
  # The template name.  The remaining elements are the folders in the
  # datacenter.
  template_name = path_elements.pop
  # Make sure @datacenters is populated.  We need the instances from the Hash keys.
  self.datacenters
  # Get the datacenter managed object from the hash
  dc = @datacenters[template_dc]
  # Get the VM Folder (Group) efficiently
  vm_folder = dc.vmFolder
  # Walk the tree resetting the folder pointer as we go
  folder = path_elements.inject(vm_folder) do |current_folder, sub_folder_name|
    # JJM VIM::Folder#find appears to be quite efficient as it uses the
    # searchIndex It certainly appears to be faster than
    # VIM::Folder#inventory since that returns _all_ managed objects of
    # a certain type _and_ their properties.
    sub_folder = current_folder.find(sub_folder_name, RbVmomi::VIM::Folder)
    raise ArgumentError, "Could not descend into #{sub_folder_name}.  Please check your path." unless sub_folder
    sub_folder
  end

  # Now find the template itself using the efficient find method
  vm_mob_ref = folder.find(template_name, RbVmomi::VIM::VirtualMachine)

  # Now find _a_ resource pool of the template's host (REVISIT: We need
  # to support cloning into a specific RP)
  esx_host = vm_mob_ref.collect!('runtime.host')['runtime.host']
  # The parent of the ESX host itself is a ComputeResource which has a resourcePool
  resource_pool = esx_host.parent.resourcePool

  # Next, create a Relocation Spec instance
  relocation_spec = RbVmomi::VIM.VirtualMachineRelocateSpec(:pool => resource_pool,
                                                            :transform => options['transform'] || 'sparse')
  # And the clone specification
  clone_spec = RbVmomi::VIM.VirtualMachineCloneSpec(:location => relocation_spec,
                                                    :powerOn  => options['power_on'] || true,
                                                    :template => false)
  task = vm_mob_ref.CloneVM_Task(:folder => vm_mob_ref.parent, :name => options['name'], :spec => clone_spec)

  # Waiting for the VM to complete allows us to get the VirtulMachine
  # object of the new machine when it's done.  It is HIGHLY recommended
  # to set 'wait' => true if your app wants to wait.  Otherwise, you're
  # going to have to reload the server model over and over which
  # generates a lot of time consuming API calls to vmware.
  if options['wait'] then
    # REVISIT: It would be awesome to call a block passed to this
    # request to notify the application how far along in the process we
    # are.  I'm thinking of updating a progress bar, etc...
    new_vm = task.wait_for_completion
  else
    tries = 0
    new_vm = begin
      # Try and find the new VM (folder.find is quite efficient)
      folder.find(options['name'], RbVmomi::VIM::VirtualMachine) or raise Fog::Vsphere::Errors::NotFound
    rescue Fog::Vsphere::Errors::NotFound
      tries += 1
      if tries <= 10 then
        sleep 15
        retry
      end
      nil
    end
  end

  # Return hash
  {
    'vm_ref'        => new_vm ? new_vm._ref : nil,
    'vm_attributes' => new_vm ? convert_vm_mob_ref_to_attr_hash(new_vm) : {},
    'task_ref'      => task._ref
  }
end

#vm_destroy(options = {}) ⇒ Object

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/fog/vsphere/requests/compute/vm_destroy.rb', line 6

def vm_destroy(options = {})
  raise ArgumentError, "instance_uuid is a required parameter" unless options.has_key? 'instance_uuid'

  # Find the VM Object
  search_filter = { :uuid => options['instance_uuid'], 'vmSearch' => true, 'instanceUuid' => true }
  vm_mob_ref = @connection.searchIndex.FindAllByUuid(search_filter).first

  unless vm_mob_ref.kind_of? RbVmomi::VIM::VirtualMachine
    raise Fog::Vsphere::Errors::NotFound,
      "Could not find VirtualMachine with instance uuid #{options['instance_uuid']}"
  end
  task = vm_mob_ref.Destroy_Task
  task.wait_for_completion
  { 'task_state' => task.info.state }
end

#vm_power_off(options = {}) ⇒ Object

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/fog/vsphere/requests/compute/vm_power_off.rb', line 6

def vm_power_off(options = {})
  options = { 'force' => false }.merge(options)
  raise ArgumentError, "instance_uuid is a required parameter" unless options.has_key? 'instance_uuid'

  search_filter = { :uuid => options['instance_uuid'], 'vmSearch' => true, 'instanceUuid' => true }
  vm_mob_ref = @connection.searchIndex.FindAllByUuid(search_filter).first

  if options['force'] then
    task = vm_mob_ref.PowerOffVM_Task
    task.wait_for_completion
    { 'task_state' => task.info.result, 'power_off_type' => 'cut_power' }
  else
    vm_mob_ref.ShutdownGuest
    {
      'task_state'     => "running",
      'power_off_type' => 'shutdown_guest',
    }
  end
end

#vm_power_on(options = {}) ⇒ Object

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
# File 'lib/fog/vsphere/requests/compute/vm_power_on.rb', line 6

def vm_power_on(options = {})
  raise ArgumentError, "instance_uuid is a required parameter" unless options.has_key? 'instance_uuid'

  search_filter = { :uuid => options['instance_uuid'], 'vmSearch' => true, 'instanceUuid' => true }
  vm_mob_ref = @connection.searchIndex.FindAllByUuid(search_filter).first

  task = vm_mob_ref.PowerOnVM_Task
  task.wait_for_completion
  # 'success', 'running', 'queued', 'error'
  { 'task_state' => task.info.state }
end

#vm_reboot(options = {}) ⇒ Object

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/fog/vsphere/requests/compute/vm_reboot.rb', line 6

def vm_reboot(options = {})
  options = { 'force' => false }.merge(options)
  raise ArgumentError, "instance_uuid is a required parameter" unless options.has_key? 'instance_uuid'

  search_filter = { :uuid => options['instance_uuid'], 'vmSearch' => true, 'instanceUuid' => true }
  vm_mob_ref = @connection.searchIndex.FindAllByUuid(search_filter).first

  if options['force'] then
    task = vm_mob_ref.ResetVM_Task
    task.wait_for_completion
    { 'task_state' => task.info.result, 'reboot_type' => 'reset_power' }
  else
    vm_mob_ref.ShutdownGuest
    { 'task_state' => "running", 'reboot_type' => 'reboot_guest' }
  end
end