Class: VCenterDriver::VirtualMachine

Inherits:
Template
  • Object
show all
Includes:
Memoize, VirtualMachineDevice, VirtualMachineHelper, VirtualMachineMonitor
Defined in:
lib/virtual_machine.rb

Overview

Class VirtualMachine

Constant Summary collapse

VM_PREFIX_DEFAULT =

Virtual Machine main Class

'one-$i-'
POLL_ATTRIBUTE =
OpenNebula::VirtualMachine::Driver::POLL_ATTRIBUTE
VM_STATE =
OpenNebula::VirtualMachine::Driver::VM_STATE
DNET_CARD =
RbVmomi::VIM::VirtualEthernetCardDistributedVirtualPortBackingInfo
NET_CARD =
RbVmomi::VIM::VirtualEthernetCardNetworkBackingInfo
OPAQUE_CARD =
RbVmomi::VIM::VirtualEthernetCardOpaqueNetworkBackingInfo
VM_SHUTDOWN_TIMEOUT =

10 minutes til poweroff hard

600

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Memoize

#[], #[]=, #clear, #clear_all

Methods included from VirtualMachineMonitor

#info, #monitor, #reset_monitor, #state_to_c

Methods included from VirtualMachineHelper

#wait_timeout

Methods inherited from Template

#cdrom?, #create_ar, #create_delta_disks, #create_network_for_import, #create_template_copy, #datacenter, #delete_template, #disk?, #disk_or_cdrom?, #disk_or_iso?, #esx_name, #fill_nic, #find_alias_ips_in_network, #find_ip_in_ar, #find_ips_in_network, #get_ipv6_prefix, #get_vcenter_disk_key, get_xml_template, #identify_network, #import_vcenter_disks, #import_vcenter_nics, #lock, #nic_alias_from_nic, #nic_from_network_created, #nic_from_network_found, #online?, #retrieve_from_device, #save_ar_ids, #save_as_linked_clones, template_to_one, #unlock, #vcenter_disks_get, #vcenter_nics_hash, #vcenter_nics_list, #vm?, #vm_template_ds_ref, #vm_to_one

Constructor Details

#initialize(vi_client, ref, one_id) ⇒ VirtualMachine

Returns a new instance of VirtualMachine.



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/virtual_machine.rb', line 104

def initialize(vi_client, ref, one_id)
    if ref
        ref = VCenterDriver::VIHelper.get_deploy_id(ref)
        @item = RbVmomi::VIM::VirtualMachine.new(vi_client.vim, ref)
        check_item(@item, RbVmomi::VIM::VirtualMachine)
    end

    super(@item, vi_client)

    @vi_client = vi_client
    @vm_id     = one_id
    @locking   = true
    @vm_info   = nil
    @disks     = {}
    @nics = { :macs => {} }
end

Instance Attribute Details

#hostObject

The OpenNebula host

Returns:

  • OpenNebula::Host or XMLElement



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/virtual_machine.rb', line 182

def host
    if @host.nil?
        if one_item.nil?
            raise "'one_item' must be previously set to be able to " <<
                  'access the OpenNebula host.'
        end

        host_id = one_item['HISTORY_RECORDS/HISTORY[last()]/HID']
        raise 'No valid host_id found.' if host_id.nil?

        @host = VIHelper.one_item(OpenNebula::Host, host_id)
    end

    @host
end

#itemObject

Returns the value of attribute item.



98
99
100
# File 'lib/virtual_machine.rb', line 98

def item
  @item
end

#one_itemObject

The OpenNebula VM

Returns:

  • OpenNebula::VirtualMachine or XMLElement



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/virtual_machine.rb', line 138

def one_item
    unless @one_item

        if @vm_id == -1
            raise 'VCenterDriver::Virtualmachine: '\
                  'OpenNebula ID is mandatory for this vm!'
        end

        @one_item =
            VIHelper
            .one_item(
                OpenNebula::VirtualMachine,
                @vm_id
            )
    end

    @one_item
end

#target_ds_refObject

Target Datastore VMware reference getter

Returns:



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/virtual_machine.rb', line 200

def target_ds_ref
    if @target_ds_ref.nil?
        if one_item.nil?
            raise "'one_item' must be previously set to be able to " <<
                  'access the target Datastore.'
        end

        target_ds_id = one_item['HISTORY_RECORDS/HISTORY[last()]/DS_ID']
        raise 'No valid target_ds_id found.' if target_ds_id.nil?

        target_ds =
            VCenterDriver::VIHelper
            .one_item(
                OpenNebula::Datastore,
                target_ds_id
            )

        @target_ds_ref = target_ds['TEMPLATE/VCENTER_DS_REF']
    end

    @target_ds_ref
end

#vi_clientObject

Attributes that must be defined when the VM does not exist in vCenter



125
126
127
# File 'lib/virtual_machine.rb', line 125

def vi_client
  @vi_client
end

#vm_idObject

Returns the value of attribute vm_id.



98
99
100
# File 'lib/virtual_machine.rb', line 98

def vm_id
  @vm_id
end

#vm_infoObject

Returns the value of attribute vm_info.



100
101
102
# File 'lib/virtual_machine.rb', line 100

def vm_info
  @vm_info
end

Class Method Details

.get_vm(opts = {}) ⇒ Object

STATIC MEMBERS, ROUTINES AND CONSTRUCTORS



3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
# File 'lib/virtual_machine.rb', line 3380

def self.get_vm(opts = {})
    # try to retrieve machine from name
    if opts[:name]
        matches = opts[:name].match(/^one-(\d*)(-(.*))?$/)
        if matches
            id = matches[1]
            one_vm = VCenterDriver::VIHelper.one_item(
                OpenNebula::VirtualMachine, id, false
            )
        end
    end

    if one_vm.nil?
        one_vm = VCenterDriver::VIHelper
                 .find_by_ref(
                     OpenNebula::VirtualMachinePool,
                     'DEPLOY_ID',
                     opts[:ref],
                     opts[:vc_uuid],
                     opts[:pool]
                 )
    end

    one_vm
end

.migrate_routine(vm_id, src_host, dst_host, hot_ds = false, ds = nil) ⇒ Object

Migrate a VM to another cluster and/or datastore



3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
# File 'lib/virtual_machine.rb', line 3413

def self.migrate_routine(
    vm_id,
    src_host,
    dst_host,
    hot_ds = false,
    ds = nil
)
    one_client = OpenNebula::Client.new
    pool = OpenNebula::HostPool.new(one_client)
    pool.info

    src_id = pool["/HOST_POOL/HOST[NAME='#{src_host}']/ID"].to_i

    return if src_id == 0

    dst_id = pool["/HOST_POOL/HOST[NAME='#{dst_host}']/ID"].to_i

    # different destination ds
    if ds
        ds_pool = OpenNebula::DatastorePool.new(one_client)
        ds_pool.info
        vcenter_ds_red =
            "/DATASTORE_POOL/DATASTORE[ID='#{ds}']" +
                '/TEMPLATE/VCENTER_DS_REF'
        datastore = ds_pool[vcenter_ds_red]
    end

    vi_client = VCenterDriver::VIClient.new_from_host(src_id)

    # required one objects
    vm = OpenNebula::VirtualMachine.new_with_id(vm_id, one_client)
    dst_host = OpenNebula::Host.new_with_id(dst_id, one_client)

    # get info
    vm.info
    dst_host.info

    esx_migration_list = dst_host['/HOST/TEMPLATE/ESX_MIGRATION_LIST']

    # required vcenter objects
    vc_vm = VCenterDriver::VirtualMachine
            .new_without_id(
                vi_client,
                vm['/VM/DEPLOY_ID']
            )

    vc_vm.vm_id = vm_id

    ccr_ref  = dst_host['/HOST/TEMPLATE/VCENTER_CCR_REF']
    vc_host  = VCenterDriver::ClusterComputeResource.new_from_ref(
        ccr_ref, vi_client
    )

    config = { :cluster => vc_host }

    config[:same_host] = src_id == dst_id

    config[:datastore] = datastore if datastore
    if hot_ds
        config[:esx_migration_list] =
            esx_migration_list if esx_migration_list
    else
        config[:esx_migration_list] = 'Selected_by_DRS'
    end

    vc_vm.reference_all_disks
    vc_vm.migrate(config)

    vm.replace({ 'VCENTER_CCR_REF' => ccr_ref })
end

.new_from_clone(vi_client, drv_action, id) ⇒ vcenterdriver::vm

build a vcenterdriver virtual machine from a template this function is used to instantiate vcenter vms

Parameters:

  • vi_client (vi_client)

    the vcenterdriver client that allows the connection

  • drv_action (xmlelement)

    driver_action that contains the info

  • id (int)

    the if of the opennebula virtual machine

Returns:

  • (vcenterdriver::vm)

    the virtual machine



3519
3520
3521
3522
3523
# File 'lib/virtual_machine.rb', line 3519

def self.new_from_clone(vi_client, drv_action, id)
    new(vi_client, nil, id).tap do |vm|
        vm.clone_vm(drv_action)
    end
end

.new_from_ref(vi_client, ref, name, opts = {}) ⇒ vcenterdriver::vm

Try to build the vcenterdriver virtualmachine without any opennebula id or object, this constructor can find inside the opennebula pool until match

Parameters:

  • vi_client (vi_client)

    the vcenterdriver client that allows the connection

  • ref (String)

    vcenter ref to the vm

  • opts (Hash) (defaults to: {})

    object with pairs that could contain multiple option :vc_uuid: give the vcenter uuid directly :name: the vcenter vm name for extract the opennebula id

Returns:

  • (vcenterdriver::vm)

    the virtual machine



3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
# File 'lib/virtual_machine.rb', line 3497

def self.new_from_ref(vi_client, ref, name, opts = {})
    unless opts[:vc_uuid]
        opts[:vc_uuid] = vi_client.vim.serviceContent.about.instanceUuid
    end

    opts[:name] = name
    opts[:ref]  = ref

    one_vm = VCenterDriver::VirtualMachine.get_vm(opts)

    new_one(vi_client, ref, one_vm)
end

.new_one(vi_client, ref, one_item) ⇒ vcenterdriver::vm

build a vcenterdriver virtual machine with the opennebula object linked

Parameters:

  • vi_client (vi_client)

    the vcenterdriver client that allows the connection

  • ref (String)

    vcenter ref to the vm

  • one_item (one::vm)

    xmlelement of opennebula

Returns:

  • (vcenterdriver::vm)

    the virtual machine



3546
3547
3548
3549
3550
3551
3552
3553
3554
# File 'lib/virtual_machine.rb', line 3546

def self.new_one(vi_client, ref, one_item)
    id = one_item['ID'] || one_item['VM/ID'] rescue -1

    new(vi_client, ref, id).tap do |vm|
        if one_item.instance_of?(OpenNebula::VirtualMachine)
            vm.one_item = one_item
        end
    end
end

.new_with_item(vm_item) ⇒ vcenterdriver::vm

build a vcenterdriver virtual machine with the vmware item already linked

Parameters:

  • vm_item

    the vmware VM item that it’s going to be associated

Returns:

  • (vcenterdriver::vm)

    the virtual machine



3531
3532
3533
3534
3535
# File 'lib/virtual_machine.rb', line 3531

def self.new_with_item(vm_item)
    new(nil, nil, -1).tap do |vm|
        vm.item_update(vm_item)
    end
end

.new_without_id(vi_client, ref) ⇒ vcenterdriver::vm

build a vcenterdriver virtual machine without opennebula object link, use id = -1 instead

Parameters:

  • vi_client (vi_client)

    the vcenterdriver client that allows the connection

  • ref (String)

    vcenter ref to the vm

Returns:

  • (vcenterdriver::vm)

    the virtual machine



3564
3565
3566
# File 'lib/virtual_machine.rb', line 3564

def self.new_without_id(vi_client, ref)
    new(vi_client, ref, -1)
end

Instance Method Details

#add_new_scsi(scsi_schema, devices) ⇒ Object



3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
# File 'lib/virtual_machine.rb', line 3074

def add_new_scsi(scsi_schema, devices)
    controller = nil

    if scsi_schema.keys.length >= 4
        raise 'Cannot add a new controller, maximum is 4.'
    end

    scsi_key    = 0
    scsi_number = 0

    if !scsi_schema.keys.empty? && scsi_schema.keys.length < 4
        scsi_key    =
            scsi_schema.keys.max + 1
        scsi_number =
            scsi_schema[scsi_schema.keys.max][:device].busNumber + 1
    end

    controller_device = RbVmomi::VIM::VirtualLsiLogicController(
        :key       => scsi_key,
        :busNumber => scsi_number,
        :sharedBus => :noSharing
    )

    device_config_spec = RbVmomi::VIM::VirtualDeviceConfigSpec(
        :device    => controller_device,
        :operation => :add
    )

    vm_config_spec = RbVmomi::VIM::VirtualMachineConfigSpec(
        :deviceChange => [device_config_spec]
    )

    @item.ReconfigVM_Task(:spec => vm_config_spec).wait_for_completion

    devices.each do |device|
        valid_device =
            device.class == RbVmomi::VIM::VirtualLsiLogicController &&
            device.key == scsi_key
        controller = device.deviceInfo.label if valid_device
    end

    controller
end

#attach_disk(disk) ⇒ Object

Attach DISK to VM (hotplug)



2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
# File 'lib/virtual_machine.rb', line 2465

def attach_disk(disk)
    # Adding a new disk in newer vSphere versions
    # automatically cleans all system snapshots
    # https://github.com/OpenNebula/one/issues/5409
    if snapshots? || one_snapshots?
        error_msg =  'Existing sytem snapshots, cannot change disks. '
        error_msg << 'Please remove all snapshots and try again'
        raise error_msg
    end

    spec_hash     = {}
    device_change = []

    # Extract unmanaged_keys
    unmanaged_keys = disk_keys
    vc_disks = vcenter_disks_get

    # Check if we're dealing with a StoragePod SYSTEM ds
    storpod = disk['VCENTER_DS_REF'].start_with?('group-')

    # Check if disk being attached is already connected to the VM
    raise 'DISK is already connected to VM' if disk_attached_to_vm(
        disk, unmanaged_keys, vc_disks
    )

    # Generate vCenter spec and reconfigure VM
    add_spec = calculate_add_disk_spec(disk)
    device_change << add_spec
    raise 'Could not generate DISK spec' if device_change.empty?

    extra_key   = "opennebula.mdisk.#{disk['DISK_ID']}"
    extra_value = add_spec[:device].key.to_s

    spec_hash[:deviceChange] = device_change
    spec_hash[:extraConfig]  =
        [{ :key => extra_key, :value => extra_value }]
    spec = RbVmomi::VIM.VirtualMachineConfigSpec(spec_hash)

    begin
        if storpod
            # Ask for StorageDRS recommendation
            # to reconfigure VM (AddDisk)
            sm = storagemanager

            # Disk id is -1 as I don't know
            # what disk id is going to be set
            disk_locator = [RbVmomi::VIM.PodDiskLocator(:diskId => -1)]

            # Disk locator is required for AddDisk
            vmpod_hash = {}
            vmpod_hash[:storagePod] = get_ds
            vmpod_hash[:disk] = disk_locator
            vmpod_config =
                RbVmomi::VIM::VmPodConfigForPlacement(
                    vmpod_hash
                )

            # The storage pod selection requires initialize
            spod_hash = {}
            spod_hash[:initialVmConfig] = [vmpod_config]
            spod_select =
                RbVmomi::VIM::StorageDrsPodSelectionSpec(
                    spod_hash
                )
            storage_spec = RbVmomi::VIM.StoragePlacementSpec(
                :type => :reconfigure,
                :podSelectionSpec => spod_select,
                :vm => self['_ref'],
                :configSpec => spec
            )

            # Query a storage placement recommendation
            result = sm
                     .RecommendDatastores(
                         :storageSpec => storage_spec
                     ) rescue nil

            if result.nil?
                raise 'Could not get placement '\
                        'specification for StoragePod'
            end

            if !result.respond_to?(:recommendations) ||
                result.recommendations.empty?
                raise 'Could not get placement '\
                        'specification for StoragePod'
            end

            # Get recommendation key to be applied
            key = result.recommendations.first.key ||= ''

            if key.empty?
                raise 'Missing Datastore recommendation for StoragePod'
            end

            # Apply recommendation
            sm.ApplyStorageDrsRecommendation_Task(
                :key => [key]
            ).wait_for_completion

            # Add the key for the volatile disk to the
            # unmanaged opennebula.disk.id variables
            unit_number    =
                spec_hash[:deviceChange][0][:device]
                .unitNumber
            controller_key =
                spec_hash[:deviceChange][0][:device]
                .controllerKey
            key =
                get_vcenter_disk_key(
                    unit_number,
                    controller_key
                )
            spec_hash = {}
            reference = {}
            reference[:key] =
                "opennebula.disk.#{disk['DISK_ID']}"
            reference[:value] = key.to_s
            spec_hash[:extraConfig] = [reference]
            @item
                .ReconfigVM_Task(
                    :spec => spec_hash
                ).wait_for_completion
        else
            @item
                .ReconfigVM_Task(
                    :spec => spec
                ).wait_for_completion
        end
        # Modify extraConfig if disks has a bad key
        sync_extraconfig_disk(spec_hash)
    rescue StandardError => e
        error = "Cannot attach DISK to VM: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace.join("\n")}"
        end

        raise error
    end
end

#attach_disks_specsObject

try to get specs for new attached disks using disk_each method with :no_exists? condition



2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
# File 'lib/virtual_machine.rb', line 2302

def attach_disks_specs
    attach_disk_array     = []
    extraconfig           = []
    attach_spod_array     = []
    attach_spod_disk_info = {}

    pos = { :ide => 0, :scsi => 0 }
    disks_each(:no_exists?) do |disk|
        disk.one_item['TYPE'] == 'CDROM' ? k = :ide : k = :scsi

        if disk.storpod?
            spec = calculate_add_disk_spec(disk.one_item, pos[k])
            attach_spod_array << spec

            controller_key = spec[:device].controllerKey
            unit_number = spec[:device].unitNumber

            unit_ctrl = "#{controller_key}-#{unit_number}"
            attach_spod_disk_info[unit_ctrl] = disk.id
        else
            aspec = calculate_add_disk_spec(disk.one_item, pos[k])
            extra_key   = "opennebula.mdisk.#{disk.one_item['DISK_ID']}"
            extra_value = aspec[:device].key.to_s

            attach_disk_array << aspec
            extraconfig << { :key => extra_key, :value => extra_value }
        end

        pos[k]+=1
    end

    { :disks => attach_disk_array,
      :spods => attach_spod_array,
      :spod_info => attach_spod_disk_info,
      :extraconfig => extraconfig }
end

#attach_nic(one_nic) ⇒ Object

Add NIC to VM



2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
# File 'lib/virtual_machine.rb', line 2219

def attach_nic(one_nic)
    spec_hash = {}

    begin
        # A new NIC requires a vcenter spec
        attach_nic_array = []
        attach_nic_array << calculate_add_nic_spec(one_nic)
        spec_hash[:deviceChange] =
            attach_nic_array unless attach_nic_array.empty?

        # Reconfigure VM
        spec = RbVmomi::VIM.VirtualMachineConfigSpec(spec_hash)

        @item.ReconfigVM_Task(:spec => spec).wait_for_completion
    rescue StandardError => e
        error = "Cannot attach NIC to VM: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace.join("\n")}"
        end

        raise error
    end
end

#boot_order_update(boot_info) ⇒ Array (vCenterbootClass)

set the boot order of the machine

the template of the virtual machine. example: disk0, nic0

Parameters:

  • boot_info (String)

    boot information stored in

Returns:

  • (Array (vCenterbootClass))

    An array with the vCenter classes



1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
# File 'lib/virtual_machine.rb', line 1627

def boot_order_update(boot_info)
    convert = lambda {|device_str|
        spl = device_str.scan(/^(nic|disk)(\d+$)/).flatten
        raise "#{device_str} is not supported" if spl.empty?

        device = nil
        sync = "sync_#{spl[0]}s"
        (0..1).each do |_i|
            device = send(spl[0], spl[1])
            break if device.exists?

            send(sync)
        end

        device.boot_dev
    }

    boot_order = boot_info.split(',').map {|str| convert.call(str) }

    RbVmomi::VIM.VirtualMachineBootOptions({ :bootOrder => boot_order })
end

#calculate_add_disk_spec(disk, position = 0) ⇒ Object



2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
# File 'lib/virtual_machine.rb', line 2765

def calculate_add_disk_spec(disk, position = 0)
    img_name_escaped = VCenterDriver::FileHelper.get_img_name(
        disk,
        one_item['ID'],
        self['name'],
        instantiated_as_persistent?
    )

    img_name = VCenterDriver::FileHelper.unescape_path(img_name_escaped)

    type     = disk['TYPE']
    size_kb  = disk['SIZE'].to_i * 1024

    if type == 'CDROM'
        # CDROM drive will be found in the IMAGE DS
        ds_ref   = disk['VCENTER_DS_REF']
        ds       = VCenterDriver::Storage.new_from_ref(ds_ref,
                                                       @vi_client)
        ds_name  = ds['name']

        # CDROM can only be added when the VM is in poweroff state
        vmdk_backing = RbVmomi::VIM::VirtualCdromIsoBackingInfo(
            :datastore => ds.item,
            :fileName  => "[#{ds_name}] #{img_name}"
        )

        if @item['summary.runtime.powerState'] != 'poweredOff'
            raise 'The CDROM image can only be added as an IDE device '\
                  'when the VM is in the powered off state'
        end

        controller, unit_number = find_free_ide_controller(position)

        device = RbVmomi::VIM::VirtualCdrom(
            :backing       => vmdk_backing,
            :key           => get_key(type),
            :controllerKey => controller.key,
            :unitNumber    => unit_number,

            :connectable => RbVmomi::VIM::VirtualDeviceConnectInfo(
                :startConnected    => true,
                :connected         => true,
                :allowGuestControl => true
            )
        )

        {
            :operation => :add,
            :device => device
        }

    else
        # TYPE is regular disk (not CDROM)
        # disk_adapter
        disk_adapter = disk['VCENTER_ADAPTER_TYPE']
        case disk_adapter
        when 'ide'
            controller, unit_number = find_free_ide_controller(position)
        else
            controller, unit_number = find_free_controller(position)
        end
        storpod = disk['VCENTER_DS_REF'].start_with?('group-')
        if storpod
            vmdk_backing = RbVmomi::VIM::VirtualDiskFlatVer2BackingInfo(
                :diskMode  => 'persistent',
                :fileName  => ''
            )
        else
            ds = get_effective_ds(disk)
            if ds.item._ref.start_with?('group-')
                ds_object = item.datastore.first
                ds_name   = ds_object.name
            else
                ds_object = ds.item
                ds_name = ds['name']
            end
            vmdk_backing = RbVmomi::VIM::VirtualDiskFlatVer2BackingInfo(
                :datastore => ds_object,
                :diskMode  => 'persistent',
                :fileName  => "[#{ds_name}] #{img_name}"
            )
        end

        device = RbVmomi::VIM::VirtualDisk(
            :backing       => vmdk_backing,
            :capacityInKB  => size_kb,
            :controllerKey => controller.key,
            :key           => get_key(type),
            :unitNumber    => unit_number
        )

        config = {
            :operation => :add,
          :device    => device
        }

        # For StorageDRS vCenter must create the file
        config[:fileOperation] = :create if storpod

        config
    end
end

#calculate_add_nic_spec(nic, unumber = nil) ⇒ Object

Returns an array of actions to be included in :deviceChange



1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
# File 'lib/virtual_machine.rb', line 1902

def calculate_add_nic_spec(nic, unumber = nil)
    mac     = nic['MAC']
    pg_name = nic['BRIDGE']
    default =
        VCenterDriver::VIHelper
        .get_default(
            'VM/TEMPLATE/NIC/MODEL'
        )
    tmodel  = one_item['USER_TEMPLATE/NIC_DEFAULT/MODEL']

    # got the model of the nic, first try to get the model
    # inside the nic, then the model defined by user and
    # last option model by default in vCenter Driver
    model   = nic['MODEL'] || tmodel || default
    raise 'nic model cannot be empty!' if model == ''

    vnet_ref  = nic['VCENTER_NET_REF']
    backing   = nil

    # Maximum bitrate for the interface in kilobytes/second
    # for inbound traffic
    limit_in  =
        nic['INBOUND_PEAK_BW'] ||
            VCenterDriver::VIHelper.get_default(
                'VM/TEMPLATE/NIC/INBOUND_PEAK_BW'
            )
    # Maximum bitrate for the interface in kilobytes/second
    # for outbound traffic
    limit_out =
        nic['OUTBOUND_PEAK_BW'] ||
            VCenterDriver::VIHelper.get_default(
                'VM/TEMPLATE/NIC/OUTBOUND_PEAK_BW'
            )
    limit = nil

    if limit_in && limit_out
        limit=([limit_in.to_i, limit_out.to_i].min / 1024) * 8
    end

    # Average bitrate for the interface in kilobytes/second
    # for inbound traffic
    rsrv_in  =
        nic['INBOUND_AVG_BW'] ||
            VCenterDriver::VIHelper.get_default(
                'VM/TEMPLATE/NIC/INBOUND_AVG_BW'
            )
    # Average bitrate for the interface in kilobytes/second
    # for outbound traffic
    rsrv_out =
        nic['OUTBOUND_AVG_BW'] ||
            VCenterDriver::VIHelper.get_default(
                'VM/TEMPLATE/NIC/OUTBOUND_AVG_BW'
            )
    rsrv = nil

    if rsrv_in || rsrv_out
        rsrv=([rsrv_in.to_i, rsrv_out.to_i].min / 1024) * 8
    end

    # get the network with ref equal to vnet_ref or
    # with name equal to pg_name
    network = self['runtime.host'].network.select do |n|
        n._ref == vnet_ref || n.name == pg_name
    end
    network = network.first

    unless network
        raise "#{pg_name} not found in #{self['runtime.host'].name}"
    end

    # start in one, we want the next avaliable id
    card_num = 1
    @item['config.hardware.device'].each do |dv|
        card_num += 1 if VCenterDriver::Network.nic?(dv)
    end

    nic_card = Nic.nic_model_class(model)

    if network.class == RbVmomi::VIM::Network
        backing = RbVmomi::VIM.VirtualEthernetCardNetworkBackingInfo(
            :deviceName => pg_name,
            :network    => network
        )
    elsif network.class == RbVmomi::VIM::DistributedVirtualPortgroup
        port = RbVmomi::VIM::DistributedVirtualSwitchPortConnection(
            :switchUuid =>
                    network.config.distributedVirtualSwitch.uuid,
            :portgroupKey => network.key
        )
        backing =
            RbVmomi::VIM
            .VirtualEthernetCardDistributedVirtualPortBackingInfo(
                :port => port
            )
    elsif network.class == RbVmomi::VIM::OpaqueNetwork
        backing =
            RbVmomi::VIM
            .VirtualEthernetCardOpaqueNetworkBackingInfo(
                :opaqueNetworkId =>
                    network.summary.opaqueNetworkId,
                :opaqueNetworkType =>
                    'nsx.LogicalSwitch'
            )
    else
        raise 'Unknown network class'
    end

    # grab the last unitNumber to ensure the nic to be added at the end
    if !unumber
        @unic = @unic || vcenter_nics_list.map do |d|
            d.unitNumber
        end.max || 0
        unumber = @unic += 1
    else
        @unic   = unumber
    end

    card_spec = {
        :key => 0,
        :deviceInfo => {
            :label => 'net' + card_num.to_s,
            :summary => pg_name
        },
        :backing     => backing,
        :addressType => mac ? 'manual' : 'generated',
        :macAddress  => mac,
        :unitNumber  => unumber
    }
    if @vi_client.vim.serviceContent.about.apiVersion.to_f >= 7.0
        card_spec[:key] = -100 - card_num.to_i
    end

    if (limit || rsrv) && (limit > 0)
        ra_spec = {}
        rsrv = limit if rsrv > limit
        # The bandwidth limit for the virtual network adapter. The
        # utilization of the virtual network adapter will not exceed
        # this limit, even if there are available resources. To clear
        # the value of this property and revert it to unset, set the
        # vaule to "-1" in an update operation. Units in Mbits/sec
        ra_spec[:limit] = limit if limit
        # Amount of network bandwidth that is guaranteed to the virtual
        # network adapter. If utilization is less than reservation, the
        # resource can be used by other virtual network adapters.
        # Reservation is not allowed to exceed the value of limit if
        # limit is set. Units in Mbits/sec
        ra_spec[:reservation] = rsrv if rsrv
        # Network share. The value is used as a relative weight in
        # competing for shared bandwidth, in case of resource contention
        ra_spec[:share] =
            RbVmomi::VIM.SharesInfo(
                {
                    :level => RbVmomi::VIM.SharesLevel('normal'),
                    :shares => 0
                }
            )
        card_spec[:resourceAllocation] =
            RbVmomi::VIM.VirtualEthernetCardResourceAllocation(
                ra_spec
            )
    end

    {
        :operation => :add,
        :device    => nic_card.new(card_spec)
    }
end

#calculate_add_nic_spec_autogenerate_mac(nic) ⇒ Object

Returns an array of actions to be included in :deviceChange



2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
# File 'lib/virtual_machine.rb', line 2071

def calculate_add_nic_spec_autogenerate_mac(nic)
    pg_name = nic['BRIDGE']

    default =
        VCenterDriver::VIHelper.get_default(
            'VM/TEMPLATE/NIC/MODEL'
        )
    tmodel = one_item['USER_TEMPLATE/NIC_DEFAULT/MODEL']

    model = nic['MODEL'] || tmodel || default

    vnet_ref  = nic['VCENTER_NET_REF']
    backing   = nil

    # Maximum bitrate for the interface in kilobytes/second
    # for inbound traffic
    limit_in  =
        nic['INBOUND_PEAK_BW'] ||
            VCenterDriver::VIHelper.get_default(
                'VM/TEMPLATE/NIC/INBOUND_PEAK_BW'
            )
    # Maximum bitrate for the interface in kilobytes/second
    # for outbound traffic
    limit_out =
        nic['OUTBOUND_PEAK_BW'] ||
            VCenterDriver::VIHelper.get_default(
                'VM/TEMPLATE/NIC/OUTBOUND_PEAK_BW'
            )
    limit = nil

    if limit_in && limit_out
        limit=([limit_in.to_i, limit_out.to_i].min / 1024) * 8
    end

    # Average bitrate for the interface in kilobytes/second
    # for inbound traffic
    rsrv_in  =
        nic['INBOUND_AVG_BW'] ||
            VCenterDriver::VIHelper.get_default(
                'VM/TEMPLATE/NIC/INBOUND_AVG_BW'
            )

    # Average bitrate for the interface in kilobytes/second
    # for outbound traffic
    rsrv_out =
        nic['OUTBOUND_AVG_BW'] ||
            VCenterDriver::VIHelper.get_default(
                'VM/TEMPLATE/NIC/OUTBOUND_AVG_BW'
            )

    rsrv = nil

    if rsrv_in || rsrv_out
        rsrv=([rsrv_in.to_i, rsrv_out.to_i].min / 1024) * 8
    end

    network = self['runtime.host'].network.select do |n|
        n._ref == vnet_ref || n.name == pg_name
    end

    network = network.first

    card_num = 1 # start in one, we want the next available id

    @item['config.hardware.device'].each do |dv|
        card_num += 1 if VCenterDriver::Network.nic?(dv)
    end

    nic_card = Nic.nic_model_class(model)

    if network.class == RbVmomi::VIM::Network
        backing = RbVmomi::VIM.VirtualEthernetCardNetworkBackingInfo(
            :deviceName => pg_name,
            :network    => network
        )
    elsif network.class == RbVmomi::VIM::DistributedVirtualPortgroup
        port = RbVmomi::VIM::DistributedVirtualSwitchPortConnection(
            :switchUuid =>
                    network.config.distributedVirtualSwitch.uuid,
            :portgroupKey => network.key
        )
        backing =
            RbVmomi::VIM
            .VirtualEthernetCardDistributedVirtualPortBackingInfo(
                :port => port
            )
    elsif network.class == RbVmomi::VIM::OpaqueNetwork
        backing =
            RbVmomi::VIM
            .VirtualEthernetCardOpaqueNetworkBackingInfo(
                :opaqueNetworkId => network.summary.opaqueNetworkId,
                :opaqueNetworkType => 'nsx.LogicalSwitch'
            )
    else
        raise 'Unknown network class'
    end

    card_spec = {
        :key => 0,
        :deviceInfo => {
            :label => 'net' + card_num.to_s,
            :summary => pg_name
        },
        :backing     => backing,
        :addressType => 'generated'
    }
    if @vi_client.vim.serviceContent.about.apiVersion.to_f >= 7.0
        card_spec[:key] = -100 - card_num.to_i
    end

    if (limit || rsrv) && (limit > 0)
        ra_spec = {}
        rsrv = limit if rsrv > limit
        # The bandwidth limit for the virtual network adapter. The
        # utilization of the virtual network adapter will not exceed
        # this limit, even if there are available resources. To clear
        # the value of this property and revert it to unset, set the
        # vaule to "-1" in an update operation. Units in Mbits/sec
        ra_spec[:limit] = limit if limit
        # Amount of network bandwidth that is guaranteed to the virtual
        # network adapter. If utilization is less than reservation, the
        # resource can be used by other virtual network adapters.
        # Reservation is not allowed to exceed the value of limit if
        # limit is set. Units in Mbits/sec
        ra_spec[:reservation] = rsrv if rsrv
        # Network share. The value is used as a relative weight in
        # competing for shared bandwidth, in case of resource contention
        ra_spec[:share] =
            RbVmomi::VIM.SharesInfo(
                {
                    :level =>
                        RbVmomi::VIM.SharesLevel(
                            'normal'
                        ),
                    :shares => 0
                }
            )
        card_spec[:resourceAllocation] =
            RbVmomi::VIM.VirtualEthernetCardResourceAllocation(ra_spec)
    end

    {
        :operation => :add,
        :device    => nic_card.new(card_spec)
    }
end

#calculate_disk_move_type(ds, vc_template, use_linked_clones) ⇒ Object

Calculates how to move disk backinggs from the vCenter VM Template moref



840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
# File 'lib/virtual_machine.rb', line 840

def calculate_disk_move_type(ds, vc_template, use_linked_clones)
    # Default disk move type (Full Clone)
    disk_move_type = :moveAllDiskBackingsAndDisallowSharing

    if ds.instance_of?(RbVmomi::VIM::Datastore) &&
        use_linked_clones &&
        use_linked_clones.downcase == 'yes'

        # Check if all disks in template has delta disks
        disks = vc_template.config
                           .hardware
                           .device
                           .grep(RbVmomi::VIM::VirtualDisk)

        disks_no_delta = disks.select do |d|
            d.backing.parent.nil?
        end

        # Can use linked clones if all disks have delta disks
        if disks_no_delta.empty?
            disk_move_type = :moveChildMostDiskBacking
        end
    end

    disk_move_type
end

#clear_tagsObject

Clear extraconfig tags from a vCenter VM



1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
# File 'lib/virtual_machine.rb', line 1700

def clear_tags
    keys_to_remove = extra_config_keys

    spec_hash =
        keys_to_remove.map {|key| { :key => key, :value => '' } }

    spec = RbVmomi::VIM.VirtualMachineConfigSpec(
        :extraConfig => spec_hash
    )
    @item.ReconfigVM_Task(:spec => spec).wait_for_completion
end

#clone_vm(drv_action) ⇒ Object

This function creates a new VM from the driver_action XML and returns the VMware ref

Parameters:

  • drv_action

    XML representing the deploy action

Returns:

  • String vmware ref



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# File 'lib/virtual_machine.rb', line 553

def clone_vm(drv_action)
    vcenter_name = vc_name

    dc = cluster.datacenter

    vcenter_vm_folder = drv_action['USER_TEMPLATE/VCENTER_VM_FOLDER']

    if !vcenter_vm_folder.nil? && !vcenter_vm_folder.empty?
        vcenter_vm_folder =
            vcenter_folder_name(vcenter_vm_folder, drv_action)

        vcenter_vm_folder_object =
            dc.item.find_folder(vcenter_vm_folder)

        if vcenter_vm_folder_object.nil?
            begin
                dc.item.vmFolder.CreateFolder(
                    :name => vcenter_vm_folder
                )
            rescue StandardError => e
                error_message = e.message
                if VCenterDriver::CONFIG[:debug_information]
                    error_message += ' ' + e.backtrace
                end
                raise 'Cannot create Folder in vCenter:'\
                      "#{error_message}"
            end
        end
    end

    vcenter_vm_folder = drv_action['USER_TEMPLATE/VCENTER_VM_FOLDER']

    if !vcenter_vm_folder.nil? && !vcenter_vm_folder.empty?
        vcenter_vm_folder =
            vcenter_folder_name(vcenter_vm_folder, drv_action)

        vcenter_vm_folder_object =
            dc.item.find_folder(vcenter_vm_folder)

        if vcenter_vm_folder_object.nil?
            begin
                vcenter_vm_folder_list = vcenter_vm_folder.split('/')
                folder_root = dc.item.vmFolder

                vcenter_vm_folder_list.each do |folder_name|
                    folder_root = find_or_create_folder(
                        folder_root,
                        folder_name
                    )
                end
            rescue StandardError => e
                error_message = e.message
                if VCenterDriver::CONFIG[:debug_information]
                    error_message += ' ' + e.backtrace
                end

                raise 'Cannot create Folder in vCenter: '\
                      "#{error_message}"
            end
        end
    end

    vc_template_ref = drv_action['USER_TEMPLATE/VCENTER_TEMPLATE_REF']
    vc_template = RbVmomi::VIM::VirtualMachine(@vi_client.vim,
                                               vc_template_ref)

    ds = get_ds

    asking_for_linked_clones =
        drv_action[
            'USER_TEMPLATE/VCENTER_LINKED_CLONES'
        ]
    disk_move_type = calculate_disk_move_type(ds,
                                              vc_template,
                                              asking_for_linked_clones)

    spec_hash = spec_hash_clone(disk_move_type)

    clone_spec = RbVmomi::VIM.VirtualMachineCloneSpec(spec_hash)

    vcenter_vm_folder_object =
        vcenter_folder(
            vcenter_vm_folder,
            vc_template,
            dc
        )

    if ds.instance_of? RbVmomi::VIM::StoragePod
        # VM is cloned using Storage Resource Manager for StoragePods
        begin
            opts = {
                :vc_template => vc_template,
                :vcenter_name => vcenter_name,
                :clone_spec => clone_spec,
                :storpod => ds,
                :vcenter_vm_folder_object => vcenter_vm_folder_object,
                :dc => dc
            }

            vm = storagepod_clonevm_task(opts)
        rescue StandardError => e
            error =
                "Cannot clone VM Template to StoragePod: #{e.message}."

            if VCenterDriver::CONFIG[:debug_information]
                error += "\n\n#{e.backtrace}"
            end

            raise error
        end
    else
        vm = nil
        begin
            vm = vc_template.CloneVM_Task(
                :folder => vcenter_vm_folder_object,
                :name   => vcenter_name,
                :spec   => clone_spec
            ).wait_for_completion
        rescue StandardError => e
            if !e.message.start_with?('DuplicateName')
                raise "Cannot clone VM Template: #{e.message}"
            end

            vm_folder = dc.vm_folder
            vm_folder.fetch!
            vm = vm_folder.items
                          .select {|_k, v| v.item.name == vcenter_name }
                          .values.first.item rescue nil

            raise "Cannot clone VM Template: #{e.message}" unless vm

            # Detach all persistent disks to
            # avoid accidental destruction
            detach_persistent_disks(vm)

            vm.Destroy_Task.wait_for_completion
            vm = vc_template.CloneVM_Task(
                :folder => vcenter_vm_folder_object,
                :name   => vcenter_name,
                :spec   => clone_spec
            ).wait_for_completion
        end
    end

    # @item is populated
    @item = vm

    reference_unmanaged_devices(vc_template_ref)

    self['_ref']
end

#clusterObject

Cached cluster

Returns:

  • ClusterComputeResource



287
288
289
290
291
292
293
294
295
# File 'lib/virtual_machine.rb', line 287

def cluster
    if @cluster.nil?
        ccr_ref = host['TEMPLATE/VCENTER_CCR_REF']
        @cluster = ClusterComputeResource.new_from_ref(ccr_ref,
                                                       vi_client)
    end

    @cluster
end

#convert_to_templateObject

Remove the MAC addresses so they cannot be in conflict with OpenNebula assigned mac addresses. We detach all nics from the VM



2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
# File 'lib/virtual_machine.rb', line 2871

def convert_to_template
    detach_all_nics

    # We attach new NICs where the MAC address is assigned by vCenter
    nic_specs = []
    one_nics = one_item.retrieve_xmlelements('TEMPLATE/NIC')
    one_nics.each do |nic|
        next unless nic['OPENNEBULA_MANAGED'] &&
            nic['OPENNEBULA_MANAGED'].upcase == 'NO'

        nic_specs <<
            calculate_add_nic_spec_autogenerate_mac(
                nic
            )
    end

    # Reconfigure VM to add unmanaged nics
    spec_hash = {}
    spec_hash[:deviceChange] = nic_specs
    spec = RbVmomi::VIM.VirtualMachineConfigSpec(spec_hash)
    @item.ReconfigVM_Task(:spec => spec).wait_for_completion

    # Convert VM to template in vCenter
    mark_as_template

    # Edit the OpenNebula template
    one_client = OpenNebula::Client.new
    template_id = one_item['TEMPLATE/TEMPLATE_ID']
    new_template = OpenNebula::Template.new_with_id(template_id,
                                                    one_client)
    new_template.info

    # unlock VM Template
    new_template.unlock

    # Update the template reference
    new_template.update("VCENTER_TEMPLATE_REF=#{@item._ref}", true)

    # Add vCenter template name
    new_template.update("VCENTER_TEMPLATE_NAME=#{@item.name}", true)
end

#cpu_hot_add_enabled?Boolean

Returns if has cpuHotAddEnabled.

Returns:

  • (Boolean)

    if has cpuHotAddEnabled



502
503
504
505
506
507
508
509
510
511
512
513
514
# File 'lib/virtual_machine.rb', line 502

def cpu_hot_add_enabled?
    one_item.info if one_item.instance_of?(
        OpenNebula::VirtualMachine
    )

    if one_item['USER_TEMPLATE/HOT_RESIZE/CPU_HOT_ADD_ENABLED'].nil?
        return false
    end

    one_item[
        'USER_TEMPLATE/HOT_RESIZE/CPU_HOT_ADD_ENABLED'
    ] == 'YES'
end

#create_snapshot(snap_id, snap_name) ⇒ Object

Create a snapshot for the VM



3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
# File 'lib/virtual_machine.rb', line 3119

def create_snapshot(snap_id, snap_name)
    memory_dumps = true
    memory_dumps = CONFIG[:memory_dumps] \
                             unless CONFIG[:memory_dumps].nil?

    snapshot_hash = {
        :name        => snap_id,
        :description => "OpenNebula Snapshot: #{snap_name}",
        :memory      => memory_dumps,
        :quiesce     => true
    }

    begin
        @item.CreateSnapshot_Task(snapshot_hash).wait_for_completion
    rescue StandardError => e
        error = "Cannot create snapshot for VM: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace.join("\n")}"
        end

        raise error
    end

    snap_id
end

#create_storagedrs_disks(device_change_spod, device_change_spod_ids) ⇒ Object

create storagedrs disks

Parameters:

  • device_change_spod (array)

    add disk spec for every device

  • device_change_spod_ids (object)

    map from unit ctrl to disk_id



1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
# File 'lib/virtual_machine.rb', line 1540

def create_storagedrs_disks(device_change_spod, device_change_spod_ids)
    sm = storagemanager
    disk_locator = []
    extra_config = []

    device_change_spod.each do |device_spec|
        disk_locator <<
            RbVmomi::VIM
            .PodDiskLocator(
                :diskId => device_spec[
                    :device
                ].key
            )
    end

    spec = {}
    spec[:deviceChange] = device_change_spod

    # Disk locator is required for AddDisk
    vmpod_hash = {}
    vmpod_hash[:storagePod] = get_ds
    vmpod_hash[:disk] = disk_locator
    vmpod_config = RbVmomi::VIM::VmPodConfigForPlacement(vmpod_hash)

    # The storage pod selection requires initialize
    spod_hash = {}
    spod_hash[:initialVmConfig] = [vmpod_config]
    spod_select = RbVmomi::VIM::StorageDrsPodSelectionSpec(spod_hash)
    storage_spec = RbVmomi::VIM.StoragePlacementSpec(
        :type => :reconfigure,
        :podSelectionSpec => spod_select,
        :vm => self['_ref'],
        :configSpec => spec
    )

    # Query a storage placement recommendation
    result = sm
             .RecommendDatastores(
                 :storageSpec => storage_spec
             ) rescue nil

    if result.nil?
        raise 'Could not get placement specification for StoragePod'
    end

    if !result.respond_to?(:recommendations) ||
        result.recommendations.empty?
        raise 'Could not get placement specification for StoragePod'
    end

    # Get recommendation key to be applied
    key = result.recommendations.first.key ||= ''

    if key.empty?
        raise 'Missing Datastore recommendation for StoragePod'
    end

    # Apply recommendation
    sm.ApplyStorageDrsRecommendation_Task(
        :key => [key]
    ).wait_for_completion

    # Set references in opennebula.disk elements
    device_change_spod.each do |device_spec|
        unit_number    = device_spec[:device].unitNumber
        controller_key = device_spec[:device].controllerKey
        key            = get_vcenter_disk_key(unit_number,
                                              controller_key)
        disk_id =
            device_change_spod_ids[
                "#{controller_key}-#{unit_number}"
            ]
        reference = {}
        reference[:key]   = "opennebula.disk.#{disk_id}"
        reference[:value] = key.to_s
        extra_config << reference
    end

    extra_config
end

#customization_specObject

Returns Customization or nil.

Returns:

  • Customization or nil



428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/virtual_machine.rb', line 428

def customization_spec
    xpath = 'USER_TEMPLATE/VCENTER_CUSTOMIZATION_SPEC'
    customization_spec = one_item[xpath]

    if customization_spec.nil?
        return
    end

    begin
        custom_spec = vi_client
                      .vim
                      .serviceContent
                      .customizationSpecManager
                      .GetCustomizationSpec(
                          :name => customization_spec
                      )

        unless custom_spec && (spec = custom_spec.spec)
            raise 'Error getting customization spec'
        end

        spec
    rescue StandardError
        raise "Customization spec '#{customization_spec}' not found"
    end
end

#delete_snapshot(snap_id) ⇒ Object

Delete VM snapshot



3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
# File 'lib/virtual_machine.rb', line 3171

def delete_snapshot(snap_id)
    snapshot_list = self['snapshot.rootSnapshotList']
    snapshot = find_snapshot_in_list(snapshot_list, snap_id)

    return unless snapshot

    begin
        delete_snapshot_hash = {
            :_this => snapshot,
            :removeChildren => false
        }
        snapshot
            .RemoveSnapshot_Task(
                delete_snapshot_hash
            ).wait_for_completion
    rescue StandardError => e
        error = "Cannot delete snapshot of VM: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace.join("\n")}"
        end

        raise error
    end
end

#destroyObject



3297
3298
3299
# File 'lib/virtual_machine.rb', line 3297

def destroy
    @item.Destroy_Task.wait_for_completion
end

#destroy_disk(disk) ⇒ Object



2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
# File 'lib/virtual_machine.rb', line 2683

def destroy_disk(disk)
    one_vm = one_item

    # Check if we can detach and delete the non persistent disk:
    # - VM is terminated
    # - The disk is managed by OpenNebula
    detachable= !(one_vm['LCM_STATE'].to_i == 11 && !disk.managed?)
    detachable &&= disk.exists?

    return unless detachable

    detach_disk(disk)

    # Check if we want to keep the non persistent disk
    keep_non_persistent_disks =
        VCenterDriver::CONFIG[:keep_non_persistent_disks]

    return if keep_non_persistent_disks == true

    disk.destroy
    @disks.delete(disk.id.to_s)
end

#detach_all_nicsObject

Detach all nics useful when removing pg and sw so they’re not in use



2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
# File 'lib/virtual_machine.rb', line 2271

def detach_all_nics
    spec_hash = {}
    device_change = []

    nics_each(:exists?) do |nic|
        device_change << {
            :operation => :remove,
            :device => nic.vc_item
        }
    end

    return if device_change.empty?

    # Remove NIC from VM in the ReconfigVM_Task
    spec_hash[:deviceChange] = device_change

    begin
        @item.ReconfigVM_Task(:spec => spec_hash).wait_for_completion
    rescue StandardError => e
        error = "Cannot detach all NICs from VM: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace}"
        end

        raise error
    end
end

#detach_disk(disk) ⇒ Object



2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
# File 'lib/virtual_machine.rb', line 2653

def detach_disk(disk)
    return unless disk.exists?

    if snapshots? || one_snapshots?
        error_message =  'Existing sytem snapshots, cannot change disks'
        error_message << '. Please remove all snapshots and try again'
        raise error_message
    end

    spec_hash = {}
    spec_hash[:extraConfig] = [disk.config(:delete)]
    spec_hash[:deviceChange] = [{
        :operation => :remove,
        :device => disk.device
    }]

    begin
        @item.ReconfigVM_Task(:spec => spec_hash).wait_for_completion
    rescue StandardError => e
        error = "Cannot detach DISK from VM: #{e.message}."
        error += "\nProbably an existing VM snapshot includes that disk"

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace}"
        end

        raise error
    end
end

#detach_disks_specsObject

try to get specs for detached disks using disk_each method with :dechaded? condition



2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
# File 'lib/virtual_machine.rb', line 2341

def detach_disks_specs
    detach_disk_array = []
    extra_config      = []
    keys = disk_keys.invert

    ipool = VCenterDriver::VIHelper.one_pool(OpenNebula::ImagePool)
    disks_each(:detached?) do |d|
        key = d.key.to_s
        source = VCenterDriver::FileHelper.escape_path(d.path)
        persistent =
            VCenterDriver::VIHelper
            .find_persistent_image_by_source(
                source, ipool
            )

        op = { :operation => :remove, :device => d.device }
        if !persistent && d.type != 'CDROM'
            op[:fileOperation] = :destroy
        end
        detach_disk_array << op

        # Remove reference opennebula.disk if exist from vmx and cache
        extra_config << d.config(:delete) if keys[key]
    end

    [detach_disk_array, extra_config]
end

#detach_nic(mac) ⇒ Object

Detach NIC from VM



2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
# File 'lib/virtual_machine.rb', line 2245

def detach_nic(mac)
    spec_hash = {}

    nic = nic(mac) rescue nil

    return if !nic || nic.no_exists?

    # Remove NIC from VM in the ReconfigVM_Task
    spec_hash[:deviceChange] = [
        :operation => :remove,
        :device => nic.vc_item
    ]
    begin
        @item.ReconfigVM_Task(:spec => spec_hash).wait_for_completion
    rescue StandardError => e
        error = "Cannot detach NIC from VM: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace.join("\n")}"
        end

        raise error
    end
end

#detach_persistent_disks(vm) ⇒ Object

Detach persistent disks to avoid incidental destruction



2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
# File 'lib/virtual_machine.rb', line 2608

def detach_persistent_disks(vm)
    spec_hash = {}
    spec_hash[:deviceChange] = []
    ipool = VCenterDriver::VIHelper.one_pool(OpenNebula::ImagePool)
    if ipool.respond_to?(:message)
        raise "Could not get OpenNebula ImagePool: #{ipool.message}"
    end

    vm.config.hardware.device.each do |disk|
        next unless disk_or_cdrom?(disk)

        # Let's try to find if disks is persistent
        source_unescaped = disk.backing.fileName.sub(
            /^\[(.*?)\] /, ''
        ) rescue next
        source = VCenterDriver::FileHelper.escape_path(source_unescaped)

        persistent = VCenterDriver::VIHelper
                     .find_persistent_image_by_source(
                         source, ipool
                     )

        next unless persistent

        spec_hash[:deviceChange] << {
            :operation => :remove,
            :device => disk
        }
    end

    return if spec_hash[:deviceChange].empty?

    begin
        vm.ReconfigVM_Task(:spec => spec_hash).wait_for_completion
    rescue StandardError => e
        error = "Cannot detach all DISKs from VM: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace}"
        end

        raise error
    end
end

#different_key?(change_disk, vc_disk) ⇒ Boolean

Returns:

  • (Boolean)


2369
2370
2371
2372
2373
# File 'lib/virtual_machine.rb', line 2369

def different_key?(change_disk, vc_disk)
    change_disk[:device].controllerKey == vc_disk.controllerKey &&
    change_disk[:device].unitNumber == vc_disk.unitNumber &&
    change_disk[:device].key != vc_disk.key
end

#disk(index, opts = {}) ⇒ Object

Queries for a certain disk

Parameters:

  • index (String | Integer)

    the id of the disk

  • opts (hash (symbol=>boolean)) (defaults to: {})

    :sync : allow you to ignore local class memory



1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
# File 'lib/virtual_machine.rb', line 1224

def disk(index, opts = {})
    index = index.to_s

    return @disks[index] if @disks[index] && opts[:sync].nil?

    one_disk =
        one_item
        .retrieve_xmlelements(
            "TEMPLATE/DISK[DISK_ID='#{index}']"
        ).first rescue nil

    raise "disk #{index} not found" unless one_disk

    opts[:keys].nil? ? keys = disk_keys : keys = opts[:keys]
    if opts[:disks].nil?
        vc_disks = vcenter_disks_get
    else
        vc_disks = opts[:disks]
    end
    vc_disk = query_disk(one_disk, keys, vc_disks)

    if vc_disk
        Disk.new(index.to_i, one_disk, vc_disk)
    else
        Disk.one_disk(index.to_i, one_disk)
    end
end

#disk_attached_to_vm(disk, unmanaged_keys, vc_disks) ⇒ Object

Get vcenter device representing DISK object (hotplug)



2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
# File 'lib/virtual_machine.rb', line 2707

def disk_attached_to_vm(disk, unmanaged_keys, vc_disks)
    img_name = ''
    device_found = nil
    disk_id = disk['DISK_ID']
    unmanaged_key = unmanaged_keys["opennebula.disk.#{disk_id}"]

    img_name_escaped = VCenterDriver::FileHelper.get_img_name(
        disk,
        one_item['ID'],
        self['name'],
        instantiated_as_persistent?
    )

    img_name = VCenterDriver::FileHelper.unescape_path(img_name_escaped)

    vc_disks.each do |d|
        key_matches  = unmanaged_key && d[:key] == unmanaged_key.to_i
        path_matches = (d[:path_wo_ds] == img_name)

        if key_matches || path_matches
            device_found = d
            break
        end
    end

    device_found
end

#disk_keysObject



345
346
347
348
349
350
351
352
353
354
# File 'lib/virtual_machine.rb', line 345

def disk_keys
    unmanaged_keys = {}
    @item.config.extraConfig.each do |val|
        u = val[:key].include?('opennebula.disk')
        m = val[:key].include?('opennebula.mdisk')
        unmanaged_keys[val[:key]] = val[:value] if u || m
    end

    unmanaged_keys
end

#disk_real_path(disk, disk_id) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/virtual_machine.rb', line 162

def disk_real_path(disk, disk_id)
    volatile = disk['TYPE'] == 'fs'

    if volatile
        dir = disk['VCENTER_DS_VOLATILE_DIR'] || 'one-volatile'
        img_path = "#{dir}/#{@vm_id}/one-#{@vm_id}-#{disk_id}.vmdk"
    else
        source = disk['SOURCE'].gsub('%20', ' ')
        folder = File.dirname(source)
        ext    = File.extname(source)
        file   = File.basename(source, ext)

        img_path = "#{folder}/#{file}-#{@vm_id}-#{disk_id}#{ext}"
    end

    img_path
end

#disksHash(String => self.Disk)

gets the representation of the disks

Returns:

  • (Hash(String => self.Disk))

    Hash(String => self.Disk)



955
956
957
958
959
# File 'lib/virtual_machine.rb', line 955

def disks
    return @disks unless @disks.empty?

    info_disks
end

#disks_each(condition) ⇒ Object

iterate over the disks model

see Self.Disk|Resource class to see some methods: :exits?, :one?…

Parameters:

  • condition (Symbol)

    selects disks that matches certain condition

Returns:

  • yield the disk



986
987
988
989
990
991
992
993
994
995
996
997
# File 'lib/virtual_machine.rb', line 986

def disks_each(condition)
    res = []
    disks.each do |_id, disk|
        next unless disk.method(condition).call

        yield disk if block_given?

        res << disk
    end

    res
end

#disks_synced?Boolean

Returns:

  • (Boolean)


999
1000
1001
1002
1003
# File 'lib/virtual_machine.rb', line 999

def disks_synced?
    disks_each(:unsynced?) { return false }

    true
end

#extra_config_keysObject

Get extraconfig tags from a vCenter VM



1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
# File 'lib/virtual_machine.rb', line 1714

def extra_config_keys
    keys_to_remove = []
    @item['config.extraConfig'].each do |extraconfig|
        next unless extraconfig.key.include?('opennebula.disk') ||
        extraconfig.key.include?('opennebula.vm') ||
        extraconfig.key.downcase.include?('remotedisplay')

        keys_to_remove << extraconfig.key
    end
    keys_to_remove
end

#extraconfig_contextObject



1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
# File 'lib/virtual_machine.rb', line 1814

def extraconfig_context
    one_item.info(true)

    context_text = "# Context variables generated by OpenNebula\n"
    one_item.each('TEMPLATE/CONTEXT/*') do |context_element|
        # next if !context_element.text
        context_text += context_element.name + "='" +
                        context_element.text.gsub("'", "\'") + "'\n"
    end

    # token
    token = File.read(File.join(VAR_LOCATION,
                                'vms',
                                one_item['ID'],
                                'token.txt')).chomp rescue nil

    context_text += "ONEGATE_TOKEN='#{token}'\n" if token

    # context_text
    [
        { :key => 'guestinfo.opennebula.context',
          :value => Base64.encode64(context_text) }
    ]
end

#extraconfig_file(file, id) ⇒ Object



1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
# File 'lib/virtual_machine.rb', line 1802

def extraconfig_file(file, id)
    path, name = file.split(':')
    name = name.gsub('\'', '')
    file_content = Base64.encode64(File.read(path))
    file_content.prepend("#{name}\n")

    [
        { :key => "guestinfo.opennebula.file.#{id}",
          :value => file_content }
    ]
end

#extraconfig_vncObject



1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
# File 'lib/virtual_machine.rb', line 1839

def extraconfig_vnc
    if one_item['TEMPLATE/GRAPHICS']
        vnc_port   = one_item['TEMPLATE/GRAPHICS/PORT'] || ''
        vnc_listen = one_item['TEMPLATE/GRAPHICS/LISTEN'] || '0.0.0.0'
        vnc_keymap = one_item['TEMPLATE/GRAPHICS/KEYMAP']

        conf =
            [
                {
                    :key =>
                        'remotedisplay.vnc.enabled',
                    :value =>
                        'TRUE'
                },
                {
                    :key =>
                        'remotedisplay.vnc.port',
                    :value =>
                        vnc_port
                },
                {
                    :key =>
                        'remotedisplay.vnc.ip',
                    :value =>
                        vnc_listen
                }
            ]

        conf +=
            [
                {
                    :key =>
                      'remotedisplay.vnc.keymap',
                    :value =>
                        vnc_keymap
                }
            ] if vnc_keymap

        conf
    else
        []
    end
end

#find_free_controller(position = 0) ⇒ Object



3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
# File 'lib/virtual_machine.rb', line 3020

def find_free_controller(position = 0)
    free_scsi_controllers = []
    scsi_schema           = {}

    used_numbers      = []
    available_numbers = []
    devices           = @item.config.hardware.device

    devices.each do |dev|
        if dev.is_a? RbVmomi::VIM::VirtualSCSIController
            if scsi_schema[dev.key].nil?
                scsi_schema[dev.key] = {}
            end

            used_numbers << dev.scsiCtlrUnitNumber
            scsi_schema[dev.key][:device] = dev
        end

        next if dev.class != RbVmomi::VIM::VirtualDisk

        used_numbers << dev.unitNumber
    end

    15.times do |scsi_id|
        available_numbers <<
            scsi_id if used_numbers.grep(scsi_id).length <= 0
    end

    scsi_schema.keys.each do |controller|
        free_scsi_controllers <<
            scsi_schema[controller][:device].deviceInfo.label
    end

    if !free_scsi_controllers.empty?
        available_controller_label = free_scsi_controllers[0]
    else
        add_new_scsi(scsi_schema, devices)
        return find_free_controller
    end

    controller = nil

    devices.each do |device|
        if device.deviceInfo.label == available_controller_label
            controller = device
            break
        end
    end

    new_unit_number = available_numbers.sort[position]

    [controller, new_unit_number]
end

#find_free_ide_controller(_position = 0) ⇒ Object



2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
# File 'lib/virtual_machine.rb', line 2971

def find_free_ide_controller(_position = 0)
    free_ide_controller = nil
    ide_schema = {}
    devices = @item.config.hardware.device

    devices.each do |dev|
        # Iteration to initialize IDE Controllers
        next unless dev.is_a? RbVmomi::VIM::VirtualIDEController

        if ide_schema[dev.key].nil?
            ide_schema[dev.key] = {}
        end
        ide_schema[dev.key][:device] = dev
        ide_schema[dev.key][:freeUnitNumber] = [0, 1]
    end

    # Iteration to match Disks and Cdroms with its controllers
    devices.each do |dev| # rubocop:disable Style/CombinableLoops
        first_condition = dev.is_a? RbVmomi::VIM::VirtualDisk
        second_condition = dev.is_a? RbVmomi::VIM::VirtualCdrom
        third_condition = ide_schema.key?(dev.controllerKey)

        next unless (first_condition || second_condition) &&
            third_condition

        ide_schema[dev.controllerKey][:freeUnitNumber]
            .delete(
                dev.unitNumber
            )
    end

    ide_schema.keys.each do |controller|
        unless ide_schema[controller][:freeUnitNumber].empty?
            free_ide_controller = ide_schema[controller]
            break
        end
    end

    if !free_ide_controller
        raise 'There are no free IDE controllers ' +
                  'to connect this CDROM device'
    end

    controller = free_ide_controller[:device]
    new_unit_number = free_ide_controller[:freeUnitNumber][0]

    [controller, new_unit_number]
end

#find_or_create_folder(folder_root, name) ⇒ Object

This function permit get a folder by name if exist or create it if not exist



537
538
539
540
541
542
543
544
545
546
# File 'lib/virtual_machine.rb', line 537

def find_or_create_folder(folder_root, name)
    folder_root.childEntity.each do |child|
        if child.instance_of?(RbVmomi::VIM::Folder) &&
            child.name == name
            return child
        end
    end

    folder_root.CreateFolder(:name => name)
end

#find_snapshot_in_list(list, snap_id) ⇒ Object



3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
# File 'lib/virtual_machine.rb', line 3197

def find_snapshot_in_list(list, snap_id)
    list.each do |i|
        return i.snapshot if i.name == snap_id.to_s

        unless i.childSnapshotList.empty?
            snap = find_snapshot_in_list(i.childSnapshotList, snap_id)
            return snap if snap
        end
    end rescue nil

    nil
end

#get_ds(current_ds_ref = nil) ⇒ Object

Returns RbVmomi::VIM::Datastore or nil.

Returns:

  • RbVmomi::VIM::Datastore or nil



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/virtual_machine.rb', line 398

def get_ds(current_ds_ref = nil)
    if !current_ds_ref
        current_ds_id =
            one_item[
                'HISTORY_RECORDS/HISTORY[last()]/DS_ID'
            ]
        current_ds = VCenterDriver::VIHelper.one_item(
            OpenNebula::Datastore, current_ds_id
        )
        current_ds_ref = current_ds['TEMPLATE/VCENTER_DS_REF']
    end

    if current_ds_ref
        dc = cluster.datacenter

        ds_folder = dc.datastore_folder
        ds = ds_folder.get(current_ds_ref)
        ds.item rescue nil

    else
        nil
    end
end

#get_effective_ds(disk) ⇒ Object

where the disk will live under

Returns:

  • VCenterDriver::Datastore datastore



457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/virtual_machine.rb', line 457

def get_effective_ds(disk)
    if disk['PERSISTENT'] == 'YES'
        ds_ref = disk['VCENTER_DS_REF']
    else
        ds_ref = target_ds_ref

        if ds_ref.nil?
            raise 'target_ds_ref must be defined on this object.'
        end
    end

    VCenterDriver::Storage.new_from_ref(ds_ref, vi_client)
end

#get_key(type) ⇒ Object



2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
# File 'lib/virtual_machine.rb', line 2735

def get_key(type)
    @used_keys ||= []

    if type == 'CDROM'
        bound = 'cdrom?'
        key   = 3000
    else
        bound = 'disk?'
        key   = 2000
    end

    used = @used_keys
    @item.config.hardware.device.each do |dev|
        used << dev.key
        next unless send(bound, dev)

        key = dev.key
    end

    loop do
        break unless used.include?(key)

        key+=1
    end

    @used_keys << key

    key
end

#get_vm_id(vm_pool = nil) ⇒ Object

Returns String the vm_id stored in vCenter.

Returns:

  • String the vm_id stored in vCenter



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/virtual_machine.rb', line 316

def get_vm_id(vm_pool = nil)
    if defined?(@vm_id) && @vm_id
        return @vm_id
    end

    vm_ref = self['_ref']
    return unless vm_ref

    vc_uuid = vcenter_instance_uuid

    one_vm =
        VCenterDriver::VIHelper
        .find_by_ref(
            OpenNebula::VirtualMachinePool,
            'DEPLOY_ID',
            vm_ref,
            vc_uuid,
            vm_pool
        )
    return unless one_vm

    @vm_id = one_vm['ID']
    @vm_id
end

#html_console_parametersObject

Get required parameters to use VMware HTML Console SDK To be used with the following SDK: code.vmware.com/web/sdk/2.1.0/html-console



1730
1731
1732
1733
1734
# File 'lib/virtual_machine.rb', line 1730

def html_console_parameters
    ticket = @item.AcquireTicket(:ticketType => 'webmks')
    { :ticket => ticket.ticket, :host => ticket.host,
  :port => ticket.port }
end

#info_disksHash ("String" => self.Disk)

Refresh VcenterDriver machine disks model, does not perform any sync operation!

Returns:

  • (Hash ("String" => self.Disk))

    Model representation of disks



1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
# File 'lib/virtual_machine.rb', line 1149

def info_disks
    @disks = {}

    keys = disk_keys
    vc_disks  = vcenter_disks_get
    one_disks = one_disks_list

    one_disks.each do |one_disk|
        index = one_disk['DISK_ID']

        disk = query_disk(one_disk, keys, vc_disks)

        vc_dev = vc_disks.delete(disk) if disk

        if vc_dev
            @disks[index] = Disk.new(index.to_i, one_disk, vc_dev)
        else
            @disks[index] = Disk.one_disk(index.to_i, one_disk)
        end
    end

    vc_disks.each {|d| @disks[d[:path_wo_ds]] = Disk.vc_disk(d) }

    @disks
end

#info_nicsHash ("String" => self.Nic)

Refresh VcenterDriver machine nics model, does not perform any sync operation!

Returns:

  • (Hash ("String" => self.Nic))

    Model representation of nics



1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
# File 'lib/virtual_machine.rb', line 1091

def info_nics
    keep_mac_on_imported = false
    keep_mac_on_imported = CONFIG[:keep_mac_on_imported] \
                             unless CONFIG[:keep_mac_on_imported].nil?

    @nics = { :macs => {} }

    vc_nics  = vcenter_nics_list
    one_nics = one_nics_get

    one_nics.each do |one_nic|
        index = one_nic['NIC_ID']
        if keep_mac_on_imported && one_nic['MAC_IMPORTED']
            mac = one_nic['MAC_IMPORTED']
        else
            mac = one_nic['MAC']
        end
        vc_dev = query_nic(mac, vc_nics)

        if vc_dev
            @nics[index]      = Nic.new(index.to_i, one_nic, vc_dev)
            @nics[:macs][mac] = index
        else
            @nics[index]      = Nic.one_nic(index.to_i, one_nic)
        end
    end

    vc_nics.each do |d|
        backing = d.backing

        case backing.class.to_s
        when NET_CARD.to_s
            key = backing.network._ref
        when DNET_CARD.to_s
            key = backing.port.portgroupKey
        when OPAQUE_CARD.to_s
            # Select only Opaque Networks
            opaque_networks = @item.network.select do |net|
                net.class == RbVmomi::VIM::OpaqueNetwork
            end
            opaque_network = opaque_networks.find do |opn|
                backing.opaqueNetworkId == opn.summary.opaqueNetworkId
            end
            key = opaque_network._ref
        else
            raise "Unsupported network card type: #{backing.class}"
        end

        @nics["#{key}#{d.key}"] = Nic.vc_nic(d)
    end

    @nics.reject {|k| k == :macs }
end

#instantiated_as_persistent?Boolean

Returns:

  • (Boolean)


2956
2957
2958
2959
2960
2961
2962
2963
# File 'lib/virtual_machine.rb', line 2956

def instantiated_as_persistent?
    begin
        !one_item['TEMPLATE/CLONING_TEMPLATE_ID'].nil?
    rescue StandardError
        # one_item may not be retrieved if deploy_id hasn't been set
        false
    end
end

#item_update(item) ⇒ Object

set the vmware item directly to the vm



158
159
160
# File 'lib/virtual_machine.rb', line 158

def item_update(item)
    @item = item
end

#linked_clonesObject



1025
1026
1027
# File 'lib/virtual_machine.rb', line 1025

def linked_clones
    one_item['USER_TEMPLATE/VCENTER_LINKED_CLONES']
end

#mark_as_templateObject



3301
3302
3303
# File 'lib/virtual_machine.rb', line 3301

def mark_as_template
    @item.MarkAsTemplate
end

#mark_as_virtual_machineObject



3305
3306
3307
3308
3309
# File 'lib/virtual_machine.rb', line 3305

def mark_as_virtual_machine
    @item.MarkAsVirtualMachine(
        :pool => cluster['resourcePool']
    )
end

#memory_hot_add_enabled?Boolean

Returns if has memoryHotAddEnabled.

Returns:

  • (Boolean)

    if has memoryHotAddEnabled



517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/virtual_machine.rb', line 517

def memory_hot_add_enabled?
    one_item.info if one_item.instance_of?(
        OpenNebula::VirtualMachine
    )

    if one_item['USER_TEMPLATE/HOT_RESIZE/MEMORY_HOT_ADD_ENABLED'].nil?
        return false
    end

    one_item[
        'USER_TEMPLATE/HOT_RESIZE/MEMORY_HOT_ADD_ENABLED'
    ] == 'YES'
end

#migrate(config = {}) ⇒ Object



3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
# File 'lib/virtual_machine.rb', line 3210

def migrate(config = {})
    if config.empty?
        raise 'You need at least 1 parameter to perform a migration'
    end

    begin
        # retrieve host from DRS
        one_cluster = config[:cluster]
        resourcepool = one_cluster.item.resourcePool
        datastore    = config[:datastore]

        if datastore
            relocate_spec_params = {
                :folder => @item.parent,
                :datastore => datastore
            }

            unless config[:same_host]
                relocate_spec_params[:pool] = resourcepool
            end

            if config[:esx_migration_list].is_a?(String)
                if config[:esx_migration_list]==''
                    relocate_spec_params[:host] =
                        config[:cluster].item.host.sample
                elsif config[:esx_migration_list]!='Selected_by_DRS'
                    hostnames = config[:esx_migration_list].split(' ')
                    hostname = hostnames.sample
                    host_moref = one_cluster.hostname_to_moref(hostname)
                    relocate_spec_params[:host] = host_moref
                end
            end

            relocate_spec =
                RbVmomi::VIM
                .VirtualMachineRelocateSpec(
                    relocate_spec_params
                )
            @item.RelocateVM_Task(
                :spec => relocate_spec,
                :priority => 'defaultPriority'
            ).wait_for_completion
        else
            migrate_spec_params = {
                :priority => 'defaultPriority'
            }

            unless config[:same_host]
                migrate_spec_params[:pool] = resourcepool
            end

            @item.MigrateVM_Task(
                migrate_spec_params
            ).wait_for_completion
        end
    rescue StandardError => e
        error = "Cannot migrate VM: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace.join("\n")}"
        end

        raise error
    end
end

#new?Boolean

Returns Boolean whether the VM exists in vCenter.

Returns:

  • (Boolean)

    Boolean whether the VM exists in vCenter



301
302
303
# File 'lib/virtual_machine.rb', line 301

def new?
    one_item['DEPLOY_ID'].empty?
end

#nic(index, opts = {}) ⇒ Object

Queries for a certain nic

Parameters:

  • index (String| Integer)

    the id of the nic or the mac

  • opts (hash (symbol=>boolean)) (defaults to: {})

    :sync : allow you to ignore local class memory



1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
# File 'lib/virtual_machine.rb', line 1180

def nic(index, opts = {})
    index = index.to_s
    is_mac = index.match(/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/)

    if is_mac
        mac = index
        index = @nics[:macs][mac]
    end

    return @nics[index] if @nics[index] && opts[:sync].nil?

    if is_mac
        one_nic =
            one_item
            .retrieve_xmlelements(
                "TEMPLATE/NIC[MAC='#{mac}']"
            ).first rescue nil
        index = one_nic['NIC_ID'] if one_nic
    else
        one_nic =
            one_item
            .retrieve_xmlelements(
                "TEMPLATE/NIC[NIC_ID='#{index}']"
            ).first rescue nil
        mac     = one_nic['MAC'] if one_nic
    end

    raise "nic #{index} not found" unless one_nic

    vc_nics = vcenter_nics_list
    vc_nic  = query_nic(mac, vc_nics)

    if vc_nic
        Nic.new(index.to_i, one_nic, vc_nic)
    else
        Nic.one_nic(index.to_i, one_nic)
    end
end

#nicsHash(String => self.Nic)

gets the representation of the nics

Returns:

  • (Hash(String => self.Nic))

    Hash(String => self.Nic)



944
945
946
947
948
949
950
# File 'lib/virtual_machine.rb', line 944

def nics
    if !@nics[:macs].empty?
        return @nics.reject {|k| k == :macs }
    end

    info_nics
end

#nics_each(condition) ⇒ Object

iterate over the nics model

see Self.Nic|Resource class to see some methods: :exits?, :one?…

Parameters:

  • condition (Symbol)

    selects nics that matches certain condition

Returns:

  • yield the nic



967
968
969
970
971
972
973
974
975
976
977
978
# File 'lib/virtual_machine.rb', line 967

def nics_each(condition)
    res = []
    nics.each do |_id, nic|
        next unless nic.method(condition).call

        yield nic if block_given?

        res << nic
    end

    res
end

#one_disks_listObject

Queries to OpenNebula the machine disks xml representation



1014
1015
1016
1017
# File 'lib/virtual_machine.rb', line 1014

def one_disks_list
    one_item.info if one_item.instance_of?(OpenNebula::VirtualMachine)
    one_item.retrieve_xmlelements('TEMPLATE/DISK')
end

#one_exist?Boolean

Returns Boolean wheter the vm exists in OpenNebula.

Returns:

  • (Boolean)

    Boolean wheter the vm exists in OpenNebula



311
312
313
# File 'lib/virtual_machine.rb', line 311

def one_exist?
    !@vm_id.nil? && @vm_id != -1
end

#one_nics_getObject

Queries to OpenNebula the machine nics xml representation



1020
1021
1022
1023
# File 'lib/virtual_machine.rb', line 1020

def one_nics_get
    one_item.info if one_item.instance_of?(OpenNebula::VirtualMachine)
    one_item.retrieve_xmlelements('TEMPLATE/NIC')
end

#one_snapshots?Boolean

Returns:

  • (Boolean)


2947
2948
2949
2950
2951
2952
2953
2954
# File 'lib/virtual_machine.rb', line 2947

def one_snapshots?
    begin
        !one_item['TEMPLATE/SNAPSHOT'].nil?
    rescue StandardError
        # one_item may not be retrieved if deploy_id hasn't been set
        false
    end
end

#powered_off?Boolean

Returns:

  • (Boolean)


3341
3342
3343
# File 'lib/virtual_machine.rb', line 3341

def powered_off?
    @item.runtime.powerState == 'poweredOff'
end

#powered_on?Boolean

Returns:

  • (Boolean)


3337
3338
3339
# File 'lib/virtual_machine.rb', line 3337

def powered_on?
    @item.runtime.powerState == 'poweredOn'
end

#poweroff_hardObject



3345
3346
3347
# File 'lib/virtual_machine.rb', line 3345

def poweroff_hard
    @item.PowerOffVM_Task.wait_for_completion
end

#poweron(set_running = false) ⇒ Object



3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
# File 'lib/virtual_machine.rb', line 3323

def poweron(set_running = false)
    begin
        @item.PowerOnVM_Task.wait_for_completion
    rescue RbVmomi::Fault => e
        error = e.message.split(':').first
        raise e.message if error != 'InvalidPowerState'
    end
    # opennebula.running flag
    set_running(true, true) if set_running

    timeout = CONFIG[:vm_poweron_wait_default]
    wait_timeout(:powered_on?, timeout)
end

#query_disk(one_disk, keys, vc_disks) ⇒ vCenter_disk

perform a query to vCenter asking for the OpenNebula disk

See vcenter_disks_get method

Parameters:

  • one_disk (XMLelement)

    The OpenNebula object representation of the disk

  • keys (Hash (String => String))

    Hashmap with the unmanaged keys

  • vc_disks (Array (vcenter_disks))

    Array of the machine real disks

Returns:

  • (vCenter_disk)

    the proper disk



1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
# File 'lib/virtual_machine.rb', line 1040

def query_disk(one_disk, keys, vc_disks)
    index     = one_disk['DISK_ID']
    unmanaged = "opennebula.disk.#{index}"
    managed   = "opennebula.mdisk.#{index}"

    if keys[managed]
        key  = keys[managed].to_i
    elsif keys[unmanaged]
        key  = keys[unmanaged].to_i
    end

    if key
        query = vc_disks.select {|dev| key == dev[:key] }
    else
        if snapshots?
            error = 'Disk metadata not present and snapshots exist. ' \
                    'Please remove imported VM with "onevm recover ' \
                    '--delete-db".'
            raise error
        end

        # Try to find the disk using the path known by OpenNebula
        source_path = one_disk['SOURCE']
        calculated_path = disk_real_path(one_disk, index)
        query = vc_disks.select do |dev|
            source_path == dev[:path_wo_ds] ||
            calculated_path == dev[:path_wo_ds]
        end
    end

    return if query.size != 1

    query.first
end

#query_nic(mac, vc_nics) ⇒ vCenter_nic

perform a query to vCenter asking for the OpenNebula nic

Parameters:

  • vc_disks (String)

    The mac of the nic

  • vc_disks (Array (vcenter_nic))

    Array of the machine real nics

Returns:

  • (vCenter_nic)

    the proper nic



1081
1082
1083
1084
1085
# File 'lib/virtual_machine.rb', line 1081

def query_nic(mac, vc_nics)
    nic = vc_nics.select {|dev| dev.macAddress == mac }.first

    vc_nics.delete(nic) if nic
end

#rebootObject



3319
3320
3321
# File 'lib/virtual_machine.rb', line 3319

def reboot
    @item.RebootGuest
end

Get a recommendation from a provided storagepod Returns the recommended datastore reference



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
# File 'lib/virtual_machine.rb', line 225

def recommended_ds(ds_ref)
    # Fail if datastore is not a storage pod
    unless ds_ref.start_with?('group-')
        raise 'Cannot recommend from a non storagepod reference'
    end

    # Retrieve information needed to create storage_spec hash
    storage_manager =
        vi_client
        .vim
        .serviceContent
        .storageResourceManager
    vcenter_name = vc_name
    vc_template =
        RbVmomi::VIM::VirtualMachine
        .new(
            vi_client.vim,
            get_template_ref
        )
    dc = cluster.datacenter
    vcenter_vm_folder_object = vcenter_folder(vcenter_folder_ref,
                                              vc_template, dc)
    storpod = get_ds(ds_ref)
    disk_move_type = calculate_disk_move_type(storpod, vc_template,
                                              linked_clones)
    spec_hash = spec_hash_clone(disk_move_type)
    clone_spec = RbVmomi::VIM.VirtualMachineCloneSpec(spec_hash)

    # Create hash needed to get the recommendation
    storage_spec = RbVmomi::VIM.StoragePlacementSpec(
        :type => 'clone',
        :cloneName => vcenter_name,
        :folder => vcenter_vm_folder_object,
        :podSelectionSpec =>
            RbVmomi::VIM
                .StorageDrsPodSelectionSpec(
                    :storagePod => storpod
                ),
        :vm => vc_template,
        :cloneSpec => clone_spec
    )

    # Query a storage placement recommendation
    result = storage_manager
             .RecommendDatastores(
                 :storageSpec => storage_spec
             ) rescue nil
    if result.nil?
        raise 'Could not get placement specification for StoragePod'
    end

    if !result.respond_to?(:recommendations) ||
        result.recommendations.empty?
        raise 'Could not get placement specification for StoragePod'
    end

    # Return recommended DS reference
    result.recommendations.first.action.first.destination._ref
end

#reference_all_disksObject



1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
# File 'lib/virtual_machine.rb', line 1376

def reference_all_disks
    # OpenNebula VM disks saved inside .vmx file in vCenter
    disks_extraconfig_current = {}
    # iterate over all attributes and get the disk information
    # keys for disks are prefixed with
    # opennebula.disk and opennebula.mdisk
    @item.config.extraConfig.each do |elem|
        disks_extraconfig_current[elem.key] =
            elem.value if elem.key.start_with?('opennebula.disk.')
        disks_extraconfig_current[elem.key] =
            elem.value if elem.key.start_with?('opennebula.mdisk.')
    end

    # disks that exist currently in the vCenter Virtual Machine
    disks_vcenter_current = []
    disks_each(:synced?) do |disk|
        begin
            if disk.managed?
                key_prefix = 'opennebula.mdisk.'
            else
                key_prefix = 'opennebula.disk.'
            end
            k = "#{key_prefix}#{disk.id}"
            v = disk.key.to_s

            disks_vcenter_current << { :key => k, :value => v }
        rescue StandardError => _e
            next
        end
    end

    update = false
    # differences in the number of disks
    # between vCenter and OpenNebula VMs
    num_disks_difference =
        disks_extraconfig_current.keys.count -
            disks_vcenter_current.count

    # check if disks are same in vCenter and OpenNebula
    disks_vcenter_current.each do |item|
        # check if vCenter disk have representation in the extraConfig
        # but with a different key, then we have to update
        first_condition =
            disks_extraconfig_current.key? item[:key]
        second_condition =
            disks_extraconfig_current[item[:key]] == item[:value]
        if first_condition && !second_condition
            update = true
        end
        # check if vCenter disk hasn't got
        # a representation in the extraConfig
        # then we have to update
        if !disks_extraconfig_current.key? item[:key]
            update = true
        end
    end

    # new configuration for vCenter .vmx file
    disks_extraconfig_new = {}

    return unless num_disks_difference != 0 || update

    # Step 1: remove disks in the current configuration of .vmx
    # Avoids having an old disk in the configuration
    # that does not really exist
    disks_extraconfig_current.keys.each do |key|
        disks_extraconfig_new[key] = ''
    end

    # Step 2: add current vCenter disks to new configuration
    disks_vcenter_current.each do |item|
        disks_extraconfig_new[item[:key]] = item[:value]
    end

    # Step 3: create extraconfig_new with the values to update
    extraconfig_new = []
    disks_extraconfig_new.keys.each do |key|
        extraconfig_new <<
            {
                :key =>
                    key,
                :value =>
                    disks_extraconfig_new[key]
            }
    end

    # Step 4: update the extraConfig
    spec_hash = { :extraConfig => extraconfig_new }
    spec = RbVmomi::VIM.VirtualMachineConfigSpec(spec_hash)
    @item.ReconfigVM_Task(:spec => spec).wait_for_completion
end

#reference_disks(template_ref, disks, managed) ⇒ Object

Build extraconfig section to reference disks by key and avoid problems with changing paths (mainly due to snapshots) Uses VM Templte if ref available, or the vCenter VM if not (latter case is if we are dealing with a Wild VM



1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
# File 'lib/virtual_machine.rb', line 1473

def reference_disks(template_ref, disks, managed)
    return [] if disks.empty? || instantiated_as_persistent?

    extraconfig = []
    if managed
        key_prefix = 'opennebula.mdisk'
    else
        key_prefix = 'opennebula.disk'
    end

    # Get vcenter VM disks to know real path of cloned disk
    vcenter_disks = vcenter_disks_get

    # Create an array with the paths of the disks in vcenter template
    if !template_ref.nil?
        template = VCenterDriver::Template.new_from_ref(template_ref,
                                                        vi_client)
        template_disks = template.vcenter_disks_get
    else
        # If we are dealing with a Wild VM, we simply use
        # what is available in the vCenter VM
        template_disks = vcenter_disks_get
    end
    template_disks_vector = []
    template_disks.each do |d|
        template_disks_vector << d[:path_wo_ds]
    end

    # Try to find index of disks in template disks
    disks.each do |disk|
        disk_source =
            VCenterDriver::FileHelper
            .unescape_path(
                disk['SOURCE']
            )
        template_disk = template_disks.select do |d|
            d[:path_wo_ds] == disk_source
        end.first

        if template_disk
            vcenter_disk = vcenter_disks.select do |d|
                d[:key] == template_disk[:key]
            end.first
        end

        unless vcenter_disk
            raise "disk with path #{disk_source}"\
                    'not found in the vCenter VM'
        end

        reference = {}
        reference[:key]   = "#{key_prefix}.#{disk['DISK_ID']}"
        reference[:value] = (vcenter_disk[:key]).to_s
        extraconfig << reference
    end

    extraconfig
end

#reference_unmanaged_devices(template_ref, execute = true) ⇒ Object

Matches disks from the vCenter VM Template (or VM if it is coming from a Wild VM) with the disks represented in OpenNebula VM data model (ie, the XML)



1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
# File 'lib/virtual_machine.rb', line 1255

def reference_unmanaged_devices(template_ref, execute = true)
    device_change = []
    spec          = {}

    # Get unmanaged disks in OpenNebula's VM template
    xpath =
        'TEMPLATE/DISK[OPENNEBULA_MANAGED="NO" '\
        'or OPENNEBULA_MANAGED="no"]'
    unmanaged_disks = one_item.retrieve_xmlelements(xpath)

    managed = false
    extraconfig = reference_disks(
        template_ref,
        unmanaged_disks,
        managed
    )

    # Add info for existing nics in template in vm xml
    xpath =
        'TEMPLATE/NIC[OPENNEBULA_MANAGED="NO" '\
        'or OPENNEBULA_MANAGED="no"]'
    unmanaged_nics = one_item.retrieve_xmlelements(xpath)

    # Handle NIC changes (different model and/or set MAC address
    # for unmanaged nics
    begin
        if !unmanaged_nics.empty?
            nics = vcenter_nics_list

            # iterate over nics array and find nic with ref
            # or return nil if not exist
            select_net =lambda {|ref|
                device = nil
                nics.each do |nic|
                    type = nic.backing.class.to_s

                    case type
                    when NET_CARD.to_s
                        nref = nic.backing.network._ref
                    when DNET_CARD.to_s
                        nref = nic.backing.port.portgroupKey
                    when OPAQUE_CARD.to_s
                        # Select only Opaque Networks
                        opaque_networks = @item.network.select do |net|
                            net.class == RbVmomi::VIM::OpaqueNetwork
                        end
                        opaque_network = opaque_networks.find do |opn|
                            nic.backing.opaqueNetworkId ==
                                opn.summary.opaqueNetworkId
                        end
                        nref = opaque_network._ref
                    else
                        raise 'Unsupported network card type: '\
                                "#{nic.backing.class}"
                    end

                    next unless nref == ref

                    device = nic
                    break
                end

                if device
                    nics.delete(device)
                else
                    nil
                end
            }

            # Go over all unmanaged nics in order to sync
            # with vCenter Virtual Machine
            unmanaged_nics.each do |unic|
                vnic      = select_net.call(unic['VCENTER_NET_REF'])
                nic_class = vnic.class if vnic

                if unic['MODEL']
                    new_model = Nic.nic_model_class(unic['MODEL'])
                end

                # if vnic is nil add a new device
                if vnic.nil?
                    device_change << calculate_add_nic_spec(unic)
                # delete actual nic and update the new one.
                elsif new_model && new_model != nic_class
                    device_change << {
                        :device => vnic,
                        :operation => :remove
                    }
                    device_change << calculate_add_nic_spec(
                        unic,
                        vnic.unitNumber
                    )
                else
                    vnic.macAddress = unic['MAC']
                    device_change << {
                        :device => vnic,
                        :operation => :edit
                    }
                end
            end

        end
    rescue StandardError => e
        raise 'There is a problem with your vm NICS, '\
              'make sure that they are working properly. '\
              "Error: #{e.message}"
    end

    # Save in extraconfig the key for unmanaged disks
    if !extraconfig.empty? || !device_change.empty?
        spec[:extraConfig]  = extraconfig unless extraconfig.empty?
        spec[:deviceChange] = device_change unless device_change.empty?

        return spec unless execute

        @item.ReconfigVM_Task(:spec => spec).wait_for_completion
    end

    {}
end

#regenerate_contextObject

Regenerate context when devices are hot plugged (reconfigure)



1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
# File 'lib/virtual_machine.rb', line 1884

def regenerate_context
    spec_hash = { :extraConfig => extraconfig_context }
    spec = RbVmomi::VIM.VirtualMachineConfigSpec(spec_hash)

    begin
        @item.ReconfigVM_Task(:spec => spec).wait_for_completion
    rescue StandardError => e
        error = "Cannot generate VM context info: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace}"
        end

        raise error
    end
end

#remove_all_snapshots(consolidate = true) ⇒ Object



3349
3350
3351
3352
3353
3354
3355
# File 'lib/virtual_machine.rb', line 3349

def remove_all_snapshots(consolidate = true)
    @item
        .RemoveAllSnapshots_Task(
            { :consolidate => consolidate }
        ).wait_for_completion
    info_disks
end

#resetObject



3311
3312
3313
# File 'lib/virtual_machine.rb', line 3311

def reset
    @item.ResetVM_Task.wait_for_completion
end

#resize_disk(disk) ⇒ Object



2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
# File 'lib/virtual_machine.rb', line 2929

def resize_disk(disk)
    if !disk.exists?
        size = disk.size
        sync_disks
        disk = disk(disk.id)
        disk.change_size(size)
    end

    spec = { :deviceChange => [disk.config(:resize)] }

    @item.ReconfigVM_Task(:spec => spec).wait_for_completion
end

#resize_unmanaged_disksObject



2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
# File 'lib/virtual_machine.rb', line 2913

def resize_unmanaged_disks
    spec = { :deviceChange => [] }
    disks_each(:one?) do |d|
        next unless !d.managed? && d.new_size

        spec[:deviceChange] << d.config(:resize)
    end

    return if spec[:deviceChange].empty?

    @item
        .ReconfigVM_Task(
            :spec => spec
        ).wait_for_completion
end

#resource_poolObject

Returns RbVmomi::VIM::ResourcePool.

Returns:

  • RbVmomi::VIM::ResourcePool



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/virtual_machine.rb', line 361

def resource_pool
    req_rp = one_item['VCENTER_RESOURCE_POOL'] ||
            one_item['USER_TEMPLATE/VCENTER_RESOURCE_POOL']

    # Get ref for req_rp
    rp_list    = cluster.get_resource_pool_list
    req_rp_ref = rp_list.select do |rp|
                     rp[:name].downcase == req_rp.downcase
                 end.first[:ref] rescue nil

    if vi_client.rp_confined?
        if req_rp_ref && req_rp_ref != vi_client.rp._ref
            raise 'Available resource pool '\
                  "[#{vi_client.rp.name}] in host"\
                  ' does not match requested resource pool'\
                  " [#{req_rp}]"
        end

        vi_client.rp
    else
        if req_rp_ref
            rps = cluster.resource_pools.select do |r|
                r._ref == req_rp_ref
            end

            if rps.empty?
                raise "No matching resource pool found (#{req_rp})."
            end

            rps.first
        else
            cluster['resourcePool']
        end
    end
end

#revert_snapshot(snap_id) ⇒ Object

Revert to a VM snapshot



3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
# File 'lib/virtual_machine.rb', line 3147

def revert_snapshot(snap_id)
    snapshot_list = self['snapshot.rootSnapshotList']
    snapshot = find_snapshot_in_list(snapshot_list, snap_id)

    return unless snapshot

    begin
        revert_snapshot_hash = { :_this => snapshot }
        snapshot
            .RevertToSnapshot_Task(
                revert_snapshot_hash
            ).wait_for_completion
    rescue StandardError => e
        error = "Cannot revert snapshot of VM: #{e.message}."

        if VCenterDriver::CONFIG[:debug_information]
            error += "\n\n#{e.backtrace.join("\n")}"
        end

        raise error
    end
end

#set_running(state, execute = true) ⇒ Object



3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
# File 'lib/virtual_machine.rb', line 3361

def set_running(state, execute = true)
    state ? value = 'yes' : value = 'no'

    config_array = [
        { :key => 'opennebula.vm.running', :value => value }
    ]

    return config_array unless execute

    spec = RbVmomi::VIM.VirtualMachineConfigSpec(
        { :extraConfig => config_array }
    )

    @item.ReconfigVM_Task(:spec => spec).wait_for_completion
end

#shutdownObject

actions



3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
# File 'lib/virtual_machine.rb', line 3280

def shutdown
    return if powered_off?

    begin
        if vm_tools?
            @item.ShutdownGuest
        else
            poweroff_hard
        end
    rescue RbVmomi::Fault => e
        error = e.message.split(':').first
        raise e.message if error != 'InvalidPowerState'
    end
    timeout = CONFIG[:vm_poweron_wait_default]
    wait_timeout(:powered_off?, timeout)
end

#snapshots?Boolean

Returns:

  • (Boolean)


2942
2943
2944
2945
# File 'lib/virtual_machine.rb', line 2942

def snapshots?
    clear('rootSnapshot')
    self['rootSnapshot'] && !self['rootSnapshot'].empty?
end

#spec_hash_clone(disk_move_type) ⇒ Object

Returns clone parameters spec hash.

Returns:

  • clone parameters spec hash



900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
# File 'lib/virtual_machine.rb', line 900

def spec_hash_clone(disk_move_type)
    # Relocate spec
    relocate_spec_params = {}

    relocate_spec_params[:pool] = resource_pool
    relocate_spec_params[:diskMoveType] = disk_move_type

    ds = get_ds

    relocate_spec_params[:datastore] =
        ds if ds.instance_of? RbVmomi::VIM::Datastore

    relocate_spec = RbVmomi::VIM.VirtualMachineRelocateSpec(
        relocate_spec_params
    )

    # Running flag - prevents spurious poweroff states in the VM
    running_flag = [{ :key => 'opennebula.vm.running', :value => 'no' }]

    running_flag_spec = RbVmomi::VIM.VirtualMachineConfigSpec(
        { :extraConfig => running_flag }
    )

    clone_parameters = {
        :location => relocate_spec,
        :powerOn  => false,
        :template => false,
        :config   => running_flag_spec
    }

    cs = customization_spec
    clone_parameters[:customization] = cs if cs

    clone_parameters
end

#storagemanagerObject

StorageResouceManager reference



423
424
425
# File 'lib/virtual_machine.rb', line 423

def storagemanager
    self['_connection.serviceContent.storageResourceManager']
end

#storagepod_clonevm_task(opts) ⇒ Object

This function clone a VM Template to StoragePod opts =

:vc_template => vc_template,
:vcenter_name => vcenter_name,
:clone_spec => clone_spec,
:storpod => ds,
:vcenter_vm_folder_object => vcenter_vm_folder_object,
:dc => dc

Parameters:

  • opts

    HASH with all parameters need it to clone



716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'lib/virtual_machine.rb', line 716

def storagepod_clonevm_task(opts)
    vc_template = opts[:vc_template]
    vcenter_name = opts[:vcenter_name]
    clone_spec = opts[:clone_spec]
    storpod = opts[:storpod]
    vcenter_vm_folder_object = opts[:vcenter_vm_folder_object]
    dc = opts[:dc]

    storage_manager =
        vc_template
        ._connection
        .serviceContent
        .storageResourceManager

    storage_spec = RbVmomi::VIM.StoragePlacementSpec(
        :type => 'clone',
        :cloneName => vcenter_name,
        :folder => vcenter_vm_folder_object,
        :podSelectionSpec =>
            RbVmomi::VIM
                .StorageDrsPodSelectionSpec(
                    :storagePod => storpod
                ),
        :vm => vc_template,
        :cloneSpec => clone_spec
    )

    # Query a storage placement recommendation
    result = storage_manager
             .RecommendDatastores(
                 :storageSpec => storage_spec
             ) rescue nil

    if result.nil?
        raise 'Could not get placement specification for StoragePod'
    end

    if !result
       .respond_to?(
           :recommendations
       ) || result.recommendations.empty?
        raise 'Could not get placement specification for StoragePod'
    end

    # Get recommendation key to be applied
    key = result.recommendations.first.key ||= ''
    if key.empty?
        raise 'Missing Datastore recommendation for StoragePod'
    end

    begin
        apply_sr = storage_manager
                   .ApplyStorageDrsRecommendation_Task(:key => [key])
                   .wait_for_completion
        apply_sr.vm
    rescue StandardError => e
        if !e.message.start_with?('DuplicateName')
            raise 'Cannot clone VM Template: '\
                  "#{e.message}\n#{e.backtrace}"
        end

        # The VM already exists, try to find the vm
        vm_folder = dc.vm_folder
        vm_folder.fetch!
        vm = vm_folder.items
                      .select {|_k, v| v.item.name == vcenter_name }
                      .values.first.item rescue nil

        if vm

            begin
                # Detach all persistent disks to
                # avoid accidental destruction
                detach_persistent_disks(vm)

                # Destroy the VM with any disks still attached to it
                vm.Destroy_Task.wait_for_completion

                # Query a storage placement recommendation
                result =
                    storage_manager
                    .RecommendDatastores(
                        :storageSpec => storage_spec
                    ) rescue nil

                if result.nil?
                    raise 'Could not get placement specification '\
                          'for StoragePod'
                end

                if !result
                   .respond_to?(
                       :recommendations
                   ) ||
                    result
                   .recommendations.empty?
                    raise 'Could not get placement '\
                          'specification for StoragePod'
                end

                # Get recommendation key to be applied
                key = result.recommendations.first.key ||= ''
                if key.empty?
                    raise 'Missing Datastore recommendation '\
                          ' for StoragePod'
                end

                apply_sr =
                    storage_manager
                    .ApplyStorageDrsRecommendation_Task(
                        :key => [key]
                    )
                    .wait_for_completion
                apply_sr.vm
            rescue StandardError => e
                raise 'Failure applying recommendation while '\
                      "cloning VM: #{e.message}"
            end
        end
    end
end

#suspendObject



3315
3316
3317
# File 'lib/virtual_machine.rb', line 3315

def suspend
    @item.SuspendVM_Task.wait_for_completion
end

#sync(deploy = {}) ⇒ Object

Synchronize the OpenNebula VM representation with vCenter VM

if the device exists in vCenter and not in OpenNebula : detach if the device exists in OpenNebula and not in vCenter : attach if the device exists in both : noop



1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
# File 'lib/virtual_machine.rb', line 1742

def sync(deploy = {})
    extraconfig   = []
    device_change = []
    sync_opt = nil

    # Disk are only synced with :all option when VM is first created
    # NOTE: Detach actions are implemented through TM (not sync)
    sync_opt = :all if deploy[:new] == true

    disks = sync_disks(sync_opt, false)
    resize_unmanaged_disks

    if deploy[:boot] && !deploy[:boot].empty?
        boot_opts = boot_order_update(deploy[:boot])
    end

    # changes from sync_disks
    device_change += disks[:deviceChange] if disks[:deviceChange]
    extraconfig   += disks[:extraConfig]  if disks[:extraConfig]

    # get token and context
    extraconfig += extraconfig_context

    # get file_ds
    if (files = one_item['TEMPLATE/CONTEXT/FILES_DS'])
        file_id = 0
        files.split(' ').each do |file|
            extraconfig += extraconfig_file(file, file_id)
            file_id += 1
        end
    end

    # vnc configuration (for config_array hash)
    extraconfig += extraconfig_vnc

    # device_change hash (nics)
    device_change += sync_nics(:all, false)

    # Set CPU, memory and extraconfig
    num_cpus = one_item['TEMPLATE/VCPU'] || 1
    spec_hash = {
        :numCPUs      => num_cpus.to_i,
        :memoryMB     => one_item['TEMPLATE/MEMORY'],
        :extraConfig  => extraconfig,
        :deviceChange => device_change
    }
    num_cores = one_item['TEMPLATE/TOPOLOGY/CORES'] || num_cpus.to_i
    if num_cpus.to_i % num_cores.to_i != 0
        num_cores = num_cpus.to_i
    end
    spec_hash[:numCoresPerSocket] = num_cores.to_i

    spec_hash[:bootOptions] = boot_opts if boot_opts

    spec = RbVmomi::VIM.VirtualMachineConfigSpec(spec_hash)

    @item.ReconfigVM_Task(:spec => spec).wait_for_completion
    sync_extraconfig_disk(spec_hash)
end

#sync_disks(option = :nil, execute = true) ⇒ Object

sync OpenNebula disk model with vCenter

method will try to sync all the disks (detached and not existing ones) otherwise it will only sync the disks that are not existing

is going to be executed

Parameters:

  • option (symbol) (defaults to: :nil)

    if :all is provided the

  • execute (boolean) (defaults to: true)

    indicates if the reconfigure operation



2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
# File 'lib/virtual_machine.rb', line 2426

def sync_disks(option = :nil, execute = true)
    info_disks

    spec_hash = {}

    if option == :all
        detach_op = {}
        detach_op[:deviceChange], detach_op[:extraConfig] =
            detach_disks_specs
        perform =
            !detach_op[:deviceChange].empty? ||
                !detach_op[:extraConfig].empty?
        @item
            .ReconfigVM_Task(
                :spec => detach_op
            ).wait_for_completion if perform
    end

    a_specs = attach_disks_specs

    if !a_specs[:spods].empty?
        spec_hash[:extraConfig] =
            create_storagedrs_disks(a_specs[:spods],
                                    a_specs[:spod_info])
    end

    if !a_specs[:disks].empty?
        spec_hash[:deviceChange] = a_specs[:disks]
        spec_hash[:extraConfig]  = a_specs[:extraconfig]
    end

    return spec_hash unless execute

    spec = RbVmomi::VIM.VirtualMachineConfigSpec(spec_hash)
    @item.ReconfigVM_Task(:spec => spec).wait_for_completion
    info_disks
end

#sync_extraconfig_disk(spec_hash) ⇒ Object



2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
# File 'lib/virtual_machine.rb', line 2375

def sync_extraconfig_disk(spec_hash)
    return if spec_hash[:deviceChange].empty?

    extraconfig_new = []
    # vCenter mob disks
    vc_disks = @item['config.hardware.device'].select do |vc_device|
        disk?(vc_device)
    end
    return unless vc_disks

    # For each changed disk, compare with vcenter mob disk
    spec_hash[:deviceChange].each_with_index do |_device, index|
        change_disk = spec_hash[:deviceChange][index]
        vc_disks.each do |vc_disk|
            next unless different_key?(change_disk, vc_disk)

            extraconfig_new <<
                {
                    :key =>
                        spec_hash[:extraConfig][index][:key],
                  :value =>
                        vc_disk.key.to_s
                }
        end
    end

    return if extraconfig_new.empty?

    spec_hash = {
        :extraConfig => extraconfig_new
    }
    spec =
        RbVmomi::VIM
        .VirtualMachineConfigSpec(
            spec_hash
        )
    @item.ReconfigVM_Task(
        :spec => spec
    ).wait_for_completion
end

#sync_nics(option = :none, execute = true) ⇒ Object

sync OpenNebula nic model with vCenter

the method will try to sync all the nics (detached and not existing ones) otherwise it will only sync the nics that are not existing

if the reconfigure operation is going to be executed

Parameters:

  • option (symbol) (defaults to: :none)

    if :all is provided

  • execute (boolean) (defaults to: true)

    indicates



1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
# File 'lib/virtual_machine.rb', line 1660

def sync_nics(option = :none, execute = true)
    device_change = []

    if option == :all
        dchange = []

        # detached? condition indicates that
        # the nic exists in OpeNebula but not
        # in vCenter
        nics_each(:detached?) do |nic|
            dchange << {
                :operation => :remove,
                :device    => nic.vc_item
            }
        end
        if !dchange.empty?
            dspec_hash = { :deviceChange => dchange }
            dspec = RbVmomi::VIM.VirtualMachineConfigSpec(dspec_hash)
            @item.ReconfigVM_Task(:spec => dspec).wait_for_completion
        end
    end

    # no_exits? condition indicates that
    # the nic does not exist in vCenter
    nics_each(:no_exists?) do |nic|
        device_change << calculate_add_nic_spec(nic.one_item)
    end

    return device_change unless execute

    spec_hash = { :deviceChange => device_change }

    spec = RbVmomi::VIM.VirtualMachineConfigSpec(spec_hash)
    @item.ReconfigVM_Task(:spec => spec).wait_for_completion

    info_nics
end

#template_ref_getObject



1005
1006
1007
# File 'lib/virtual_machine.rb', line 1005

def template_ref_get
    one_item['USER_TEMPLATE/VCENTER_TEMPLATE_REF']
end

#use_linked_clone?Boolean

Returns:

  • (Boolean)


2965
2966
2967
2968
2969
# File 'lib/virtual_machine.rb', line 2965

def use_linked_clone?
    one_item['USER_TEMPLATE/VCENTER_LINKED_CLONES'] &&
        one_item['USER_TEMPLATE/VCENTER_LINKED_CLONES']
            .upcase == 'YES'
end

#vc_nameObject

Returns String vcenter name.

Returns:

  • String vcenter name



472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# File 'lib/virtual_machine.rb', line 472

def vc_name
    vm_prefix = host['TEMPLATE/VM_PREFIX']
    vm_prefix = VM_PREFIX_DEFAULT if vm_prefix.nil?

    if !one_item['USER_TEMPLATE/VM_PREFIX'].nil?
        vm_prefix = one_item['USER_TEMPLATE/VM_PREFIX']
    end
    vm_prefix.gsub!('$i', one_item['ID'])

    vm_suffix = ''
    if !one_item['USER_TEMPLATE/VM_SUFFIX'].nil?
        vm_suffix = one_item['USER_TEMPLATE/VM_SUFFIX']
    end
    vm_suffix.gsub!('$i', one_item['ID'])

    vm_prefix + one_item['NAME'] + vm_suffix
end

#vcenter_folder(vcenter_vm_folder, vc_template, dc) ⇒ Object

Get vcenter folder object from the reference If folder is not found, the folder of the vCenter VM Template is returned



881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
# File 'lib/virtual_machine.rb', line 881

def vcenter_folder(vcenter_vm_folder, vc_template, dc)
    vcenter_vm_folder_object = nil

    if !vcenter_vm_folder.nil? && !vcenter_vm_folder.empty?
        vcenter_vm_folder_object =
            dc
            .item
            .find_folder(
                vcenter_vm_folder
            )
    end

    vcenter_vm_folder_object =
        vc_template
        .parent if vcenter_vm_folder_object.nil?
    vcenter_vm_folder_object
end

#vcenter_folder_name(vm_folder_name, drv_action) ⇒ Object

Returns String vcenter folder name.

Returns:

  • String vcenter folder name



868
869
870
871
872
873
874
875
876
# File 'lib/virtual_machine.rb', line 868

def vcenter_folder_name(vm_folder_name, drv_action)
    uname = drv_action['UNAME']
    gname = drv_action['GNAME']

    vm_folder_name.gsub!('$uname', uname)
    vm_folder_name.gsub!('$gname', gname)

    vm_folder_name
end

#vcenter_folder_refObject



1009
1010
1011
# File 'lib/virtual_machine.rb', line 1009

def vcenter_folder_ref
    one_item['USER_TEMPLATE/VCENTER_VM_FOLDER']
end

#vcenter_instance_uuidObject



341
342
343
# File 'lib/virtual_machine.rb', line 341

def vcenter_instance_uuid
    @vi_client.vim.serviceContent.about.instanceUuid
end

#vcenter_tagsObject

Returns vCenter Tags.

Returns:

  • vCenter Tags



491
492
493
494
# File 'lib/virtual_machine.rb', line 491

def vcenter_tags
    one_item.info if one_item.instance_of?(OpenNebula::VirtualMachine)
    one_item.retrieve_xmlelements('USER_TEMPLATE/VCENTER_TAG')
end

#vcenter_tags?Boolean

Returns if has vCenter Tags.

Returns:

  • (Boolean)

    if has vCenter Tags



497
498
499
# File 'lib/virtual_machine.rb', line 497

def vcenter_tags?
    !vcenter_tags.empty?
end

#vm_tools?Boolean

Returns:

  • (Boolean)


3357
3358
3359
# File 'lib/virtual_machine.rb', line 3357

def vm_tools?
    @item.guest.toolsRunningStatus == 'guestToolsRunning'
end

#wild?Boolean

Returns:

  • (Boolean)


305
306
307
308
# File 'lib/virtual_machine.rb', line 305

def wild?
    !(one_item['TEMPLATE/IMPORTED'] &&
        one_item['TEMPLATE/IMPORTED'] == 'YES').nil?
end