Class: Beaker::Vcloud

Inherits:
Hypervisor
  • Object
show all
Defined in:
lib/beaker/hypervisor/vcloud.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vcloud_hosts, options) ⇒ Vcloud

Returns a new instance of Vcloud.



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/beaker/hypervisor/vcloud.rb', line 17

def initialize(vcloud_hosts, options)
  @options = options
  @logger = options[:logger]
  @hosts = vcloud_hosts

  raise 'You must specify a datastore for vCloud instances!' unless @options['datastore']
  raise 'You must specify a folder for vCloud instances!' unless @options['folder']
  raise 'You must specify a datacenter for vCloud instances!' unless @options['datacenter']

  @vcenter_credentials = get_fog_credentials(@options[:dot_fog], @options[:vcenter_instance] || :default)
end

Class Method Details

.new(vcloud_hosts, options) ⇒ Object



7
8
9
10
11
12
13
14
15
# File 'lib/beaker/hypervisor/vcloud.rb', line 7

def self.new(vcloud_hosts, options)
  # Warning for pre-vmpooler style hosts configuration. TODO: remove this eventually.
  if options['pooling_api'] && !options['datacenter']
    options[:logger].warn 'It looks like you may be trying to access vmpooler with `hypervisor: vcloud`. ' \
                          'This functionality has been removed. Change your hosts to `hypervisor: vmpooler` ' \
                          'and remove unused :datacenter, :folder, and :datastore from CONFIG.'
  end
  super
end

Instance Method Details

#booting_host(host, try, attempts) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/beaker/hypervisor/vcloud.rb', line 52

def booting_host(host, try, attempts)
  @logger.notify "Booting #{host['vmhostname']} (#{host.name}) and waiting for it to register with vSphere"
  until @vsphere_helper.find_vms(host['vmhostname'])[host['vmhostname']].summary.guest.toolsRunningStatus == 'guestToolsRunning' and
        !@vsphere_helper.find_vms(host['vmhostname'])[host['vmhostname']].summary.guest.ipAddress.nil?
    raise "vSphere registration failed after #{@options[:timeout].to_i} seconds" unless try <= attempts

    sleep 5
    try += 1

  end
end

#cleanupObject



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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/beaker/hypervisor/vcloud.rb', line 192

def cleanup
  @logger.notify 'Destroying vCloud boxes'
  connect_to_vsphere

  vm_names = @hosts.map { |h| h['vmhostname'] }.compact
  if @hosts.length != vm_names.length
    @logger.warn 'Some hosts did not have vmhostname set correctly! This likely means VM provisioning was not successful'
  end
  vms = @vsphere_helper.find_vms vm_names
  begin
    vm_names.each do |name|
      unless vm = vms[name]
        @logger.warn "Unable to cleanup #{name}, couldn't find VM #{name} in vSphere!"
        next
      end

      if vm.runtime.powerState == 'poweredOn'
        @logger.notify "Shutting down #{vm.name}"
        duration = run_and_report_duration do
          vm.PowerOffVM_Task.wait_for_completion
        end
        @logger.notify "Spent %.2f seconds halting #{vm.name}" % duration
      end

      duration = run_and_report_duration do
        vm.Destroy_Task
      end
      @logger.notify "Spent %.2f seconds destroying #{vm.name}" % duration
    end
  rescue RbVmomi::Fault => e
    if e.fault.is_a?(RbVmomi::VIM::ManagedObjectNotFound)
      # it's already gone, don't bother trying to delete it
      name = vms.key(e.fault.obj)
      vms.delete(name)
      vm_names.delete(name)
      @logger.warn "Unable to destroy #{name}, it was not found in vSphere"
      retry
    end
  end
  @vsphere_helper.close
end

#connect_to_vsphereObject



29
30
31
32
33
34
35
36
# File 'lib/beaker/hypervisor/vcloud.rb', line 29

def connect_to_vsphere
  @logger.notify "Connecting to vSphere at #{@vcenter_credentials[:vsphere_server]}" +
                 " with credentials for #{@vcenter_credentials[:vsphere_username]}"

  @vsphere_helper = VsphereHelper.new server: @vcenter_credentials[:vsphere_server],
                                      user: @vcenter_credentials[:vsphere_username],
                                      pass: @vcenter_credentials[:vsphere_password]
end

#create_clone_spec(host) ⇒ Object



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/beaker/hypervisor/vcloud.rb', line 74

def create_clone_spec(host)
  # Add VM annotation
  configSpec = RbVmomi::VIM.VirtualMachineConfigSpec(
    annotation: 'Base template:  ' + host['template'] + "\n" +
      'Creation time:  ' + Time.now.strftime('%Y-%m-%d %H:%M') + "\n\n" +
      'CI build link:  ' + (ENV['BUILD_URL'] || 'Deployed independently of CI') +
      'department:     ' + @options[:department] +
      'project:        ' + @options[:project],
    extraConfig: [
      { key: 'guestinfo.hostname',
        value: host['vmhostname'], },
    ],
  )

  # Are we using a customization spec?
  customizationSpec = @vsphere_helper.find_customization(host['template'])

  if customizationSpec
    # Print a logger message if using a customization spec
    @logger.notify "Found customization spec for '#{host['template']}', will apply after boot"
  end

  # Put the VM in the specified folder and resource pool
  relocateSpec = RbVmomi::VIM.VirtualMachineRelocateSpec(
    datastore: @vsphere_helper.find_datastore(@options['datacenter'], @options['datastore']),
    pool: if @options['resourcepool']
            @vsphere_helper.find_pool(@options['datacenter'],
                                      @options['resourcepool'])
          end,
    diskMoveType: :moveChildMostDiskBacking,
  )

  # Create a clone spec
  RbVmomi::VIM.VirtualMachineCloneSpec(
    config: configSpec,
    location: relocateSpec,
    customization: customizationSpec,
    powerOn: true,
    template: false,
  )
end

#enable_root(host) ⇒ Object

Directly borrowed from openstack hypervisor



65
66
67
68
69
70
71
72
# File 'lib/beaker/hypervisor/vcloud.rb', line 65

def enable_root(host)
  return unless host['user'] != 'root'

  copy_ssh_to_root(host, @options)
  (host, @options)
  host['user'] = 'root'
  host.close
end

#provisionObject



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
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
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/beaker/hypervisor/vcloud.rb', line 116

def provision
  connect_to_vsphere
  begin
    try = 1
    attempts = @options[:timeout].to_i / 5

    start = Time.now
    tasks = []
    @hosts.each_with_index do |h, _i|
      h['vmhostname'] = (h['name'] || generate_host_name)

      if h['template'].nil? and defined?(ENV.fetch('BEAKER_vcloud_template', nil))
        h['template'] = ENV.fetch('BEAKER_vcloud_template', nil)
      end

      unless h['template']
        raise "Missing template configuration for #{h}.  Set template in nodeset or set ENV[BEAKER_vcloud_template]"
      end

      if %r{/}.match?(h['template'])
        templatefolders = h['template'].split('/')
        h['template'] = templatefolders.pop
      end

      @logger.notify "Deploying #{h['vmhostname']} (#{h.name}) to #{@options['folder']} from template '#{h['template']}'"

      vm = {}

      if templatefolders
        vm[h['template']] =
          @vsphere_helper.find_folder(@options['datacenter'], templatefolders.join('/')).find(h['template'])
      else
        vm = @vsphere_helper.find_vms(h['template'])
      end

      raise "Unable to find template '#{h['template']}'!" if vm.length == 0

      spec = create_clone_spec(h)

      # Deploy from specified template
      tasks << vm[h['template']].CloneVM_Task(
        folder: @vsphere_helper.find_folder(@options['datacenter'],
                                            @options['folder']), name: h['vmhostname'], spec: spec
      )
    end

    try = (Time.now - start) / 5
    @vsphere_helper.wait_for_tasks(tasks, try, attempts)
    @logger.notify format('Spent %.2f seconds deploying VMs', (Time.now - start))

    try = (Time.now - start) / 5
    duration = run_and_report_duration do
      @hosts.each_with_index do |h, _i|
        booting_host(h, try, attempts)
      end
    end
    @logger.notify 'Spent %.2f seconds booting and waiting for vSphere registration' % duration

    try = (Time.now - start) / 5
    duration = run_and_report_duration do
      @hosts.each do |host|
        repeat_fibonacci_style_for 8 do
          !@vsphere_helper.find_vms(host['vmhostname'])[host['vmhostname']].summary.guest.ipAddress.nil?
        end
        host[:ip] = @vsphere_helper.find_vms(host['vmhostname'])[host['vmhostname']].summary.guest.ipAddress
        enable_root(host) unless host.is_cygwin?
      end
    end

    @logger.notify 'Spent %.2f seconds waiting for DNS resolution' % duration
  rescue StandardError => e
    @vsphere_helper.close
    report_and_raise(@logger, e, 'Vcloud.provision')
  end
end

#wait_for_dns_resolution(host, try, attempts) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/beaker/hypervisor/vcloud.rb', line 38

def wait_for_dns_resolution(host, try, attempts)
  @logger.notify "Waiting for #{host['vmhostname']} DNS resolution"
  begin
    Socket.getaddrinfo(host['vmhostname'], nil)
  rescue StandardError
    raise "DNS resolution failed after #{@options[:timeout].to_i} seconds" unless try <= attempts

    sleep 5
    try += 1

    retry
  end
end