Class: ChefProvisioningVsphere::VsphereHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connect_options, datacenter_name) ⇒ VsphereHelper

Returns a new instance of VsphereHelper.



10
11
12
13
14
15
16
17
18
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 10

def initialize(connect_options, datacenter_name)
  http = Net::HTTP.new(connect_options[:host], connect_options[:port])
  if http.proxy?
    connect_options[:proxyHost] = http.proxy_address
    connect_options[:proxyPort] = http.proxy_port
  end
  @connect_options = connect_options
  @datacenter_name = datacenter_name
end

Instance Attribute Details

#connect_optionsObject (readonly)

Returns the value of attribute connect_options.



20
21
22
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 20

def connect_options
  @connect_options
end

#datacenter_nameObject (readonly)

Returns the value of attribute datacenter_name.



21
22
23
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 21

def datacenter_name
  @datacenter_name
end

Instance Method Details

#add_extra_nic(action_handler, vm_template, options, vm) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 121

def add_extra_nic(action_handler, vm_template, options, vm)
  deviceAdditions, changes = network_device_changes(action_handler, vm_template, options)

  if deviceAdditions.count > 0
    current_networks = find_ethernet_cards_for(vm).map { |card| network_id_for(card.backing) }
    new_devices = deviceAdditions.select { |device| !current_networks.include?(network_id_for(device.device.backing)) }

    if new_devices.count > 0
      action_handler.report_progress 'Adding extra NICs'
      task = vm.ReconfigVM_Task(spec: RbVmomi::VIM.VirtualMachineConfigSpec(deviceChange: new_devices))
      task.wait_for_completion
      new_devices
    end
  end
end

#backing_info_for(action_handler, network_name) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 219

def backing_info_for(action_handler, network_name)
  action_handler.report_progress('finding networks...')
  network = find_network(network_name)
  action_handler.report_progress(
    "network: #{network_name} is a #{network.class}"
  )
  if network.is_a?(RbVmomi::VIM::DistributedVirtualPortgroup)
    port = RbVmomi::VIM::DistributedVirtualSwitchPortConnection(
      switchUuid: network.config.distributedVirtualSwitch.uuid,
      portgroupKey: network.key
    )
    RbVmomi::VIM::VirtualEthernetCardDistributedVirtualPortBackingInfo(
      port: port
    )
  else
    RbVmomi::VIM::VirtualEthernetCardNetworkBackingInfo(
      deviceName: network_name.split('/').last
    )
  end
end

#create_delta_disk(vm_template) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 145

def create_delta_disk(vm_template)
disks = vm_template.config.hardware.device.grep(RbVmomi::VIM::VirtualDisk)
disks.select { |disk| disk.backing.parent.nil? }.each do |disk|
  spec = {
    deviceChange: [
      {
        operation: :remove,
        device: disk
      },
      {
        operation: :add,
        fileOperation: :create,
        device: disk.dup.tap do |new_disk|
          new_disk.backing = new_disk.backing.dup
          new_disk.backing.fileName = "[#{disk.backing.datastore.name}]"
          new_disk.backing.parent = disk.backing
        end
      }
    ]
  }
  vm_template.ReconfigVM_Task(spec: spec).wait_for_completion
end
end

#datacenterObject



87
88
89
90
91
92
93
94
95
96
97
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 87

def datacenter
  vim # ensure connection is valid
  @datacenter ||= begin
    rootFolder = vim.serviceInstance.content.rootFolder
    dc = rootFolder.childEntity.grep(RbVmomi::VIM::Datacenter).find do |x|
      x.name == datacenter_name
    end
    raise("vSphere Datacenter not found [#{datacenter_name}]") if dc.nil?
    dc
  end
end

#find_customization_spec(customization_spec) ⇒ Object



320
321
322
323
324
325
326
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 320

def find_customization_spec(customization_spec)
  csm = vim.serviceContent.customizationSpecManager
  csi = csm.GetCustomizationSpec(name: customization_spec)
  spec = csi.spec
  raise "Customization Spec not found [#{customization_spec}]" if spec.nil?
  spec
end

#find_datastore(datastore_name) ⇒ Object



240
241
242
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 240

def find_datastore(datastore_name)
  datacenter.datastore.find { |f| f.info.name == datastore_name } || raise("no such datastore #{datastore_name}")
end

#find_entity(name, parent_folder) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 244

def find_entity(name, parent_folder)
  parts = name.split('/').reject(&:empty?)
  parts.each do |item|
    Chef::Log.debug("Identifying entity part: #{item} in folder type: #{parent_folder.class}")
    if parent_folder.is_a? RbVmomi::VIM::Folder
      Chef::Log.debug('Parent folder is a folder')
      parent_folder = parent_folder.childEntity.find { |f| f.name == item }
    else
      parent_folder = yield(parent_folder, item)
    end
  end
  parent_folder
end

#find_ethernet_cards_for(vm) ⇒ Object



117
118
119
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 117

def find_ethernet_cards_for(vm)
  vm.config.hardware.device.select { |d| d.is_a?(RbVmomi::VIM::VirtualEthernetCard) }
end

#find_folder(folder_name) ⇒ Object

folder could be like: /Level1/Level2/folder_name



76
77
78
79
80
81
82
83
84
85
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 76

def find_folder(folder_name)
  base = datacenter.vmFolder
  unless folder_name.nil?
    folder_name.split('/').reject(&:empty?).each do |item|
      base = base.find(item, RbVmomi::VIM::Folder) ||
             raise("vSphere Folder not found [#{folder_name}]")
    end
  end
  base
end

#find_host(host_name) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 258

def find_host(host_name)
  host = find_entity(host_name, datacenter.hostFolder) do |parent, part|
    case parent
    when RbVmomi::VIM::ClusterComputeResource || RbVmomi::VIM::ComputeResource
      parent.host.find { |f| f.name == part }
    when RbVmomi::VIM::HostSystem
      parent.host.find { |f| f.name == part }
    end
  end

  raise "vSphere Host not found [#{host_name}]" if host.nil?

  host = host.host.first if host.is_a?(RbVmomi::VIM::ComputeResource)
  host
end

#find_network(name) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 302

def find_network(name)
  base = datacenter.networkFolder
  entity_array = name.split('/').reject(&:empty?)
  entity_array.each do |item|
    case base
    when RbVmomi::VIM::Folder
      base = base.find(item)
    when RbVmomi::VIM::VmwareDistributedVirtualSwitch
      idx = base.summary.portgroupName.find_index(item)
      base = idx.nil? ? nil : base.portgroup[idx]
    end
  end

  raise "vSphere Network not found [#{name}]" if base.nil?

  base
end

#find_pool(pool_name) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 274

def find_pool(pool_name)
  Chef::Log.debug("Finding pool: #{pool_name}")
  pool = find_entity(pool_name, datacenter.hostFolder) do |parent, part|
    case parent
    when RbVmomi::VIM::ClusterComputeResource, RbVmomi::VIM::ComputeResource
      Chef::Log.debug("finding #{part} in a #{parent.class}: #{parent.name}")
      Chef::Log.debug("Parent root pool has #{parent.resourcePool.resourcePool.count} pools")
      parent.resourcePool.resourcePool.each { |p| Chef::Log.debug(p.name) }
      parent.resourcePool.resourcePool.find { |f| f.name == part }
    when RbVmomi::VIM::ResourcePool
      Chef::Log.debug("finding #{part} in a Resource Pool: #{parent.name}")
      Chef::Log.debug("Pool has #{parent.resourcePool.count} pools")
      parent.resourcePool.each { |p| Chef::Log.debug(p.name) }
      parent.resourcePool.find { |f| f.name == part }
    else
      Chef::Log.debug("parent of #{part} is unexpected type: #{parent.class}")
      nil
    end
  end

  raise "vSphere ResourcePool not found [#{pool_name}]" if pool.nil?

  if !pool.is_a?(RbVmomi::VIM::ResourcePool) && pool.respond_to?(:resourcePool)
    pool = pool.resourcePool
  end
  pool
end

#find_vm(folder, vm_name) ⇒ Object



43
44
45
46
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 43

def find_vm(folder, vm_name)
  folder = find_folder(folder) unless folder.is_a? RbVmomi::VIM::Folder
  folder.find(vm_name, RbVmomi::VIM::VirtualMachine)
end

#find_vm_by_id(uuid) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 48

def find_vm_by_id(uuid)
  vm = vim.searchIndex.FindByUuid(
    uuid: uuid,
    vmSearch: true,
    instanceUuid: true
  )
end

#network_adapter_for(operation, network_name, network_label, device_key, backing_info) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 99

def network_adapter_for(operation, network_name, network_label, device_key, backing_info)
  connectable = RbVmomi::VIM::VirtualDeviceConnectInfo(
    allowGuestControl: true,
    connected: true,
    startConnected: true
  )
  device = RbVmomi::VIM::VirtualVmxnet3(
    backing: backing_info,
    deviceInfo: RbVmomi::VIM::Description(label: network_label, summary: network_name.split('/').last),
    key: device_key,
    connectable: connectable
  )
  RbVmomi::VIM::VirtualDeviceConfigSpec(
    operation: operation,
    device: device
  )
end

#network_device_changes(action_handler, vm_template, options) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 188

def network_device_changes(action_handler, vm_template, options)
  additions = []
  changes = []
  networks = options[:network_name]
  networks = [networks] if networks.is_a?(String)

  cards = find_ethernet_cards_for(vm_template)

  key = 4000
  networks.each_index do |i|
    label = "Ethernet #{i + 1}"
    backing_info = backing_info_for(action_handler, networks[i])
    if card = cards.shift
      key = card.key
      operation = RbVmomi::VIM::VirtualDeviceConfigSpecOperation('edit')
      action_handler.report_progress "changing template nic for #{networks[i]}"
      changes.push(
        network_adapter_for(operation, networks[i], label, key, backing_info)
      )
    else
      key += 1
      operation = RbVmomi::VIM::VirtualDeviceConfigSpecOperation('add')
      action_handler.report_progress "will be adding nic for #{networks[i]}"
      additions.push(
        network_adapter_for(operation, networks[i], label, key, backing_info)
      )
    end
  end
  [additions, changes]
end

#network_id_for(backing_info) ⇒ Object



137
138
139
140
141
142
143
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 137

def network_id_for(backing_info)
  if backing_info.is_a?(RbVmomi::VIM::VirtualEthernetCardDistributedVirtualPortBackingInfo)
    backing_info.port.portgroupKey
  else
    backing_info.deviceName
  end
end

#start_vm(vm, _wait_on_port = 22) ⇒ Object



56
57
58
59
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 56

def start_vm(vm, _wait_on_port = 22)
  state = vm.runtime.powerState
  vm.PowerOnVM_Task.wait_for_completion unless state == 'poweredOn'
end

#stop_vm(vm, timeout = 600) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 61

def stop_vm(vm, timeout = 600)
  start = Time.now.utc
  begin
    vm.ShutdownGuest
    until (Time.now.utc - start) > timeout ||
          vm.runtime.powerState == 'poweredOff'
      print '.'
      sleep 2
    end
  rescue
    vm.PowerOffVM_Task.wait_for_completion
  end
end

#upload_file_to_vm(vm, username, password, local, remote) ⇒ Object



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 328

def upload_file_to_vm(vm, username, password, local, remote)
  auth = RbVmomi::VIM::NamePasswordAuthentication(username: username, password: password, interactiveSession: false)
  size = File.size(local)
  endpoint = $guest_op_managers[vim.pretty_inspect].fileManager.InitiateFileTransferToGuest(
    vm: vm,
    auth: auth,
    guestFilePath: remote,
    overwrite: true,
    fileAttributes: RbVmomi::VIM::GuestWindowsFileAttributes.new,
    fileSize: size
  )

  uri = URI.parse(endpoint)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  req = Net::HTTP::Put.new("#{uri.path}?#{uri.query}")
  req.body_stream = File.open(local)
  req['Content-Type'] = 'application/octet-stream'
  req['Content-Length'] = size
  res = http.request(req)
  unless res.is_a?(Net::HTTPSuccess)
    raise "Error: #{res.inspect} :: #{res.body} :: sending #{local} to #{remote} at #{vm.name} via #{endpoint} with a size of #{size}"
  end
end

#vimObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 23

def vim
  if @current_connection.nil? || @current_connection.serviceContent.sessionManager.currentSession.nil?
    @datacenter = nil
    puts "establishing connection to #{connect_options[:host]}"
    @current_connection = RbVmomi::VIM.connect connect_options
    str_conn = @current_connection.pretty_inspect # a string in the format of VIM(host ip)

    # we are caching guest operation managers in a global variable...terrible i know
    # this object is available from the serviceContent object on API version 5 forward
    # Its a singleton and if another connection is made for the same host and user
    # that object is not available on any subsequent connection
    # I could find no documentation that discusses this
    unless $guest_op_managers.key?(str_conn)
      $guest_op_managers[str_conn] = @current_connection.serviceContent.guestOperationsManager
    end
  end

  @current_connection
end

#virtual_disk_for(vm, datastore, size_gb) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/chef/provisioning/vsphere_driver/vsphere_helpers.rb', line 169

def virtual_disk_for(vm, datastore, size_gb)
  idx = vm.disks.count
  RbVmomi::VIM::VirtualDeviceConfigSpec(
    operation: :add,
    fileOperation: :create,
    device: RbVmomi::VIM.VirtualDisk(
      key: idx,
      backing: RbVmomi::VIM.VirtualDiskFlatVer2BackingInfo(
        fileName: "[#{datastore}]",
        diskMode: 'persistent',
        thinProvisioned: true
      ),
      capacityInKB: size_gb * 1024 * 1024,
      controllerKey: 1000,
      unitNumber: idx
    )
  )
end