Class: Bosh::OpenStackCloud::Cloud

Inherits:
Cloud
  • Object
show all
Includes:
Helpers
Defined in:
lib/cloud/openstack/cloud.rb

Overview

BOSH OpenStack CPI

Constant Summary collapse

OPTION_KEYS =
['openstack', 'registry', 'agent']
BOSH_APP_DIR =
'/var/vcap/bosh'
FIRST_DEVICE_NAME_LETTER =
'b'

Constants included from Helpers

Helpers::DEFAULT_RETRY_TIMEOUT, Helpers::DEFAULT_STATE_TIMEOUT, Helpers::MAX_RETRIES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#cloud_error, #parse_openstack_response, #task_checkpoint, #wait_resource, #with_openstack

Constructor Details

#initialize(options) ⇒ Cloud

Creates a new BOSH OpenStack CPI

Parameters:

  • options (Hash)

    CPI options

Options Hash (options):

  • openstack (Hash)

    OpenStack specific options

  • agent (Hash)

    agent options

  • registry (Hash)

    agent options



28
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
# File 'lib/cloud/openstack/cloud.rb', line 28

def initialize(options)
  @options = normalize_options(options)

  validate_options
  initialize_registry

  @logger = Bosh::Clouds::Config.logger

  @agent_properties = @options['agent'] || {}
  @openstack_properties = @options['openstack']

  @default_key_name = @openstack_properties["default_key_name"]
  @default_security_groups = @openstack_properties["default_security_groups"]
  @state_timeout = @openstack_properties["state_timeout"]
  @stemcell_public_visibility = @openstack_properties["stemcell_public_visibility"]
  @wait_resource_poll_interval = @openstack_properties["wait_resource_poll_interval"]
  @boot_from_volume = @openstack_properties["boot_from_volume"]
  @boot_volume_cloud_properties = @openstack_properties["boot_volume_cloud_properties"] || {}

  unless @openstack_properties['auth_url'].match(/\/tokens$/)
    @openstack_properties['auth_url'] = @openstack_properties['auth_url'] + '/tokens'
  end

  @openstack_properties['connection_options'] ||= {}

  extra_connection_options = {'instrumentor' => Bosh::OpenStackCloud::ExconLoggingInstrumentor}

  openstack_params = {
    :provider => 'OpenStack',
    :openstack_auth_url => @openstack_properties['auth_url'],
    :openstack_username => @openstack_properties['username'],
    :openstack_api_key => @openstack_properties['api_key'],
    :openstack_tenant => @openstack_properties['tenant'],
    :openstack_region => @openstack_properties['region'],
    :openstack_endpoint_type => @openstack_properties['endpoint_type'],
    :connection_options => @openstack_properties['connection_options'].merge(extra_connection_options)
  }
  begin
    @openstack = Fog::Compute.new(openstack_params)
  rescue Exception => e
    @logger.error(e)
    cloud_error('Unable to connect to the OpenStack Compute API. Check task debug log for details.')
  end

  glance_params = {
    :provider => 'OpenStack',
    :openstack_auth_url => @openstack_properties['auth_url'],
    :openstack_username => @openstack_properties['username'],
    :openstack_api_key => @openstack_properties['api_key'],
    :openstack_tenant => @openstack_properties['tenant'],
    :openstack_region => @openstack_properties['region'],
    :openstack_endpoint_type => @openstack_properties['endpoint_type'],
    :connection_options => @openstack_properties['connection_options'].merge(extra_connection_options)
  }
  begin
    @glance = Fog::Image.new(glance_params)
  rescue Exception => e
    @logger.error(e)
    cloud_error('Unable to connect to the OpenStack Image Service API. Check task debug log for details.')
  end

  volume_params = {
    :provider => "OpenStack",
    :openstack_auth_url => @openstack_properties['auth_url'],
    :openstack_username => @openstack_properties['username'],
    :openstack_api_key => @openstack_properties['api_key'],
    :openstack_tenant => @openstack_properties['tenant'],
    :openstack_region => @openstack_properties['region'],
    :openstack_endpoint_type => @openstack_properties['endpoint_type'],
    :connection_options => @openstack_properties['connection_options'].merge(extra_connection_options)
  }
  begin
    @volume = Fog::Volume.new(volume_params)
  rescue Exception => e
    @logger.error(e)
    cloud_error("Unable to connect to the OpenStack Volume API. Check task debug log for details.")
  end

  @metadata_lock = Mutex.new
end

Instance Attribute Details

#glanceObject (readonly)

Returns the value of attribute glance.



17
18
19
# File 'lib/cloud/openstack/cloud.rb', line 17

def glance
  @glance
end

#loggerObject

Returns the value of attribute logger.



19
20
21
# File 'lib/cloud/openstack/cloud.rb', line 19

def logger
  @logger
end

#openstackObject (readonly)

Returns the value of attribute openstack.



15
16
17
# File 'lib/cloud/openstack/cloud.rb', line 15

def openstack
  @openstack
end

#registryObject (readonly)

Returns the value of attribute registry.



16
17
18
# File 'lib/cloud/openstack/cloud.rb', line 16

def registry
  @registry
end

#volumeObject (readonly)

Returns the value of attribute volume.



18
19
20
# File 'lib/cloud/openstack/cloud.rb', line 18

def volume
  @volume
end

Instance Method Details

#attach_disk(server_id, disk_id) ⇒ void

This method returns an undefined value.

Attaches an OpenStack volume to an OpenStack server

Parameters:

  • server_id (String)

    OpenStack server UUID

  • disk_id (String)

    OpenStack volume UUID



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/cloud/openstack/cloud.rb', line 489

def attach_disk(server_id, disk_id)
  with_thread_name("attach_disk(#{server_id}, #{disk_id})") do
    server = with_openstack { @openstack.servers.get(server_id) }
    cloud_error("Server `#{server_id}' not found") unless server

    volume = with_openstack { @openstack.volumes.get(disk_id) }
    cloud_error("Volume `#{disk_id}' not found") unless volume

    device_name = attach_volume(server, volume)

    update_agent_settings(server) do |settings|
      settings['disks'] ||= {}
      settings['disks']['persistent'] ||= {}
      settings['disks']['persistent'][disk_id] = device_name
    end
  end
end

#configure_networks(server_id, network_spec) ⇒ void

This method returns an undefined value.

Configures networking on existing OpenStack server

Parameters:

  • server_id (String)

    OpenStack server UUID

  • network_spec (Hash)

    Raw network spec passed by director

Raises:

  • (Bosh::Clouds:NotSupported)

    If there’s a network change that requires the recreation of the VM



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/cloud/openstack/cloud.rb', line 364

def configure_networks(server_id, network_spec)
  with_thread_name("configure_networks(#{server_id}, ...)") do
    @logger.info("Configuring `#{server_id}' to use the following " \
                 "network settings: #{network_spec.pretty_inspect}")
    network_configurator = NetworkConfigurator.new(network_spec)

    server = with_openstack { @openstack.servers.get(server_id) }
    cloud_error("Server `#{server_id}' not found") unless server

    compare_security_groups(server, network_configurator.security_groups(@default_security_groups))

    compare_private_ip_addresses(server, network_configurator.private_ips)

    network_configurator.configure(@openstack, server)

    update_agent_settings(server) do |settings|
      settings['networks'] = network_spec
    end
  end
end

#create_boot_disk(size, stemcell_id, availability_zone = nil, boot_volume_cloud_properties = {}) ⇒ String

Creates a new OpenStack boot volume

Parameters:

  • size (Integer)

    disk size in MiB

  • stemcell_id (String)

    OpenStack image UUID that will be used to populate the boot volume

  • availability_zone (optional, String) (defaults to: nil)

    to be passed to the volume API

  • volume_type (optional, String)

    to be passed to the volume API

Returns:

  • (String)

    OpenStack volume UUID



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/cloud/openstack/cloud.rb', line 434

def create_boot_disk(size, stemcell_id, availability_zone = nil, boot_volume_cloud_properties = {})
  with_thread_name("create_boot_disk(#{size}, #{stemcell_id}, #{availability_zone}, #{boot_volume_cloud_properties})") do
    raise ArgumentError, "Disk size needs to be an integer" unless size.kind_of?(Integer)
    cloud_error("Minimum disk size is 1 GiB") if (size < 1024)
    cloud_error("Maximum disk size is 1 TiB") if (size > 1024 * 1000)

    volume_params = {
      :display_name => "volume-#{generate_unique_name}",
      :size => (size / 1024.0).ceil,
      :imageRef => stemcell_id
    }

    volume_params[:availability_zone] = availability_zone if availability_zone
    volume_params[:volume_type] = boot_volume_cloud_properties["type"] if boot_volume_cloud_properties["type"]

    @logger.info("Creating new boot volume...")
    boot_volume = with_openstack { @volume.volumes.create(volume_params) }

    @logger.info("Creating new boot volume `#{boot_volume.id}'...")
    wait_resource(boot_volume, :available)

    boot_volume.id.to_s
  end
end

#create_disk(size, cloud_properties, server_id = nil) ⇒ String

Creates a new OpenStack volume

Parameters:

  • size (Integer)

    disk size in MiB

  • server_id (optional, String) (defaults to: nil)

    OpenStack server UUID of the VM that this disk will be attached to

Returns:

  • (String)

    OpenStack volume UUID



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/cloud/openstack/cloud.rb', line 392

def create_disk(size, cloud_properties, server_id = nil)
  with_thread_name("create_disk(#{size}, #{cloud_properties}, #{server_id})") do
    raise ArgumentError, 'Disk size needs to be an integer' unless size.kind_of?(Integer)
    cloud_error('Minimum disk size is 1 GiB') if (size < 1024)
    cloud_error('Maximum disk size is 1 TiB') if (size > 1024 * 1000)

    volume_params = {
      :display_name => "volume-#{generate_unique_name}",
      :display_description => '',
      :size => (size / 1024.0).ceil
    }

    if cloud_properties.has_key?('type')
      volume_params[:volume_type] = cloud_properties['type']
    end

    if server_id
      server = with_openstack { @openstack.servers.get(server_id) }
      if server && server.availability_zone
        volume_params[:availability_zone] = server.availability_zone
      end
    end

    @logger.info('Creating new volume...')
    new_volume = with_openstack { @volume.volumes.create(volume_params) }

    @logger.info("Creating new volume `#{new_volume.id}'...")
    wait_resource(new_volume, :available)

    new_volume.id.to_s
  end
end

#create_stemcell(image_path, cloud_properties) ⇒ String

Creates a new OpenStack Image using stemcell image. It requires access to the OpenStack Glance service.

Parameters:

  • image_path (String)

    Local filesystem path to a stemcell image

  • cloud_properties (Hash)

    CPI-specific properties

Options Hash (cloud_properties):

  • name (String)

    Stemcell name

  • version (String)

    Stemcell version

  • infrastructure (String)

    Stemcell infraestructure

  • disk_format (String)

    Image disk format

  • container_format (String)

    Image container format

  • kernel_file (optional, String)

    Name of the kernel image file provided at the stemcell archive

  • ramdisk_file (optional, String)

    Name of the ramdisk image file provided at the stemcell archive

Returns:

  • (String)

    OpenStack image UUID of the stemcell



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
# File 'lib/cloud/openstack/cloud.rb', line 125

def create_stemcell(image_path, cloud_properties)
  with_thread_name("create_stemcell(#{image_path}...)") do
    begin
      Dir.mktmpdir do |tmp_dir|
        @logger.info('Creating new image...')
        image_params = {
          :name => "BOSH-#{generate_unique_name}",
          :disk_format => cloud_properties['disk_format'],
          :container_format => cloud_properties['container_format'],
          :is_public => @stemcell_public_visibility.nil? ? false : @stemcell_public_visibility,
        }

        image_properties = {}
        vanilla_options = ['name', 'version', 'os_type', 'os_distro', 'architecture', 'auto_disk_config',
                           'hw_vif_model', 'hypervisor_type', 'vmware_adaptertype', 'vmware_disktype',
                           'vmware_linked_clone', 'vmware_ostype']
        vanilla_options.reject{ |o| cloud_properties[o].nil? }.each do |key|
          image_properties[key.to_sym] = cloud_properties[key]
        end
        image_params[:properties] = image_properties unless image_properties.empty?

        # If image_location is set in cloud properties, then pass the copy-from parm. Then Glance will fetch it
        # from the remote location on a background job and store it in its repository.
        # Otherwise, unpack image to temp directory and upload to Glance the root image.
        if cloud_properties['image_location']
          @logger.info("Using remote image from `#{cloud_properties['image_location']}'...")
          image_params[:copy_from] = cloud_properties['image_location']
        else
          @logger.info("Extracting stemcell file to `#{tmp_dir}'...")
          unpack_image(tmp_dir, image_path)
          image_params[:location] = File.join(tmp_dir, 'root.img')
        end

        # Upload image using Glance service
        @logger.debug("Using image parms: `#{image_params.inspect}'")
        image = with_openstack { @glance.images.create(image_params) }

        @logger.info("Creating new image `#{image.id}'...")
        wait_resource(image, :active)

        image.id.to_s
      end
    rescue => e
      @logger.error(e)
      raise e
    end
  end
end

#create_vm(agent_id, stemcell_id, resource_pool, network_spec = nil, disk_locality = nil, environment = nil) ⇒ String

Creates an OpenStack server and waits until it’s in running state

Parameters:

  • agent_id (String)

    UUID for the agent that will be used later on by the director to locate and talk to the agent

  • stemcell_id (String)

    OpenStack image UUID that will be used to power on new server

  • resource_pool (Hash)

    cloud specific properties describing the resources needed for this VM

  • networks (Hash)

    list of networks and their settings needed for this VM

  • disk_locality (optional, Array) (defaults to: nil)

    List of disks that might be attached to this server in the future, can be used as a placement hint (i.e. server will only be created if resource pool availability zone is the same as disk availability zone)

  • environment (optional, Hash) (defaults to: nil)

    Data to be merged into agent settings

Returns:

  • (String)

    OpenStack server UUID



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
301
302
303
304
305
306
307
308
# File 'lib/cloud/openstack/cloud.rb', line 210

def create_vm(agent_id, stemcell_id, resource_pool,
              network_spec = nil, disk_locality = nil, environment = nil)
  with_thread_name("create_vm(#{agent_id}, ...)") do
    @logger.info('Creating new server...')
    server_name = "vm-#{generate_unique_name}"

    network_configurator = NetworkConfigurator.new(network_spec)

    openstack_security_groups = with_openstack { @openstack.security_groups }.collect { |sg| sg.name }
    security_groups = network_configurator.security_groups(@default_security_groups)
    security_groups.each do |sg|
      cloud_error("Security group `#{sg}' not found") unless openstack_security_groups.include?(sg)
    end
    @logger.debug("Using security groups: `#{security_groups.join(', ')}'")

    nics = network_configurator.nics
    @logger.debug("Using NICs: `#{nics.join(', ')}'")

    image = with_openstack { @openstack.images.find { |i| i.id == stemcell_id } }
    cloud_error("Image `#{stemcell_id}' not found") if image.nil?
    @logger.debug("Using image: `#{stemcell_id}'")

    flavor = with_openstack { @openstack.flavors.find { |f| f.name == resource_pool['instance_type'] } }
    cloud_error("Flavor `#{resource_pool['instance_type']}' not found") if flavor.nil?
    if flavor_has_ephemeral_disk?(flavor)
      if flavor.ram
        # Ephemeral disk size should be at least the double of the vm total memory size, as agent will need:
        # - vm total memory size for swapon,
        # - the rest for /vcar/vcap/data
        min_ephemeral_size = (flavor.ram / 1024) * 2
        if flavor.ephemeral < min_ephemeral_size
          cloud_error("Flavor `#{resource_pool['instance_type']}' should have at least #{min_ephemeral_size}Gb " +
            'of ephemeral disk')
        end
      end
    end
    @logger.debug("Using flavor: `#{resource_pool['instance_type']}'")

    keyname = resource_pool['key_name'] || @default_key_name
    keypair = with_openstack { @openstack.key_pairs.find { |k| k.name == keyname } }
    cloud_error("Key-pair `#{keyname}' not found") if keypair.nil?
    @logger.debug("Using key-pair: `#{keypair.name}' (#{keypair.fingerprint})")

    use_config_drive = !!@openstack_properties.fetch("config_drive", nil)

    server_params = {
      :name => server_name,
      :image_ref => image.id,
      :flavor_ref => flavor.id,
      :key_name => keypair.name,
      :security_groups => security_groups,
      :nics => nics,
      :config_drive => use_config_drive,
      :user_data => Yajl::Encoder.encode(user_data(server_name, network_spec))
    }

    availability_zone = select_availability_zone(disk_locality, resource_pool['availability_zone'])
    server_params[:availability_zone] = availability_zone if availability_zone

    if @boot_from_volume
      boot_vol_size = flavor.disk * 1024

      boot_vol_id = create_boot_disk(boot_vol_size, stemcell_id, availability_zone, @boot_volume_cloud_properties)
      cloud_error("Failed to create boot volume.") if boot_vol_id.nil?
      @logger.debug("Using boot volume: `#{boot_vol_id}'")

      server_params[:block_device_mapping] = [{
                                               :volume_size => "",
                                               :volume_id => boot_vol_id,
                                               :delete_on_termination => "1",
                                               :device_name => "/dev/vda"
                                             }]
    end

    @logger.debug("Using boot parms: `#{server_params.inspect}'")
    server = with_openstack { @openstack.servers.create(server_params) }

    @logger.info("Creating new server `#{server.id}'...")
    begin
      wait_resource(server, :active, :state)
    rescue Bosh::Clouds::CloudError => e
      @logger.warn("Failed to create server: #{e.message}")

      with_openstack { server.destroy }

      raise Bosh::Clouds::VMCreationFailed.new(true)
    end

    @logger.info("Configuring network for server `#{server.id}'...")
    network_configurator.configure(@openstack, server)

    @logger.info("Updating settings for server `#{server.id}'...")
    settings = initial_agent_settings(server_name, agent_id, network_spec, environment,
                                      flavor_has_ephemeral_disk?(flavor))
    @registry.update_settings(server.name, settings)

    server.id.to_s
  end
end

#delete_disk(disk_id) ⇒ void

This method returns an undefined value.

Deletes an OpenStack volume

Parameters:

  • disk_id (String)

    OpenStack volume UUID

Raises:

  • (Bosh::Clouds::CloudError)

    if disk is not in available state



465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/cloud/openstack/cloud.rb', line 465

def delete_disk(disk_id)
  with_thread_name("delete_disk(#{disk_id})") do
    @logger.info("Deleting volume `#{disk_id}'...")
    volume = with_openstack { @openstack.volumes.get(disk_id) }
    if volume
      state = volume.status
      if state.to_sym != :available
        cloud_error("Cannot delete volume `#{disk_id}', state is #{state}")
      end

      with_openstack { volume.destroy }
      wait_resource(volume, :deleted, :status, true)
    else
      @logger.info("Volume `#{disk_id}' not found. Skipping.")
    end
  end
end

#delete_snapshot(snapshot_id) ⇒ void

This method returns an undefined value.

Deletes an OpenStack volume snapshot

Parameters:

  • snapshot_id (String)

    OpenStack snapshot UUID

Raises:

  • (Bosh::Clouds::CloudError)

    if snapshot is not in available state



571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
# File 'lib/cloud/openstack/cloud.rb', line 571

def delete_snapshot(snapshot_id)
  with_thread_name("delete_snapshot(#{snapshot_id})") do
    @logger.info("Deleting snapshot `#{snapshot_id}'...")
    snapshot = with_openstack { @openstack.snapshots.get(snapshot_id) }
    if snapshot
      state = snapshot.status
      if state.to_sym != :available
        cloud_error("Cannot delete snapshot `#{snapshot_id}', state is #{state}")
      end

      with_openstack { snapshot.destroy }
      wait_resource(snapshot, :deleted, :status, true)
    else
      @logger.info("Snapshot `#{snapshot_id}' not found. Skipping.")
    end
  end
end

#delete_stemcell(stemcell_id) ⇒ void

This method returns an undefined value.

Deletes a stemcell

Parameters:

  • stemcell_id (String)

    OpenStack image UUID of the stemcell to be deleted



180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/cloud/openstack/cloud.rb', line 180

def delete_stemcell(stemcell_id)
  with_thread_name("delete_stemcell(#{stemcell_id})") do
    @logger.info("Deleting stemcell `#{stemcell_id}'...")
    image = with_openstack { @glance.images.find_by_id(stemcell_id) }
    if image
      with_openstack { image.destroy }
      @logger.info("Stemcell `#{stemcell_id}' is now deleted")
    else
      @logger.info("Stemcell `#{stemcell_id}' not found. Skipping.")
    end
  end
end

#delete_vm(server_id) ⇒ void

This method returns an undefined value.

Terminates an OpenStack server and waits until it reports as terminated

Parameters:

  • server_id (String)

    OpenStack server UUID



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/cloud/openstack/cloud.rb', line 315

def delete_vm(server_id)
  with_thread_name("delete_vm(#{server_id})") do
    @logger.info("Deleting server `#{server_id}'...")
    server = with_openstack { @openstack.servers.get(server_id) }
    if server
      with_openstack { server.destroy }
      wait_resource(server, [:terminated, :deleted], :state, true)

      @logger.info("Deleting settings for server `#{server.id}'...")
      @registry.delete_settings(server.name)
    else
      @logger.info("Server `#{server_id}' not found. Skipping.")
    end
  end
end

#detach_disk(server_id, disk_id) ⇒ void

This method returns an undefined value.

Detaches an OpenStack volume from an OpenStack server

Parameters:

  • server_id (String)

    OpenStack server UUID

  • disk_id (String)

    OpenStack volume UUID



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/cloud/openstack/cloud.rb', line 513

def detach_disk(server_id, disk_id)
  with_thread_name("detach_disk(#{server_id}, #{disk_id})") do
    server = with_openstack { @openstack.servers.get(server_id) }
    cloud_error("Server `#{server_id}' not found") unless server

    volume = with_openstack { @openstack.volumes.get(disk_id) }
    cloud_error("Volume `#{disk_id}' not found") unless volume

    detach_volume(server, volume)

    update_agent_settings(server) do |settings|
      settings['disks'] ||= {}
      settings['disks']['persistent'] ||= {}
      settings['disks']['persistent'].delete(disk_id)
    end
  end
end

#ensure_same_availability_zone(disks, default) ⇒ String

Note:

this is a private method that is public to make it easier to test

Ensure all supplied availability zones are the same

Parameters:

  • disks (Array)

    OpenStack volumes

  • default (String)

    availability zone specified in the resource pool (may be nil)

Returns:

  • (String)

    availability zone to use or nil



636
637
638
639
640
641
642
# File 'lib/cloud/openstack/cloud.rb', line 636

def ensure_same_availability_zone(disks, default)
  zones = disks.map { |disk| disk.availability_zone }
  zones << default if default
  zones.uniq!
  cloud_error "can't use multiple availability zones: %s" %
    zones.join(', ') unless zones.size == 1 || zones.empty?
end

#has_vm?(server_id) ⇒ Boolean

Checks if an OpenStack server exists

Parameters:

  • server_id (String)

    OpenStack server UUID

Returns:

  • (Boolean)

    True if the vm exists



336
337
338
339
340
341
# File 'lib/cloud/openstack/cloud.rb', line 336

def has_vm?(server_id)
  with_thread_name("has_vm?(#{server_id})") do
    server = with_openstack { @openstack.servers.get(server_id) }
    !server.nil? && ![:terminated, :deleted].include?(server.state.downcase.to_sym)
  end
end

#reboot_vm(server_id) ⇒ void

This method returns an undefined value.

Reboots an OpenStack Server

Parameters:

  • server_id (String)

    OpenStack server UUID



348
349
350
351
352
353
354
355
# File 'lib/cloud/openstack/cloud.rb', line 348

def reboot_vm(server_id)
  with_thread_name("reboot_vm(#{server_id})") do
    server = with_openstack { @openstack.servers.get(server_id) }
    cloud_error("Server `#{server_id}' not found") unless server

    soft_reboot(server)
  end
end

#select_availability_zone(volumes, resource_pool_az) ⇒ String

Note:

this is a private method that is public to make it easier to test

Selects the availability zone to use from a list of disk volumes, resource pool availability zone (if any) and the default availability zone.

Parameters:

  • volumes (Array)

    OpenStack volume UUIDs to attach to the vm

  • resource_pool_az (String)

    availability zone specified in the resource pool (may be nil)

Returns:

  • (String)

    availability zone to use or nil



618
619
620
621
622
623
624
625
626
# File 'lib/cloud/openstack/cloud.rb', line 618

def select_availability_zone(volumes, resource_pool_az)
  if volumes && !volumes.empty?
    disks = volumes.map { |vid| with_openstack { @openstack.volumes.get(vid) } }
    ensure_same_availability_zone(disks, resource_pool_az)
    disks.first.availability_zone
  else
    resource_pool_az
  end
end

#set_vm_metadata(server_id, metadata) ⇒ void

This method returns an undefined value.

Set metadata for an OpenStack server

Parameters:

  • server_id (String)

    OpenStack server UUID

  • metadata (Hash)

    Metadata key/value pairs



595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/cloud/openstack/cloud.rb', line 595

def (server_id, )
  with_thread_name("set_vm_metadata(#{server_id}, ...)") do
    with_openstack do
      server = @openstack.servers.get(server_id)
      cloud_error("Server `#{server_id}' not found") unless server

      .each do |name, value|
        TagManager.tag(server, name, value)
      end
    end
  end
end

#snapshot_disk(disk_id, metadata) ⇒ String

Takes a snapshot of an OpenStack volume

Parameters:

  • disk_id (String)

    OpenStack volume UUID

  • metadata (Hash)

    Metadata key/value pairs to add to snapshot

Returns:

  • (String)

    OpenStack snapshot UUID

Raises:

  • (Bosh::Clouds::CloudError)

    if volume is not found



538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/cloud/openstack/cloud.rb', line 538

def snapshot_disk(disk_id, )
  with_thread_name("snapshot_disk(#{disk_id})") do
    volume = with_openstack { @openstack.volumes.get(disk_id) }
    cloud_error("Volume `#{disk_id}' not found") unless volume

    devices = []
    volume.attachments.each { |attachment| devices << attachment['device'] unless attachment.empty? }

    description = [:deployment, :job, :index].collect { |key| [key] }
    description << devices.first.split('/').last unless devices.empty?
    snapshot_params = {
      :name => "snapshot-#{generate_unique_name}",
      :description => description.join('/'),
      :volume_id => volume.id
    }

    @logger.info("Creating new snapshot for volume `#{disk_id}'...")
    snapshot = @openstack.snapshots.new(snapshot_params)
    with_openstack { snapshot.save(true) }

    @logger.info("Creating new snapshot `#{snapshot.id}' for volume `#{disk_id}'...")
    wait_resource(snapshot, :available)

    snapshot.id.to_s
  end
end