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, #task_checkpoint, #wait_resource, #with_openstack

Constructor Details

#initialize(options) ⇒ Cloud

Creates a new BOSH OpenStack CPI

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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# 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$/)
    @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_domain_name => @openstack_properties['domain'],
    :openstack_region => @openstack_properties['region'],
    :openstack_endpoint_type => @openstack_properties['endpoint_type'],
    :connection_options => @openstack_properties['connection_options'].merge(@extra_connection_options)
  }

  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 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"])

  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_domain_name => @openstack_properties['domain'],
    :openstack_region => @openstack_properties['region'],
    :openstack_endpoint_type => @openstack_properties['endpoint_type'],
    :connection_options => @openstack_properties['connection_options'].merge(@extra_connection_options)
  }

  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(glance_params)
    end
  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

   = 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



529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/cloud/openstack/cloud.rb', line 529

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

Raises:

  • (Bosh::Clouds:NotSupported)

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



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/cloud/openstack/cloud.rb', line 388

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'] = agent_network_spec(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



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/cloud/openstack/cloud.rb', line 458

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



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/cloud/openstack/cloud.rb', line 416

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.

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



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

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



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

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 = 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
    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)

    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 => keypair.name,
      :security_groups => security_groups,
      :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}'")
    server = with_openstack { @openstack.servers.create(server_params) }

    @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

Raises:

  • (Bosh::Clouds::CloudError)

    if disk is not in available state



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/cloud/openstack/cloud.rb', line 505

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

Raises:

  • (Bosh::Clouds::CloudError)

    if snapshot is not in available state



614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
# File 'lib/cloud/openstack/cloud.rb', line 614

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



187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/cloud/openstack/cloud.rb', line 187

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



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/cloud/openstack/cloud.rb', line 339

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



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# File 'lib/cloud/openstack/cloud.rb', line 553

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



490
491
492
493
494
495
496
497
# File 'lib/cloud/openstack/cloud.rb', line 490

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



360
361
362
363
364
365
# File 'lib/cloud/openstack/cloud.rb', line 360

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



372
373
374
375
376
377
378
379
# File 'lib/cloud/openstack/cloud.rb', line 372

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.



661
662
663
# File 'lib/cloud/openstack/cloud.rb', line 661

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



638
639
640
641
642
643
644
645
646
647
648
649
# File 'lib/cloud/openstack/cloud.rb', line 638

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

Raises:

  • (Bosh::Clouds::CloudError)

    if volume is not found



580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/cloud/openstack/cloud.rb', line 580

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