Class: ESX::Host

Inherits:
Object
  • Object
show all
Defined in:
lib/esx.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(address, user, password, opts = {}) ⇒ Host

Returns a new instance of Host.



26
27
28
29
30
31
# File 'lib/esx.rb', line 26

def initialize(address, user, password, opts = {})
  @address = address
  @password = password
  @user = user
  @templates_dir = opts[:templates_dir] || "/vmfs/volumes/datastore1/esx-gem/templates"
end

Instance Attribute Details

#addressObject (readonly)

Returns the value of attribute address.



23
24
25
# File 'lib/esx.rb', line 23

def address
  @address
end

#passwordObject (readonly)

Returns the value of attribute password.



23
24
25
# File 'lib/esx.rb', line 23

def password
  @password
end

#templates_dirObject

Returns the value of attribute templates_dir.



24
25
26
# File 'lib/esx.rb', line 24

def templates_dir
  @templates_dir
end

#userObject (readonly)

Returns the value of attribute user.



23
24
25
# File 'lib/esx.rb', line 23

def user
  @user
end

Class Method Details

.connect(host, user, password, insecure = true) ⇒ Object

Connect to a ESX host

Requires hostname/ip, username and password

Host connection is insecure by default



38
39
40
41
42
43
# File 'lib/esx.rb', line 38

def self.connect(host, user, password, insecure=true)
  vim = RbVmomi::VIM.connect :host => host, :user => user, :password => password, :insecure => insecure
  host = Host.new(host, user,password)
  host.vim = vim
  host
end

Instance Method Details

#copy_from_template(template_disk, destination) ⇒ Object

Expects vmdk source file path and destination path

copy_from_template “/home/fooser/my.vmdk”, “/vmfs/volumes/datastore1/foovm/foovm.vmdk”

Destination directory must exist otherwise rises exception



314
315
316
317
318
319
320
321
322
# File 'lib/esx.rb', line 314

def copy_from_template(template_disk, destination)
  Log.debug "Copying from template #{template_disk} to #{destination}"
  raise "Template does not exist" if not template_exist?(template_disk)
  source = File.join(@templates_dir, File.basename(template_disk))
  Net::SSH.start(@address, @user, :password => @password) do |ssh|
    Log.debug "Clone disk #{source} to #{destination}"
    Log.debug ssh.exec!("vmkfstools -i #{source} --diskformat thin #{destination} 2>&1")
  end
end

#cpu_coresObject

Number of CPU cores available in this host

returns a String



69
70
71
# File 'lib/esx.rb', line 69

def cpu_cores
  @_host.hardware.cpuInfo.numCpuCores
end

#create_net_dev(nic_id, spec) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/esx.rb', line 180

def create_net_dev(nic_id, spec)
  h = {
    :key => nic_id,
    :deviceInfo => {
      :label => "Network Adapter #{nic_id}",
      :summary => spec[:network] || 'VM Network'
    },
    :backing => RbVmomi::VIM.VirtualEthernetCardNetworkBackingInfo(
      :deviceName => spec[:network] || 'VM Network'
    )
  }

  if spec[:mac_address]
    h[:macAddress] = spec[:mac_address]
    h[:addressType] = 'manual'
  else
    h[:addressType] = 'generated'
  end
  h
end

#create_vm(specification) ⇒ Object

Create a Virtual Machine

Requires a Hash with the following keys:

:vm_name => name, (string, required)
:cpus => 1, #(int, optional)
:guest_id => 'otherGuest', #(string, optional)
:disk_size => 4096,  #(in MB, optional)
:memory => 128, #(in MB, optional)
:datastore => datastore1 #(string, optional)
:disk_file => path to vmdk inside datastore (optional)
:disk_type => flat, sparse (default flat)

supported guest_id list: pubs.vmware.com/vsphere-50/index.jsp?topic=/com.vmware.wssdk.apiref.doc_50/vim.vm.GuestOsDescriptor.GuestOsIdentifier.html

Default values above.



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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/esx.rb', line 119

def create_vm(specification)
  spec = specification
  spec[:cpus] = (specification[:cpus] || 1).to_i
  spec[:guest_id] = specification[:guest_id] || 'otherGuest'
  if specification[:disk_size]
    spec[:disk_size] = (specification[:disk_size].to_i * 1024)
  else
    spec[:disk_size] = 4194304
  end
  spec[:memory] = (specification[:memory] || 128).to_i
  if specification[:datastore]
    spec[:datastore] = "[#{specification[:datastore]}]"
  else
    spec[:datastore] = '[datastore1]'
  end
  vm_cfg = {
    :name => spec[:vm_name],
    :guestId => spec[:guest_id],
    :files => { :vmPathName => spec[:datastore] },
    :numCPUs => spec[:cpus],
    :memoryMB => spec[:memory],
    :deviceChange => [
      {
        :operation => :add,
        :device => RbVmomi::VIM.VirtualLsiLogicController(
                         :key => 1000,
                         :busNumber => 0,
                         :sharedBus => :noSharing)
      }
    ],
    :extraConfig => [
      {
        :key => 'bios.bootOrder',
        :value => 'ethernet0'
      }
    ]
  }
  
  #Add multiple nics
  nics_count = 0
  if spec[:nics]
    spec[:nics].each do |nic_spec|
      vm_cfg[:deviceChange].push(
        {
          :operation => :add,
          :device => RbVmomi::VIM.VirtualE1000(create_net_dev(nics_count, nic_spec))
          
        }
      )
      nics_count += 1
    end
  end
  # VMDK provided, replace the empty vmdk
  vm_cfg[:deviceChange].push(create_disk_spec(:disk_file => spec[:disk_file], 
                            :disk_type => spec[:disk_type],
                            :disk_size => spec[:disk_size],
                            :datastore => spec[:datastore]))

  VM.wrap(@_datacenter.vmFolder.CreateVM_Task(:config => vm_cfg, :pool => @_datacenter.hostFolder.children.first.resourcePool).wait_for_completion)
end

#datastoresObject

Return a list of ESX::Datastore objects available in this host



92
93
94
95
96
97
98
# File 'lib/esx.rb', line 92

def datastores
  datastores = []
  @_host.datastore.each do |ds|
    datastores << Datastore.wrap(ds)
  end
  datastores
end

#delete_template(template_disk) ⇒ Object

Expects fooimg.vmdk Trims path if /path/to/fooimg.vmdk



279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/esx.rb', line 279

def delete_template(template_disk)
  Log.debug "deleting template #{template_disk}"
  template = File.join(@templates_dir, File.basename(template_disk))
  template_flat = File.join(@templates_dir, File.basename(template_disk, ".vmdk") + "-flat.vmdk")
  Net::SSH.start(@address, @user, :password => @password) do |ssh|
    if (ssh.exec! "ls #{template} 2>/dev/null").nil?
      Log.error "Template #{template_disk} does not exist"
      raise "Template does not exist" 
    end 
    ssh.exec!("rm -f #{template} && rm -f #{template_flat} 2>&1")
  end
end

#host_infoObject

Return product info as an array of strings containing

fullName, apiType, apiVersion, osType, productLineId, vendor, version



205
206
207
208
209
210
211
212
213
214
215
# File 'lib/esx.rb', line 205

def host_info 
  [
   @_host.summary.config.product.fullName,
   @_host.summary.config.product.apiType,
   @_host.summary.config.product.apiVersion,
   @_host.summary.config.product.osType,
   @_host.summary.config.product.productLineId,
   @_host.summary.config.product.vendor,
   @_host.summary.config.product.version
  ]
end

#import_disk(source, destination, print_progress = false, params = {}) ⇒ Object

Imports a VMDK

if params has :use_template => true, the disk is saved as a template in Destination directory must exist otherwise rises exception



332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/esx.rb', line 332

def import_disk(source, destination, print_progress = false, params = {})
  use_template = params[:use_template] || false
  if use_template
    Log.debug "import_disk :use_template => true"
    if !template_exist?(source)
      Log.debug "import_disk, template does not exist, importing."
      import_template(source, { :print_progress => print_progress })
    end
    copy_from_template(source, destination)
  else
    import_disk_convert source, destination, print_progress
  end
end

#import_disk_convert(source, destination, print_progress = false) ⇒ Object

This method does all the heavy lifting when importing the disk. It also converts the imported VMDK to thin format



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/esx.rb', line 350

def import_disk_convert(source, destination, print_progress = false)
  tmp_dest = destination + ".tmp"
  Net::SSH.start(@address, @user, :password => @password) do |ssh|
    if not (ssh.exec! "ls #{destination} 2>/dev/null").nil?
      raise Exception.new("Destination file #{destination} already exists")
    end
    Log.info "Uploading file... (#{File.basename(source)})" if print_progress
    ssh.scp.upload!(source, tmp_dest) do |ch, name, sent, total|
      if print_progress
        print "\rProgress: #{(sent.to_f * 100 / total.to_f).to_i}%"
      end
    end
    if print_progress
      Log.info "Converting disk..."
      ssh.exec "vmkfstools -i #{tmp_dest} --diskformat thin #{destination}; rm -f #{tmp_dest}"
    else
      ssh.exec "vmkfstools -i #{tmp_dest} --diskformat thin #{destination} >/dev/null 2>&1; rm -f #{tmp_dest}"
    end
  end
end

#import_template(source, params = {}) ⇒ Object



292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/esx.rb', line 292

def import_template(source, params = {})
  print_progress = params[:print_progress] || false
  dest_file = File.join(@templates_dir, File.basename(source))
  Log.debug "Importing template #{source} to #{dest_file}"
  return dest_file if template_exist?(dest_file)
  Net::SSH.start(@address, @user, :password => @password) do |ssh|
    if (ssh.exec! "ls -la #{@templates_dir} 2>/dev/null").nil?
      # Create template dir 
      Log.debug "Creating templates dir #{@templates_dir}"
      ssh.exec "mkdir -p #{@templates_dir}"
    end
  end
  import_disk_convert(source, dest_file, print_progress)
end

#list_templatesObject



264
265
266
267
268
269
270
271
272
273
# File 'lib/esx.rb', line 264

def list_templates
  templates = []
  Net::SSH.start(@address, @user, :password => @password) do |ssh|
    output = (ssh.exec! "ls -l #{@templates_dir}/*-flat.vmdk 2>/dev/null")
    output.each_line do |t|
      templates << t.gsub(/-flat\.vmdk/,".vmdk").split().last.strip.chomp rescue next
    end unless output.nil?
  end
  templates
end

#memory_sizeObject

Host memory size in bytes

returns a Fixnum



61
62
63
# File 'lib/esx.rb', line 61

def memory_size
  @_host.hardware.memorySize.to_i
end

#memory_usageObject

Host memory usage in bytes

returns a Fixnum



85
86
87
# File 'lib/esx.rb', line 85

def memory_usage
  @_host.summary.quickStats.overallMemoryUsage * 1024 * 1024
end

#nameObject

Returns the name of this host



53
54
55
# File 'lib/esx.rb', line 53

def name
  @_host.summary.config.name
end

#power_stateObject

Power state of this host

poweredOn, poweredOff



77
78
79
# File 'lib/esx.rb', line 77

def power_state
  @_host.summary.runtime.powerState
end

#remote_command(cmd) ⇒ Object

Run a command in the ESX host via SSH



230
231
232
233
234
235
236
# File 'lib/esx.rb', line 230

def remote_command(cmd)
  output = ""
  Net::SSH.start(@address, @user, :password => @password) do |ssh|
    output = ssh.exec! cmd
  end
  output
end

#template_exist?(vmdk_file) ⇒ Boolean Also known as: has_template?

Returns:

  • (Boolean)


252
253
254
255
256
257
258
259
260
261
# File 'lib/esx.rb', line 252

def template_exist?(vmdk_file)
  template_file = File.join(@templates_dir, File.basename(vmdk_file))
  Log.debug "Checking if template #{template_file} exists"
  Net::SSH.start(@address, @user, :password => @password) do |ssh|
    return false if (ssh.exec! "ls -la #{@templates_dir} 2>/dev/null").nil?
    return false if (ssh.exec! "ls #{template_file} 2>/dev/null").nil?
  end
  Log.debug "Template #{template_file} found"
  true
end

#upload_file(source, dest, print_progress = false) ⇒ Object

Upload file



241
242
243
244
245
246
247
248
249
250
# File 'lib/esx.rb', line 241

def upload_file(source, dest, print_progress = false)
  Net::SSH.start(@address, @user, :password => @password) do |ssh|
    Log.info "Uploading file #{File.basename(source)}..." if print_progress
    ssh.scp.upload!(source, dest) do |ch, name, sent, total|
      if print_progress
        print "\rProgress: #{(sent.to_f * 100 / total.to_f).to_i}% completed"
      end
    end
  end
end

#vim=(vim) ⇒ Object



45
46
47
48
49
# File 'lib/esx.rb', line 45

def vim=(vim)
  @_vim = vim
  @_datacenter = @_vim.serviceInstance.find_datacenter
  @_host = @_datacenter.hostFolder.children.first.host.first
end

#virtual_machinesObject

Return a list of VM available in the inventory



219
220
221
222
223
224
225
# File 'lib/esx.rb', line 219

def virtual_machines
  vms = []
  vm = @_datacenter.vmFolder.childEntity.each do |x| 
    vms << VM.wrap(x)
  end
  vms
end