Class: OpenNebula::VirtualMachine

Inherits:
Object
  • Object
show all
Defined in:
service/objects/vm.rb

Overview

OpenNebula::VirtualMachine class

Defined Under Namespace

Classes: ShowbackError

Constant Summary collapse

SCHEDULABLE_ACTIONS =

Actions supported by OpenNebula scheduler

%w(
    terminate
    terminate-hard
    hold
    release
    stop
    suspend
    resume
    reboot
    reboot-hard
    poweroff
    poweroff-hard
    undeploy
    undeploy-hard
    snapshot-create
)

Instance Method Summary collapse

Instance Method Details

#calculate_showback(stime_req, etime_req, group_by_day = false) ⇒ Hash

Calculates VMs Showback

Parameters:

  • stime_req (Integer)
    • Point from which calculation starts(timestamp)
  • etime_req (Integer)
    • Point at which calculation stops(timestamp)
  • group_by_day (Boolean) (defaults to: false)
    • Groups showbacks by days

Returns:



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'service/objects/vm.rb', line 342

def calculate_showback stime_req, etime_req, group_by_day = false
    raise ShowbackError, ["Wrong Time-period given", stime_req, etime_req] if stime_req >= etime_req
    
    info!

    stime, etime = stime_req, etime_req

    raise ShowbackError, ["VM didn't exist in given time-period", etime, self['/VM/STIME'].to_i] if self['/VM/STIME'].to_i > etime

    stime = self['/VM/STIME'].to_i if self['/VM/STIME'].to_i > stime
    etime = self['/VM/ETIME'].to_i if self['/VM/ETIME'].to_i < etime && self['/VM/ETIME'].to_i != 0

    requested_time = (etime - stime) / 3600.0

    public_ip = 0
    nic = to_hash['VM']['TEMPLATE']['NIC']
    if nic.class == Array then
        nic.each do | el |
            vnet = VirtualNetwork.new_with_id el['NETWORK_ID'], @client
            vnet.info!
            public_ip += vnet['/VNET/TEMPLATE/TYPE'] == 'PUBLIC' ? 1 : 0
        end
    elsif nic.class == Hash 
        vnet = VirtualNetwork.new_with_id nic['NETWORK_ID'], @client
        vnet.info!
        public_ip += vnet['/VNET/TEMPLATE/TYPE'] == 'PUBLIC' ? 1 : 0
    end
    public_ip_cost = public_ip * requested_time * self['/VM/USER_TEMPLATE/PUBLIC_IP_COST'].to_f
    
    ### Quick response for HOLD and PENDING vms ###
    return {
        "work_time" => 0,
        "time_period_requested" => etime_req - stime_req,
        "time_period_corrected" => etime - stime,
        "CPU" => 0,
        "MEMORY" => 0,
        "DISK" => 0,
        "DISK_TYPE" => self['/VM/USER_TEMPLATE/DRIVE'],
        "PUBLIC_IP" => public_ip_cost,
        "EXCEPTION" => "State #{state == 0 ? "HOLD" : "PENDING"}",
        "TOTAL" => public_ip_cost
    } if state == 0 || state == 1

    records = OpenNebula::Records.new(id).records

    ### Generating Timeline ###
    timeline = []
    records.each_with_index do | record, i |
        timeline << {
            'stime' => record[:time],
            'etime' => i + 1 != records.size ? records[i + 1][:time] - 1 : etime,
            'state' => record[:state]
        }
    end

    timeline.delete_if { |r| (r['etime'] < stime) || (r['stime'] > etime)   }
    raise OpenNebula::Records::NoRecordsError if timeline.empty?
    timeline[0]['stime'] = stime if timeline[0]['stime'] < stime
    timeline[timeline.size - 1]['etime'] = etime if timeline.last['etime'] > etime


    ### Calculating Capacity ###
    cpu     = self['/VM/TEMPLATE/VCPU'].to_f * self['/VM/TEMPLATE/CPU'].to_f
    memory  = self['/VM/TEMPLATE/MEMORY'].to_f / 1024
    disk    = self['/VM/TEMPLATE/DISK/SIZE'].to_f / 1024

    ### Calculating Showback ###
    cpu_cost        = cpu       * self['/VM/TEMPLATE/CPU_COST'].to_f
    memory_cost     = memory    * self['/VM/TEMPLATE/MEMORY_COST'].to_f
    disk_cost       = disk      * self['/VM/TEMPLATE/DISK_COST'].to_f
    public_ip_cost  = public_ip * self['/VM/USER_TEMPLATE/PUBLIC_IP_COST'].to_f

    unless group_by_day then
        ### Calculating Work Time ###
        work_time = 0
        timeline.each do | record |
            next unless record['state'] == 'on'
            work_time += record['etime'] - record['stime']
        end
        work_time = work_time / 3600.0

        

        ### Calculating Showback ###
        cpu_cost        *= work_time     
        memory_cost     *= work_time     
        disk_cost       *= requested_time
        public_ip_cost  *= requested_time

        return {
            "work_time" => work_time,
            "time_period_requested" => etime_req - stime_req,
            "time_period_corrected" => etime - stime,
            "CPU" => cpu_cost,
            "MEMORY" => memory_cost,
            "DISK" => disk_cost,
            "DISK_TYPE" => self['/VM/USER_TEMPLATE/DRIVE'],
            "PUBLIC_IP" => public_ip_cost,
            "TOTAL" => cpu_cost + memory_cost + disk_cost + public_ip_cost
        }
    else
        timeline.clone.each_with_index do | r, i |
            diff = (Time.at(r['etime']).to_date - Time.at(r['stime']).to_date).to_i
            if diff >= 1 then
                result, border = [], Time.at(r['stime']).to_a
                border[0..2] = 59, 59, 23
                border = Time.local(*border).to_i

                result << { 'stime' => r['stime'], 'etime' => border, 'state' => r['state'], 'date' => Time.at(r['stime']).to_a[3..4].join('/') }

                (diff).times do | day |
                    result << { 'stime' => border += 1, 'date' => Time.at(border).to_a[3..4].join('/'), 'etime' => border += 86399, 'state' => r['state'] }
                end

                result[diff]['etime'] = r['etime']
                
                timeline[i] = result
            else
                timeline[i]['date'] = Time.at(r['stime']).to_a[3..4].join('/')
            end
        end
        timeline.flatten!

        timeline.map! do | r |
            {
                "date" => r['date'],
                "requested_time" => (r['etime'] - r['stime']),
                'state' => r['state']
            }
        end
        timeline = timeline.group_by { | r | r['date'] }
        timeline = timeline.map do | date, date_records |
            result = date_records.inject({
                'date' => date,
                'work_time' => 0,
                'requested_time' => 0,
                'CPU' => 0,
                'MEMORY' => 0,
                'DISK' => 0,
                'PUBLIC_IP' => 0,
                'TOTAL' => 0
            }) do | showback, record |
                requested_time = record['requested_time'] / 3600.0
                work_time = record['state'] == 'on' ? requested_time : 0
                showback['work_time'] += work_time
                showback['requested_time'] += record['requested_time']
                showback['CPU'] += cpu_cost * work_time
                showback['MEMORY'] += memory_cost * work_time
                showback['DISK'] +=  disk_cost * requested_time if record['state'] != 'pnd'
                showback['PUBLIC_IP'] += public_ip_cost * requested_time
                
                showback
            end

            result['TOTAL'] += (result['CPU'] + result['MEMORY'] + result['DISK'] + result['PUBLIC_IP'])
            result
        end

        return {
            "work_time" => timeline.inject(0){|total, record| total + record['work_time']},
            "requested_time" => timeline.inject(0){|total, record| total + record['requested_time']},
            "time_period_requested" => etime_req - stime_req,
            "time_period_corrected" => etime - stime,
            "showback" => timeline,
            "DISK_TYPE" => self['/VM/USER_TEMPLATE/DRIVE'],
            "TOTAL" => timeline.inject(0){|total, record| total + record['TOTAL']}
        }

    end
rescue OpenNebula::Records::NoRecordsError
    return {
        "work_time" => 0,
        "time_period_requested" => etime_req - stime_req,
        "time_period_corrected" => etime - stime,
        "CPU" => 0,
        "MEMORY" => 0,
        "DISK" => 0,
        "DISK_TYPE" => 'no_type',
        "PUBLIC_IP" => 0,
        "EXCEPTION" => "No Records",
        "TOTAL" => 0
    }
end

#generate_schedule_str(id, action, time) ⇒ Object

Generates template for OpenNebula scheduler record



21
22
23
24
25
26
# File 'service/objects/vm.rb', line 21

def generate_schedule_str(id, action, time)
    "\nSCHED_ACTION=[\n" + 
    "  ACTION=\"#{action}\",\n" + 
    "  ID=\"#{id}\",\n" + 
    "  TIME=\"#{time}\" ]"
end

#get_vms_vcenter_dsString

Gets the datastore, where VM allocated is

Returns:

  • (String)

    DS name



181
182
183
184
185
186
187
188
189
190
191
192
# File 'service/objects/vm.rb', line 181

def get_vms_vcenter_ds
    host = onblock(Host, IONe.new($client, $db).get_vm_host(self.id))
    datastores = get_vcenter_dc(host).datastoreFolder.children
    
    self.info!
    search_template = "VirtualMachine(\"#{self.deploy_id}\")"
    datastores.each do | ds |
        ds.vm.each do | vm |
            return ds.name if vm.to_s == search_template
        end
    end
end

#getResourcesAllocationLimits(name = nil) ⇒ Hash | String

Note:

For correct work of this method, you must keep actual vCenter Password at VCENTER_PASSWORD_ACTUAL attribute in OpenNebula

Note:

Method searches VM by it's default name: one-(id)-(name), if target vm got another name, you should provide it

Gets resources allocation limits from vCenter node

Parameters:

  • name (String) (defaults to: nil)

    VM name on vCenter node

Returns:

  • (Hash | String)

    Returns limits Hash if success or exception message if fails



276
277
278
279
280
281
282
283
284
285
286
287
# File 'service/objects/vm.rb', line 276

def getResourcesAllocationLimits(name = nil)
    begin
        host = onblock(Host, IONe.new($client, $db).get_vm_host(self.id))
        datacenter = get_vcenter_dc(host)

        vm = recursive_find_vm(datacenter.vmFolder, name.nil? ? "one-#{self.info! || self.id}-#{self.name}" : name).first
        vm_disk = vm.disks.first
        {cpu: vm.config.cpuAllocation.limit, ram: vm.config.cpuAllocation.limit, iops: vm_disk.storageIOAllocation.limit}
    rescue => e
        "Unexpected error, cannot handle it: #{e.message}"
    end
end

#got_snapshot?Boolean

Gives info about snapshots availability

Returns:

  • (Boolean)


311
312
313
314
# File 'service/objects/vm.rb', line 311

def got_snapshot?
    self.info!
    !self.to_hash['VM']['TEMPLATE']['SNAPSHOT'].nil?
end

#hot_resize(spec = {:name => nil}) ⇒ Boolean | String

Note:

Method returns true if resize action ended correct, false if VM not support hot reconfiguring

Resizes VM without powering off the VM

Parameters:

  • spec (Hash) (defaults to: {:name => nil})

Options Hash (spec):

  • :cpu (Integer)

    CPU amount to set

  • :ram (Integer)

    RAM amount in MB to set

  • :name (String)

    VM name on vCenter node

Returns:

  • (Boolean | String)


200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'service/objects/vm.rb', line 200

def hot_resize(spec = {:name => nil})
    return false if !self.hotAddEnabled?
    begin
        host = onblock(Host, IONe.new($client, $db).get_vm_host(self.id))
        datacenter = get_vcenter_dc(host)

        vm = recursive_find_vm(datacenter.vmFolder, spec[:name].nil? ? "one-#{self.info! || self.id}-#{self.name}" : spec[:name]).first
        query = {
            :numCPUs => spec[:cpu],
            :memoryMB => spec[:ram]
        }
        vm.ReconfigVM_Task(:spec => query).wait_for_completion
        return true
    rescue => e
        return "Reconfigure Error:#{e.message}"            
    end
end

#hotAddEnabled?(name = nil) ⇒ Hash | String

Note:

For correct work of this method, you must keep actual vCenter Password at VCENTER_PASSWORD_ACTUAL attribute in OpenNebula

Note:

Method searches VM by it's default name: one-(id)-(name), if target vm got another name, you should provide it

Checks if resources hot add enabled

Parameters:

  • name (String) (defaults to: nil)

    VM name on vCenter node

Returns:

  • (Hash | String)

    Returns limits Hash if success or exception message if fails



222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'service/objects/vm.rb', line 222

def hotAddEnabled?(name = nil)
    begin
        host = onblock(:h, IONe.new($client, $db).get_vm_host(self.id))
        datacenter = get_vcenter_dc(host)

        vm = recursive_find_vm(datacenter.vmFolder, name.nil? ? "one-#{self.info! || self.id}-#{self.name}" : name).first
        return {
            :cpu => vm.config.cpuHotAddEnabled, :ram => vm.config.memoryHotAddEnabled
        }
    rescue => e
        return "Unexpected error, cannot handle it: #{e.message}"
    end
end

#hotResourcesControlConf(spec = {:cpu => true, :ram => true, :name => nil}) ⇒ true | String

Sets resources hot add settings

Parameters:

  • spec (Hash) (defaults to: {:cpu => true, :ram => true, :name => nil})

Options Hash (spec):

  • :cpu (Boolean)
  • :ram (Boolean)
  • :name (String)

    VM name on vCenter node

Returns:

  • (true | String)


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
# File 'service/objects/vm.rb', line 241

def hotResourcesControlConf(spec = {:cpu => true, :ram => true, :name => nil})
    begin
        host, name = onblock(Host, IONe.new($client, $db).get_vm_host(self.id)), spec[:name]
        datacenter = get_vcenter_dc(host)

        vm = recursive_find_vm(datacenter.vmFolder, name.nil? ? "one-#{self.info! || self.id}-#{self.name}" : name).first
        query = {
            :cpuHotAddEnabled => spec[:cpu],
            :memoryHotAddEnabled => spec[:ram]
        }
        state = true
        begin
            LOG_DEBUG 'Powering VM Off'
            LOG_DEBUG vm.PowerOffVM_Task.wait_for_completion
        rescue => e
            state = false
        end
        
            LOG_DEBUG 'Reconfiguring VM'
            LOG_DEBUG vm.ReconfigVM_Task(:spec => query).wait_for_completion
        
        begin
            LOG_DEBUG 'Powering VM On'
            LOG_DEBUG vm.PowerOnVM_Task.wait_for_completion
        rescue
        end if state
    rescue => e
        "Unexpected error, cannot handle it: #{e.message}"
    end
end

#is_at_ds?(ds_name) ⇒ Boolean

Checks if vm is on given vCenter Datastore

Returns:

  • (Boolean)


164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'service/objects/vm.rb', line 164

def is_at_ds?(ds_name)
    host = onblock(Host, IONe.new($client, $db).get_vm_host(self.id))
    datacenter = get_vcenter_dc(host)
    begin
        datastore = recursive_find_ds(datacenter.datastoreFolder, ds_name, true).first
    rescue
        return 'Invalid DS name.'
    end
    self.info!
    search_template = "VirtualMachine(\"#{self.deploy_id}\")"
    datastore.vm.each do | vm |
        return true if vm.to_s == search_template
    end
    false
end

#lcm_state!Object

Returns actual lcm state without calling info! method



326
327
328
# File 'service/objects/vm.rb', line 326

def lcm_state!
    self.info! || self.lcm_state
end

#lcm_state_str!Object

Returns actual lcm state as string without calling info! method



334
335
336
# File 'service/objects/vm.rb', line 334

def lcm_state_str!
    self.info! || self.lcm_state_str
end

#list_snapshotsArray<Hash>, ...

Returns all available snapshots

Returns:



317
318
319
320
# File 'service/objects/vm.rb', line 317

def list_snapshots
    out = self.to_hash!['VM']['TEMPLATE']['SNAPSHOT']
    out.class == Array ? out : [ out ]
end

#schedule(action, time, periodic = nil) ⇒ Object

Adds actions to OpenNebula internal scheduler, like --schedule in 'onevm' cli utility

Parameters:

  • action (String)
    • Action which should be scheduled
  • time (Integer)
    • Time when action schould be perfomed in secs
  • periodic (String) (defaults to: nil)
    • Not working now

Returns:

  • true



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'service/objects/vm.rb', line 37

def schedule(action, time, periodic = nil)
    return 'Unsupported action' if !SCHEDULABLE_ACTIONS.include? action
    self.info!
    id = 
        begin
            ids = self.to_hash['VM']['USER_TEMPLATE']['SCHED_ACTION']
            if ids.class == Array then
                ids.last['ID'].to_i + 1
            elsif ids.class == Hash then
                ids['ID'].to_i + 1
            elsif ids.class == NilClass then
                ids.to_i
            else
                raise
            end
        rescue
            0
        end

    # str_periodic = ''

    self.update(self.user_template_str << generate_schedule_str(id, action, time))
end

#schedule_actionsArray

Returns allowed actions to schedule

Returns:



29
30
31
# File 'service/objects/vm.rb', line 29

def schedule_actions
    SCHEDULABLE_ACTIONS
end

#schedulerNilClass | Hash | Array

Lists actions scheduled in OpenNebula

Returns:



83
84
85
86
# File 'service/objects/vm.rb', line 83

def scheduler
    self.info!
    self.to_hash['VM']['USER_TEMPLATE']['SCHED_ACTION']
end

#setResourcesAllocationLimits(spec) ⇒ String

Note:

For correct work of this method, you must keep actual vCenter Password at VCENTER_PASSWORD_ACTUAL attribute in OpenNebula

Note:

Attention!!! VM will be rebooted at the process

Note:

Valid units are: CPU - MHz, RAM - MB

Note:

Method searches VM by it's default name: one-(id)-(name), if target vm got another name, you should provide it

Sets resources allocation limits at vCenter node

Examples:

Return messages decode

vm.setResourcesAllocationLimits(spec)
    => 'Reconfigure Success' -- Task finished with success code, all specs are equal to given
    => 'Reconfigure Unsuccessed' -- Some of specs didn't changed
    => 'Reconfigure Error:{error message}' -- Exception has been generated while proceed, check your configuration

Parameters:

  • spec (Hash)
    • List of limits should be applied to target VM

Options Hash (spec):

  • :cpu (Integer)

    MHz limit for VMs CPU usage

  • :ram (Integer)

    MBytes limit for VMs RAM space usage

  • :iops (Integer)

    IOPS limit for VMs disk

  • :name (String)

    VM name on vCenter node

Returns:

  • (String)


120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'service/objects/vm.rb', line 120

def setResourcesAllocationLimits(spec)
    LOG_DEBUG spec.debug_out
    return 'Unsupported query' if IONe.new($client, $db).get_vm_data(self.id)['IMPORTED'] == 'YES'        
    
    query, host = {}, onblock(Host, IONe.new($client, $db).get_vm_host(self.id))
    datacenter = get_vcenter_dc(host)

    vm = recursive_find_vm(datacenter.vmFolder, spec[:name].nil? ? "one-#{self.info! || self.id}-#{self.name}" : spec[:name]).first
    disk = vm.disks.first

    query[:cpuAllocation] = {:limit => spec[:cpu].to_i, :reservation => 0} if !spec[:cpu].nil?
    query[:memoryAllocation] = {:limit => spec[:ram].to_i} if !spec[:ram].nil?
    if !spec[:iops].nil? then
        disk.storageIOAllocation.limit = spec[:iops].to_i
        disk.backing.sharing = nil
        query[:deviceChange] = [{
                :device => disk,
                :operation => :edit
        }]
    end

    state = true
    begin
        LOG_DEBUG 'Powering VM Off'
        LOG_DEBUG vm.PowerOffVM_Task.wait_for_completion
    rescue => e
        state = false
    end
    
        LOG_DEBUG 'Reconfiguring VM'
        LOG_DEBUG vm.ReconfigVM_Task(:spec => query).wait_for_completion
    
    begin
        LOG_DEBUG 'Powering VM On'
        LOG_DEBUG vm.PowerOnVM_Task.wait_for_completion
    rescue
    end if state

rescue => e
    return "Reconfigure Error:#{e.message}<|>Backtrace:#{e.backtrace}"
ensure
    return nil
end

#state!Object

Returns actual state without calling info! method



322
323
324
# File 'service/objects/vm.rb', line 322

def state!
    self.info! || self.state
end

#state_str!Object

Returns actual state as string without calling info! method



330
331
332
# File 'service/objects/vm.rb', line 330

def state_str!
    self.info! || self.state_str
end

#uid(info = true, from_pool = false) ⇒ Integer

Returns owner user ID

Parameters:

  • info (Boolean) (defaults to: true)
    • method doesn't get object full info one more time -- usefull if collecting data from pool
  • from_pool (Boolean) (defaults to: false)
    • levels differenct between object and object received from pool.each | object |

Returns:

  • (Integer)


295
296
297
298
299
# File 'service/objects/vm.rb', line 295

def uid(info = true, from_pool = false)
    self.info! if info
    return @xml[0].children[1].text.to_i unless from_pool
    @xml.children[1].text.to_i
end

#uname(info = true, from_pool = false) ⇒ String

Returns owner user name

Parameters:

  • info (Boolean) (defaults to: true)
    • method doesn't get object full info one more time -- usefull if collecting data from pool
  • from_pool (Boolean) (defaults to: false)
    • levels differenct between object and object received from pool.each | object |

Returns:

  • (String)


304
305
306
307
308
# File 'service/objects/vm.rb', line 304

def uname(info = true, from_pool = false)
    self.info! if info
    return @xml[0].children[3].text.to_i unless from_pool
    @xml.children[3].text
end

#unschedule(id) ⇒ Object

Note:

Not working, if action is already initialized

Unschedules given action by ID



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'service/objects/vm.rb', line 62

def unschedule(id)
    self.info!
    schedule_data, object = self.to_hash['VM']['USER_TEMPLATE']['SCHED_ACTION'], nil

    if schedule_data.class == Array then
        schedule_data.map do | el |
            object = el if el['ID'] == id.to_s
        end
    elsif schedule_data.class == Hash then
        return 'none' if schedule_data['ID'] != id.to_s
        object = schedule_data
    else
        return 'none'
    end
    action, time = object['ACTION'], object['TIME']
    template = self.user_template_str
    template.slice!(generate_schedule_str(id, action, time))
    self.update(template)
end

#wait_for_state(s = 3, lcm_s = 3) ⇒ Boolean

Waits until VM will have the given state

Parameters:

  • s (Integer) (defaults to: 3)
    • VM state to wait for
  • lcm_s (Integer) (defaults to: 3)
    • VM LCM state to wait for

Returns:

  • (Boolean)


91
92
93
94
95
96
97
98
99
100
# File 'service/objects/vm.rb', line 91

def wait_for_state(s = 3, lcm_s = 3)
    i = 0
    until state() == s && lcm_state() == lcm_s do
        return false if i >= 3600
        sleep(1)
        i += 1
        self.info!
    end
    true
end