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', 'use_dhcp']
BOSH_APP_DIR =
'/var/vcap/bosh'
FIRST_DEVICE_NAME_LETTER =
'b'
CONNECT_RETRY_DELAY =
1
CONNECT_RETRY_COUNT =
5

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, #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



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

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"] || {}
  @use_dhcp = @openstack_properties.fetch('use_dhcp', true)

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

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

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

  @openstack_params = openstack_params

  connect_retry_errors = [Excon::Errors::GatewayTimeout, Excon::Errors::SocketError]

  @connect_retry_options = {
    sleep: CONNECT_RETRY_DELAY,
    tries: CONNECT_RETRY_COUNT,
    on: connect_retry_errors,
  }

  begin
    Bosh::Common.retryable(@connect_retry_options) do |tries, error|
      @logger.error("Failed #{tries} times, last failure due to: #{error.inspect}") unless error.nil?
      @openstack = Fog::Compute.new(@openstack_params)
    end
  rescue Excon::Errors::SocketError => e
    cloud_error(socket_error_msg + "#{e.message}")
  rescue Bosh::Common::RetryCountExceeded, Excon::Errors::ClientError, Excon::Errors::ServerError
    cloud_error('Unable to connect to the OpenStack Compute API. Check task debug log for details.')
  end

  @az_provider = Bosh::OpenStackCloud::AvailabilityZoneProvider.new(
    @openstack,
    @openstack_properties["ignore_server_availability_zone"])

  begin
    Bosh::Common.retryable(@connect_retry_options) do |tries, error|
      @logger.error("Failed #{tries} times, last failure due to: #{error.inspect}") unless error.nil?
      @glance = Fog::Image.new(@openstack_params)
    end
  rescue Excon::Errors::SocketError => e
    cloud_error(socket_error_msg + "#{e.message}")
  rescue Bosh::Common::RetryCountExceeded, Excon::Errors::ClientError, Excon::Errors::ServerError
    cloud_error('Unable to connect to the OpenStack Image Service API. Check task debug log for details.')
  end

  @metadata_lock = Mutex.new
end

Instance Attribute Details

#glanceObject (readonly)

Returns the value of attribute glance.



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

def glance
  @glance
end

#loggerObject

Returns the value of attribute logger.



22
23
24
# File 'lib/cloud/openstack/cloud.rb', line 22

def logger
  @logger
end

#openstackObject (readonly)

Returns the value of attribute openstack.



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

def openstack
  @openstack
end

#registryObject (readonly)

Returns the value of attribute registry.



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

def registry
  @registry
end

#state_timeoutObject (readonly)

Returns the value of attribute state_timeout.



21
22
23
# File 'lib/cloud/openstack/cloud.rb', line 21

def state_timeout
  @state_timeout
end

#volumeObject (readonly)

Returns the value of attribute volume.



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

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



547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/cloud/openstack/cloud.rb', line 547

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

#auth_urlObject



102
103
104
# File 'lib/cloud/openstack/cloud.rb', line 102

def auth_url
  @openstack_properties['auth_url']
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



419
420
421
422
423
424
425
# File 'lib/cloud/openstack/cloud.rb', line 419

def configure_networks(server_id, network_spec)
  with_thread_name("configure_networks(#{server_id}, ...)") do
    raise Bosh::Clouds::NotSupported,
      'network configuration change requires VM recreation: %s' % [network_spec]

  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



476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'lib/cloud/openstack/cloud.rb', line 476

def create_boot_disk(size, stemcell_id, availability_zone = nil, boot_volume_cloud_properties = {})
  volume_service_client = connect_to_volume_service
  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)

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

    if availability_zone && @az_provider.constrain_to_server_availability_zone?
      volume_params[:availability_zone] = availability_zone
    end
    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_service_client.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



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

def create_disk(size, cloud_properties, server_id = nil)
  volume_service_client = connect_to_volume_service
  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)

    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  && @az_provider.constrain_to_server_availability_zone?
      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_service_client.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



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

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

  • network_spec (Hash) (defaults to: nil)

    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



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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/cloud/openstack/cloud.rb', line 207

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)

    network_spec_security_groups = network_configurator.security_groups
    resource_pool_spec_security_groups = resource_pool_spec_security_groups(resource_pool)

    if network_spec_security_groups.size > 0 && resource_pool_spec_security_groups.size > 0
      cloud_error('Cannot define security groups in both network and resource pool.')
    end

    openstack_security_groups = with_openstack { @openstack.security_groups }.collect { |sg| sg.name }
    network_security_groups = network_configurator.security_groups(@default_security_groups)
    security_groups_to_be_used = resource_pool_spec_security_groups.size > 0 ? resource_pool_spec_security_groups : network_security_groups

    security_groups_to_be_used.each do |sg|
      cloud_error("Security group `#{sg}' not found") unless openstack_security_groups.include?(sg)
    end
    @logger.debug("Using security groups: `#{security_groups_to_be_used.join(', ')}'")

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

    image = nil
    begin
      Bosh::Common.retryable(@connect_retry_options) do |tries, error|
        @logger.error("Unable to connect to OpenStack API to find image: `#{stemcell_id} due to: #{error.inspect}") unless error.nil?
        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}'")
      end
    rescue Bosh::Common::RetryCountExceeded, Excon::Errors::SocketError => e
      cloud_error("Unable to connect to OpenStack API to find image: `#{stemcell_id}'")
    end

    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 /var/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
    validate_key_exists(keyname)

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

    if resource_pool['scheduler_hints']
      @logger.debug("Using scheduler hints: `#{resource_pool['scheduler_hints']}'")
    end

    server_params = {
      :name => server_name,
      :image_ref => image.id,
      :flavor_ref => flavor.id,
      :key_name => keyname,
      :security_groups => security_groups_to_be_used,
      :os_scheduler_hints => resource_pool['scheduler_hints'],
      :nics => nics,
      :config_drive => use_config_drive,
      :user_data => Yajl::Encoder.encode(user_data(server_name, network_spec))
    }

    availability_zone = @az_provider.select(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 => boot_vol_size,
                                               :volume_id => boot_vol_id,
                                               :delete_on_termination => "1",
                                               :device_name => "/dev/vda"
                                             }]
    end

    @logger.debug("Using boot parms: `#{server_params.inspect}'")
    begin
      server = with_openstack { @openstack.servers.create(server_params) }
    rescue Excon::Errors::Timeout => e
      @logger.debug(e.backtrace)
      cloud_error_message = "VM creation with name '#{server_params[:name]}' received a timeout. " +
                            "The VM might still have been created by OpenStack.\nOriginal message: "
      raise Bosh::Clouds::VMCreationFailed.new(false), cloud_error_message + e.message
    rescue Excon::Errors::NotFound, Fog::Compute::OpenStack::NotFound => e
      not_existing_net_ids = not_existing_net_ids(nics)
      if not_existing_net_ids.empty?
        raise e
      else
        @logger.debug(e.backtrace)
        cloud_error_message = "VM creation with name '#{server_params[:name]}' failed. Following network " +
        "IDs are not existing or not accessible from this project: '#{not_existing_net_ids.join(",")}'. " +
        "Make sure you do not use subnet IDs"
        raise Bosh::Clouds::VMCreationFailed.new(false), cloud_error_message
      end
    end

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

      @logger.info("Configuring network for server `#{server.id}'...")
      network_configurator.configure(@openstack, server)
    rescue => e
      @logger.warn("Failed to create server: #{e.message}")
      destroy_server(server)
      raise Bosh::Clouds::VMCreationFailed.new(true), e.message
    end

    begin
      @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)
    rescue => e
      @logger.warn("Failed to register server: #{e.message}")
      destroy_server(server)
      raise Bosh::Clouds::VMCreationFailed.new(false), e.message
    end

    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



523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
# File 'lib/cloud/openstack/cloud.rb', line 523

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



632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'lib/cloud/openstack/cloud.rb', line 632

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



177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/cloud/openstack/cloud.rb', line 177

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



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/cloud/openstack/cloud.rb', line 370

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



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

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) }
    if volume.nil?
      @logger.info("Disk `#{disk_id}' not found while trying to detach it from vm `#{server_id}'...")
    else
      detach_volume(server, volume)
    end

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

#has_disk?(disk_id) ⇒ bool

Check whether an OpenStack volume exists or not

Parameters:

  • disk_id (String)

    OpenStack volume UUID

Returns:

  • (bool)

    whether the specific disk is there or not



508
509
510
511
512
513
514
515
# File 'lib/cloud/openstack/cloud.rb', line 508

def has_disk?(disk_id)
  with_thread_name("has_disk?(#{disk_id})") do
    @logger.info("Check the presence of disk with id `#{disk_id}'...")
    volume = with_openstack { @openstack.volumes.get(disk_id) }

    !volume.nil?
  end
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



391
392
393
394
395
396
# File 'lib/cloud/openstack/cloud.rb', line 391

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

#is_v3Object



683
684
685
# File 'lib/cloud/openstack/cloud.rb', line 683

def is_v3
  @options['openstack']['auth_url'].match(/\/v3(?=\/|$)/)
end

#not_existing_net_ids(nics) ⇒ Object



349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/cloud/openstack/cloud.rb', line 349

def not_existing_net_ids(nics)
  result = []
  begin
    network = connect_to_network_service
    nics.each do |nic|
      if nic["net_id"]
        result << nic["net_id"] unless network.networks.get(nic["net_id"])
      end
    end
  rescue Bosh::Clouds::CloudError => e
    @logger.debug(e.backtrace)
  end
  result
end

#reboot_vm(server_id) ⇒ void

This method returns an undefined value.

Reboots an OpenStack Server

Parameters:

  • server_id (String)

    OpenStack server UUID



403
404
405
406
407
408
409
410
# File 'lib/cloud/openstack/cloud.rb', line 403

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



679
680
681
# File 'lib/cloud/openstack/cloud.rb', line 679

def select_availability_zone(volumes, resource_pool_az)
  @az_provider.select(volumes, resource_pool_az)
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



656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/cloud/openstack/cloud.rb', line 656

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



598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
# File 'lib/cloud/openstack/cloud.rb', line 598

def snapshot_disk(disk_id, )
  with_thread_name("snapshot_disk(#{disk_id})") do
     = Hash[.map{|key,value| [key.to_s, value] }]
    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