Class: IONe

Inherits:
Object
  • Object
show all
Includes:
Deferable
Defined in:
ione.rb,
ione.rb,
lib/server/main.rb,
lib/vminfo/main.rb,
lib/vmcontrol/main.rb,
lib/accounting/main.rb,
lib/appbindings/main.rb,
lib/useful_things/main.rb,
lib/creative_funcs/main.rb,
lib/data_import_handler/main.rb,
modules/stat/main.rb,
modules/ansible/main.rb,
service/log.rb

Overview

Main App class. All methods, which must be available as JSON-RPC methods, should be defined in this class

Defined Under Namespace

Classes: PostDeployActivities

Ansible collapse

Instance Method Summary collapse

Methods included from Deferable

#defer

Constructor Details

#initialize(client, db) ⇒ IONe

IONe initializer, stores auth-client and version

Parameters:

  • client (OpenNebula::Client)


89
90
91
92
93
# File 'ione.rb', line 89

def initialize(client, db)
    @client = client
    @db = db
    @version = VERSION
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object

Will call object method if smth like vm_poweroff(1) called



3
4
5
6
7
8
9
10
# File 'lib/appbindings/main.rb', line 3

def method_missing m, *args, &block
    obj, method = m.to_s.split('_')
    if ONeHelper::ON_INSTANCES.keys.include? obj.to_sym then
        onblock(obj.to_sym, args[0]).send(method, self)
    else
        super
    end
end

Instance Method Details

#activity_logString

Get log from ione.log file

Returns:

  • (String)

    Log



147
148
149
150
151
152
# File 'service/log.rb', line 147

def activity_log()
    LOG_STAT()        
    LOG "Log file content has been copied remotely", "activity_log"
    log = File.read("#{LOG_ROOT}/ione.log")
    log
end

#AnsibleController(params) ⇒ 200

Runs given playbook on given host

Examples:

{
  'host' => '127.0.0.1:22',
  'services' => [
    'playbook0' => 'playbook0 body',
    'playbook1' => 'playbook1 body'
  ]

Parameters:

  • params (Hash)
    • Parameters for Ansible execution

Options Hash (params):

  • host (String)
    • hostname or IP-address of VM where to run playbook in host:port format

  • services (Array)
    • services to run on VM

Returns:

  • (200)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'modules/ansible/main.rb', line 32

def AnsibleController(params)
    LOG_DEBUG params.merge!({:method => __method__.to_s}).debug_out
    host, playbooks = params['host'], params['services']
    ip, err = host.split(':').first, ""
    Thread.new do
        playbooks.each do |service, playbook|
            installid = id_gen.crypt(service.delete(' ')[0..3]).delete('!@#$%^&*()_+:"\'.,\/\\')
            LOG "#{service} should be installed on #{ip}, installation ID is: #{installid}", "AnsibleController"
            begin
                LOG 'Connecting to Ansible', 'AnsibleController'            
                err = "Line #{__LINE__ + 1}: Error while connecting to Ansible-server"
                Net::SSH.start(ANSIBLE_HOST, ANSIBLE_HOST_USER, :port => ANSIBLE_HOST_PORT) do | ssh |
                    err = "Line #{__LINE__ + 1}: Error while creating temporary playbook file occurred"
                    File.open("/tmp/#{installid}.yml", 'w') { |file| file.write(playbook.gsub('<%group%>', installid)) }
                    err = "Line #{__LINE__ + 1}: Error while uploading playbook occurred"
                    ssh.sftp.upload!("/tmp/#{installid}.yml", "/tmp/#{installid}.yml")
                    err = "Line #{__LINE__ + 1}: Error while creating temporary ansible-inventory file occurred"
                    File.open("/tmp/#{installid}.ini", 'w') { |file| file.write("[#{installid}]\n#{host}\n") }
                    err = "Line #{__LINE__ + 1}: Error while uploading ansible-inventory occurred"
                    ssh.sftp.upload!("/tmp/#{installid}.ini", "/tmp/#{installid}.ini")
                    Thread.exit if params['upload']
                    LOG 'PB and hosts have been generated', 'AnsibleController' 
                    err = "Line #{__LINE__ + 1}: Error while executing playbook occured"
                    LOG 'Executing PB', 'AnsibleController' 
                    ssh.exec!("ansible-playbook /tmp/#{installid}.yml -i /tmp/#{installid}.ini")
                    LOG 'PB has been Executed', 'AnsibleController' 
                    LOG "#{service} installed on #{ip}", "AnsibleController"
                    LOG 'Wiping hosts and pb files', 'AnsibleController' 
                    ssh.sftp.remove!("/tmp/#{installid}.ini")
                    File.delete("/tmp/#{installid}.ini")
                    ssh.sftp.remove!("/tmp/#{installid}.yml")
                    File.delete("/tmp/#{installid}.yml")
                end
            rescue => e
                LOG "An Error occured, while installing #{service} on #{ip}: #{err}, Code: #{e.message}", "AnsibleController"
            end
        end
        LOG 'Ansible job ended', 'AnsibleController'
        if !params['end-method'].nil? then
            LOG 'Calling end-method', 'AnsibleController'
            begin
                send params['end-method'], params
            rescue
            end
        end
        Thread.exit
    end
    return 200
end

#AnsiblePlaybookProcessInfo(id) ⇒ Hash

Returns AnsblePlaybook run Process by id as Hash

Parameters:

  • id (Fixnum)
    • Process id

Returns:



191
192
193
# File 'modules/ansible/main.rb', line 191

def AnsiblePlaybookProcessInfo id
    AnsiblePlaybookProcess.new(proc_id:id).to_hash
end

#AnsiblePlaybookProcessStatus(id) ⇒ String

Returns given AnsiblePlaybookProcess state

Parameters:

  • id (Fixnum)
    • Process id

Returns:

  • (String)


185
186
187
# File 'modules/ansible/main.rb', line 185

def AnsiblePlaybookProcessStatus id
    AnsiblePlaybookProcess.new(proc_id:id).status
end

#AnsiblePlaybookToProcess(playbook_id, uid, hosts = [], vars = {}, comment = '', auth = 'default') ⇒ Object

Creates Process instance with given playbook, host and variables

Parameters:

  • playbook_id (Fixnum)
    • Playbook ID

  • uid (Fixnum)
    • User ID who initialized playbook

  • hosts (Array<String>) (defaults to: [])
    • Array of hosts where to run playbook

  • vars (Hash) (defaults to: {})
    • Hash with playbook variables values

  • comment (String) (defaults to: '')
  • auth (String) (defaults to: 'default')
    • auth driver



154
155
156
157
158
159
160
161
162
163
# File 'modules/ansible/main.rb', line 154

def AnsiblePlaybookToProcess playbook_id, uid, hosts = [], vars = {}, comment = '', auth = 'default'
    AnsiblePlaybookProcess.new(
        playbook_id: playbook_id,
        uid: uid,
        hosts: hosts,
        vars: vars,
        comment: comment,
        auth: auth
    ).id
end

#CalculateShowback(uid, stime, etime = Time.now.to_i, group_by_day = false, stream_data = nil) ⇒ Object

Calculates Showback for given User

Parameters:

  • uid (Integer)
    • User ID

  • stime (Integer)
    • Point from which calculation starts(timestamp)

  • etime (Integer) (defaults to: Time.now.to_i)
    • Point at which calculation stops(timestamp)

  • group_by_day (Boolean) (defaults to: false)
    • Groups showbacks by days



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/accounting/main.rb', line 17

def CalculateShowback uid, stime, etime = Time.now.to_i, group_by_day = false, stream_data = nil
    vm_pool = @db[:vm_pool].select(:oid).where(:uid => uid).to_a.map! {| vm | vm[:oid]}

    showback = {}
    stream = !stream_data.nil?

    vm_pool.each do | vm |
        vm = onblock :vm, vm, @client
        vm.info!

        next if vm['/VM/ETIME'].to_i < stime && vm['/VM/ETIME'].to_i != 0
        begin
            r = vm.calculate_showback(stime, etime, group_by_day).without('time_period_requested', 'time_period_corrected')
            showback[vm.id] = r
            if stream then
                stream_data << "\"#{vm.id}\": " << JSON.generate(r) << ","
            end
        rescue OpenNebula::VirtualMachine::ShowbackError => e
            if e.message.include? "VM didn't exist in given time-period" then
                next
            else
                raise e
            end
        end
    end

    showback['TOTAL'] = showback.values.inject(0){| result, record | result += record['TOTAL'].to_f }
    showback['time_period_requested'] = etime - stime
    if stream then
        stream_data << '"TOTAL": ' << showback['TOTAL'] << ','
        stream_data << '"time_period_requested": ' << showback['time_period_requested']
    end

    showback unless stream
end

#CheckAnsiblePlaybookSyntax(body) ⇒ Boolean

Checks AnsiblePlaybook Syntax



144
145
146
# File 'modules/ansible/main.rb', line 144

def CheckAnsiblePlaybookSyntax body
    AnsiblePlaybook.check_syntax body
end

#compare_info(vms = []) ⇒ Array<Hash>, ...

Returns VM listing with some additional data, available nodes list and free IP-addresses in AddressPool

Examples:

VM's filter given

compare_info([1, 2, ...]) => 
    [{
        :vmid => 1, :userid => 1, :host => 'example-node0',
        :login => 'username', :ip => '0.0.0.0', :state => 'RUNNING'
    }, ...], ['example-node0', 'example-node1', ...]

VM's filter not given

compare_info() => 
    [{
        :vmid => 0, :userid => 0, :host => 'example-node0',
        :login => 'username', :ip => '192.168.10.3', :state => 'RUNNING'
    }, ...], ['example-node0', 'example-node1', ...], ['192.168.10.2', '192.168.10.4', '192.168.10.5', ...]

Parameters:

  • vms (Array) (defaults to: [])
    • filter, returns only listed vms

Returns:



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/useful_things/main.rb', line 130

def compare_info vms = []
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'compare_info') }
    info = []
    infot = Thread.new do
        unless vms.empty? then
            vm_pool = vms.map! do |vmid| 
                onblock(:vm, vmid) {| vm | vm.info! || vm }
            end
        else
            vm_pool = VirtualMachinePool.new(@client)
            vm_pool.info_all!
        end
        vm_pool.each do |vm| # Creating VM list from VirtualMachine Pool Object
            begin
            info << {
                :vmid => vm.id, :userid => vm.uid(false), :host => get_vm_host(vm.id),
                :login => vm.uname(false, true), :ip => GetIP(vm), :state => (vm.lcm_state != 0 ? vm.lcm_state_str : vm.state_str)
            }
            rescue
                binding.pry
                break
            end
        end
    end

    return info || infot.join unless vms.empty?

    free = []
    freet = Thread.new do
        vn_pool = VirtualNetworkPool.new(@client)
        vn_pool.info_all!
        vn_pool.each do | vn | # Getting leases from each VN
            break if vn.nil?
            begin
                # This, generates list of free addresses in given VN
                vn = vn.to_hash!["VNET"]["AR_POOL"]["AR"][0]
                next if (vn['IP'] && vn['SIZE']).nil?
                pool = ((vn["IP"].split('.').last.to_i)..(vn["IP"].split('.').last.to_i + vn["SIZE"].to_i)).to_a.map! { |item| vn['IP'].split('.').slice(0..2).join('.') + "." + item.to_s }
                vn['LEASES']['LEASE'].each do | lease |
                    pool.delete(lease['IP'])
                end
                free.push pool
            rescue
            end
        end
    end

    host_pool, hosts = HostPool.new(@client), [] # Collecting hostnames(node-names) from HostPool
    host_pool.info_all!
    host_pool.each do | host |
        hosts << host.name
    end

    freet.join
    infot.join

    return info, hosts, free
end

#CreateAnsiblePlaybook(args = {}) ⇒ Fixnum

Creates playbook

Parameters:

  • args (Hash) (defaults to: {})
    • Parameters for new playbook

Options Hash (args):

  • name (String)
    • (Mandatory)

  • uid (Integer)
    • Owner id (Mandatory)

  • gid (Integer)
    • Group id (Mandatory)

  • description (String)
    • (Optional)

  • body (String)
    • (Mandatory)

  • extra_data (String)
    • You may store here additional data, such as supported OS (Optional)

Returns:

  • (Fixnum)

    new playbook id



93
94
95
# File 'modules/ansible/main.rb', line 93

def CreateAnsiblePlaybook args = {}
    AnsiblePlaybook.new(args.to_sym!).id
end

#CreateVMwithSpecs(params, trace = ["#{__method__.to_s} method called:#{__LINE__}"]) ⇒ Hash?

Creates new virtual machine from the given OS template and resize it to given specs, and new user account, which becomes owner of this VM

Examples:

Example out

Success: {'userid' => 777, 'vmid' => 123, 'ip' => '0.0.0.0'}
Debug is set to true: nil
Template not found Error: {'error' => "TemplateLoadError", 'trace' => (trace << "TemplateLoadError:#{__LINE__ - 1}")(Array<String>)}
User create Error: {'error' => "UserAllocateError", 'trace' => trace(Array<String>)}
Unknown error: { 'error' => e.message, 'trace' => trace(Array<String>)} 

Parameters:

  • params (Hash)
    • all needed data for new User and VM creation

  • trace (Array<String>) (defaults to: ["#{__method__.to_s} method called:#{__LINE__}"])
    • public trace log

Options Hash (params):

  • :login (String)

    Username for new OpenNebula account

  • :password (String)

    Password for new OpenNebula account

  • :passwd (String)

    Password for new Virtual Machine

  • :templateid (Integer)

    Template ID to instantiate

  • :cpu (Integer)

    vCPU cores amount for new VM

  • :iops (Integer)

    IOPS limit for new VM's drive

  • :units (String)

    Units for RAM and drive size, can be 'MB' or 'GB'

  • :ram (Integer)

    RAM size for new VM

  • :drive (Integer)

    Drive size for new VM

  • :ds_type (String)

    VM deploy target datastore drives type, 'SSD' or 'HDD'

  • :groupid (Integer)

    Additional group, in which user should be

  • :trial (Boolean) — default: false

    VM will be suspended after TRIAL_SUSPEND_DELAY

  • :release (Boolean) — default: false

    VM will be started on HOLD if false

  • :user-template (String)

    Addon template, you may append to default template(Use XML-string as OpenNebula requires)

Returns:

  • (Hash, nil)

    UserID, VMID and IP address if success, or error message and backtrace log if error



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
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
525
526
527
# File 'lib/creative_funcs/main.rb', line 322

def CreateVMwithSpecs(params, trace = ["#{__method__.to_s} method called:#{__LINE__}"])
    LOG_STAT()
    LOG_CALL(id = id_gen(), true, __method__)
    defer { LOG_CALL(id, false, 'CreateVMwithSpecs') }
    LOG_DEBUG params.merge!(:method => __method__.to_s).debug_out
    # return {'userid' => 6666, 'vmid' => 6666, 'ip' => '127.0.0.1'}
    trace << "Checking params types:#{__LINE__ + 1}"
        
        
    params['cpu'], params['ram'], params['drive'], params['iops'] = params.get('cpu', 'ram', 'drive', 'iops').map { |el| el.to_i }

    begin
        params['iops'] = params['iops'] == 0 ? $ione_conf['vCenter']['drives-iops'][params['ds-type']] : params['iops']
    rescue
        LOG_DEBUG "No vCenter configuration found"
    end

    params['username'] = params['username'] || 'Administrator'
    ###################### Doing some important system stuff ###############################################################
    
    LOG_AUTO "CreateVMwithSpecs for #{params['login']} Order Accepted! #{params['trial'] == true ? "VM is Trial" : nil}"
    
    LOG_DEBUG "Params: #{params.debug_out}"
    
    trace << "Checking template:#{__LINE__ + 1}"
    onblock(:t, params['templateid']) do | t |
        result = t.info!
        if result != nil then
            LOG_ERROR "Error: TemplateLoadError" 
            return {'error' => "TemplateLoadError", 'trace' => (trace << "TemplateLoadError:#{__LINE__ - 1}")}
        end
        params['extra'] = params['extra'] || {'type' => t['/VMTEMPLATE/TEMPLATE/HYPERVISOR']}
    end
        
    #####################################################################################################################
    
    #####   Initializing useful variables   #####
    userid, vmid = 0, 0
    ##### Initializing useful variables END #####
    
    
    #####   Creating new User   #####
    LOG_AUTO "Creating new user for #{params['login']}"
    if params['nouser'].nil? || !params['nouser'] then
        trace << "Creating new user:#{__LINE__ + 1}"
        userid, user =
            UserCreate(
                params['login'], params['password'], USERS_GROUP, object:true,
                type: params['extra']['type'] ) if params['test'].nil?
        LOG_ERROR "Error: UserAllocateError" if userid == 0
        trace << "UserAllocateError:#{__LINE__ - 2}" if userid == 0
        return {'error' => "UserAllocateError", 'trace' => trace} if userid == 0
    else
        userid, user = params['userid'], onblock(:u, params['userid'])
    end
    params['user_id'] = userid
    LOG_AUTO "New User account created"

    ##### Creating new User END #####
    
    #####   Creating and Configuring VM   #####
    LOG_AUTO "Creating VM for #{params['login']}"
    trace << "Creating new VM:#{__LINE__ + 1}"
    onblock(:t, params['templateid']) do | t |
        t.info!
        specs = ""
        if !t['/VMTEMPLATE/TEMPLATE/CAPACITY'] && t['/VMTEMPLATE/TEMPLATE/HYPERVISOR'].upcase == "VCENTER" then
            specs = {
                        "VCPU" => params['cpu'],
                        "MEMORY" => params['ram'] * (params['units'] == 'GB' ? 1024 : 1),
                        "DRIVE" => params['ds_type'],
                        "DISK" => {
                            "IMAGE_ID" => t.to_hash['VMTEMPLATE']['TEMPLATE']['DISK']['IMAGE_ID'],
                            "SIZE" => params['drive'] * (params['units'] == 'GB' ? 1024 : 1),
                            "OPENNEBULA_MANAGED" => "NO"
                        }
                    }
        elsif t['/VMTEMPLATE/TEMPLATE/HYPERVISOR'].upcase == 'AZURE' then
            specs = {
                        "OS_DISK_SIZE" => params['drive'],
                        "SIZE" => params['extra']['instance_size'],
                        "VM_USER_NAME" => params['username'],
                        "PASSWORD" => params['passwd'],
                        "VCPU" => params['cpu'],
                        "MEMORY" => params['ram'] * (params['units'] == 'GB' ? 1024 : 1)
                    }
        elsif t['/VMTEMPLATE/TEMPLATE/HYPERVISOR'].upcase == 'KVM' then
            specs = {
                        "VCPU" => params['cpu'],
                        "MEMORY" => params['ram'] * (params['units'] == 'GB' ? 1024 : 1),
                        "DRIVE" => params['ds_type'],
                        "DISK" => {
                            "IMAGE_ID" => t.to_hash['VMTEMPLATE']['TEMPLATE']['DISK']['IMAGE_ID'],
                            "SIZE" => params['drive'] * (params['units'] == 'GB' ? 1024 : 1),
                            "DEV_PREFIX" => "vd",
                            "DRIVER" => "qcow2",
                            "OPENNEBULA_MANAGED" => "NO"
                        }
                    }
        end
        trace << "Updating user quota:#{__LINE__ + 1}"
        user.update_quota_by_vm(
            'append' => true, 'cpu' => params['cpu'],
            'ram' => params['ram'] * (params['units'] == 'GB' ? 1024 : 1),
            'drive' => params['drive'] * (params['units'] == 'GB' ? 1024 : 1)
        ) unless t['/VMTEMPLATE/TEMPLATE/CAPACITY'] == 'FIXED'
        specs = specs.to_one_template
        LOG_DEBUG "Resulting capacity template:\n" + specs
        vmid = t.instantiate("#{params['login']}_vm", true, specs + "\n" + params['user-template'].to_s)
    end

    raise "Template instantiate Error: #{vmid.message}" if vmid.class != Fixnum
    
    host =  if params['host'].nil? then
                JSON.parse(@db[:settings].as_hash(:name, :body)['NODES_DEFAULT'])[params['extra']['type'].upcase]
            else
                params['host']
            end

    LOG_AUTO 'Configuring VM Template'
    trace << "Configuring VM Template:#{__LINE__ + 1}"            
    onblock(:vm, vmid) do | vm |
        trace << "Changing VM owner:#{__LINE__ + 1}"
        begin
            r = vm.chown(userid, USERS_GROUP)
            raise r.message unless r.nil?
        rescue
            LOG_DEBUG "CHOWN error, params: #{userid}, #{vm}"
        end

        if %w(VCENTER KVM).include? params['extra']['type'].upcase then
            win = onblock(:t, params['templateid']).win?
            LOG_DEBUG "Instantiating VM as#{win ? nil : ' not'} Windows"
            trace << "Setting VM context:#{__LINE__ + 2}"
            begin
                vm.updateconf(
                    "CONTEXT = [ NETWORK=\"YES\", PASSWORD = \"#{params['passwd']}\", SSH_PUBLIC_KEY = \"$USER[SSH_PUBLIC_KEY]\"#{ win ? ", USERNAME = \"#{params['username']}\"" : nil} ]"
                )
            rescue => e
                LOG_DEBUG "Context configuring error: #{e.message}"
            end

            trace << "Setting VM VNC settings:#{__LINE__ + 2}"
            begin
                vm.updateconf(
                    "GRAPHICS = [ LISTEN=\"0.0.0.0\", PORT=\"#{($ione_conf['OpenNebula']['base-vnc-port'] + vmid).to_s}\", TYPE=\"VNC\" ]"
                ) # Configuring VNC
            rescue => e
                LOG_DEBUG "VNC configuring error: #{e.message}"
            end
        end

        if %w(VCENTER KVM).include? params['extra']['type'].upcase then
            trace << "Deploying VM:#{__LINE__ + 1}"
            vm.deploy(host, false, ChooseDS(params['ds_type'], params['extra']['type']))
        else
            trace << "Deploying VM:#{__LINE__ + 1}"
            vm.deploy(host, false)
        end if params['release']
    end
        ##### Creating and Configuring VM END #####            

        #####   PostDeploy Activity define   #####
    Thread.new do

        LOG_DEBUG "Starting PostDeploy Activities for VM#{vmid}"
            
        onblock(:vm, vmid).wait_for_state

        LOG_DEBUG "VM is active now, let it go"

        postDeploy = PostDeployActivities.new @client

        #TrialController

        if params['trial'] then
            trace << "Creating trial counter thread:#{__LINE__ + 1}"
            postDeploy.TrialController(params, vmid, host)
        end

        #endTrialController
        #AnsibleController

        if params['ansible'] && params['release'] then
            trace << "Creating Ansible Installer thread:#{__LINE__ + 1}"
            postDeploy.AnsibleController(params, vmid, host)
        end

        #endAnsibleController

    end if params['release']
    ##### PostDeploy Activity define END #####

    LOG_AUTO 'Post-Deploy joblist defined, basic installation job ended'
    return out = {'userid' => userid, 'vmid' => vmid, 'ip' => GetIP(vmid)}
rescue => err
    begin
        out = { :exception => err.message, :trace => trace << 'END_TRACE' }
        LOG_DEBUG out.debug_out
        out[:params] = params
        return out
    ensure
        onblock(:vm, vmid).recover(3)    if defined? vmid
        onblock(:u, userid).delete      if defined? userid
    end
end

#DatastoresMonitoring(type) ⇒ Array<Hash> | String

Returns monitoring information about datastores

Examples:

DatastoresMonitoring('sys') => [{"id"=>101, "name"=>"NASX", "full_size"=>"16TB", "used"=>"3.94TB", "type"=>"HDD", "deploy"=>"TRUE"}, ...]
DatastoresMonitoring('ing') => String("WrongTypeExeption: type 'ing' not exists")

Parameters:

  • type (String)
    • choose datastores types for listing: system('sys') or image('img')

Returns:



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/useful_things/main.rb', line 210

def DatastoresMonitoring(type)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'DatastoresMonitoring') }    
    return "WrongTypeExeption: type '#{type}' not exists" if type != 'sys' && type != 'img'

    # @!visibility private
    # Converts MB to GB
    def sizeConvert(mb)
        if mb.to_f / 1024 > 768 then
            return "#{(mb.to_f / 1048576.0).round(2).to_s}TB"
        else
            return "#{(mb.to_f / 1024.0).round(2).to_s}GB" 
        end
    end

    img_pool, mon = DatastorePool.new(@client), []
    img_pool.info_all!
    img_pool.each do | img |
        mon << { 
            'id' => img.id, 'name' => img.name.split('(').first, :full_size => sizeConvert(img.to_hash['DATASTORE']['TOTAL_MB']),
            'used' => sizeConvert(img.to_hash['DATASTORE']['USED_MB']),
            'type' => img.to_hash['DATASTORE']['TEMPLATE']['DRIVE_TYPE'],
            'deploy' => img.to_hash['DATASTORE']['TEMPLATE']['DEPLOY'],
            'hypervisor' => img.to_hash['DATASTORE']['TEMPLATE']['HYPERVISOR']
        } if img.short_type_str == type && img.id > 2
    end
    mon
end

#Delete(userid) ⇒ nil | OpenNebula::Error

Deletes given user by ID

Parameters:

  • userid (Integer)

Returns:

  • (nil | OpenNebula::Error)


251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/vmcontrol/main.rb', line 251

def Delete(userid)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Delete') }

    if userid == 0 then
        LOG "Delete query rejected! Tryed to delete root-user(oneadmin)", "Delete"
    end
    LOG "Deleting User ##{userid}", "Delete"
    onblock(:u, userid).delete
end

#DeleteAnsiblePlaybook(id) ⇒ NilClass

Deletes playbook from DB by id

Parameters:

  • id (Fixnum)

Returns:



121
122
123
# File 'modules/ansible/main.rb', line 121

def DeleteAnsiblePlaybook id
    AnsiblePlaybook.new(id:id).delete
end

#DeleteAnsiblePlaybookProcess(id) ⇒ NilClass

Deletes given AnsiblePlaybookProcess

Parameters:

  • id (Fixnum)
    • Process id

Returns:



173
174
175
# File 'modules/ansible/main.rb', line 173

def DeleteAnsiblePlaybookProcess id
    AnsiblePlaybookProcess.new(proc_id:id).delete
end

#get_uid_by_name(name) ⇒ Integer| 'none'

Returns user id by username

Examples:

=> Integer => user found
=> 'none'  => no user exists

Parameters:

  • name (String)
    • username

Returns:

  • (Integer| 'none')


57
58
59
60
61
62
63
64
65
66
67
# File 'lib/useful_things/main.rb', line 57

def get_uid_by_name(name)
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'get_uid_by_name') }
    up = UserPool.new(@client)
    up.info_all!
    up.each do | u |
        return u.id.to_i if u.name == name
    end
    'none'        
end

#get_vm_by_uid(uid) ⇒ Integer | 'none'

Returns vmid by owner id

Examples:

=> Integer => user and vm found
=> 'none'  => no user or now vm exists

Parameters:

  • uid (Integer)
    • owner id

Returns:

  • (Integer | 'none')


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/useful_things/main.rb', line 24

def get_vm_by_uid(uid)
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'get_vm_by_uid') }
    vmp = VirtualMachinePool.new(@client)
    vmp.info_all!
    vmp.each do | vm |
        return vm.id.to_i if vm.uid(false) == uid
    end
    'none'
end

#get_vm_by_uname(name) ⇒ Hash

Returns vmid, userid and VM IP by owner username

Examples:

=> {:vmid => Integer, :userid => Integer, :ip => String} => User and VM found
=> {:vmid => 'none', :userid => 'none', :ip => String}

Parameters:

  • name (String)
    • username

Returns:



74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/useful_things/main.rb', line 74

def get_vm_by_uname name
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'get_vm_by_uname') }
    userid = get_uid_by_name(name)
    vmid = get_vm_by_uid(userid)
    unless vmid.nil? then
        { :vmid => vmid, :userid => userid, :ip => GetIP(vmid) }
    else
        nil
    end
end

#get_vm_data(vm) ⇒ Hash

Getting VM most important data

Parameters:

  • vm (Integer)
    • VM ID

Returns:

  • (Hash)

    Data(name, owner-name, owner-id, group id, ip, host, state, cpu, ram, datastore type, disk size imported)



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/vminfo/main.rb', line 107

def get_vm_data(vm)
    vm = onblock(:vm, vm) if vm.class == Fixnum || vm.class == String
    r = vm.info!
    raise r if OpenNebula.is_error? r
    vmid = vm.id
    vm_hash = vm.to_hash!['VM']
    hostname, host_id = get_vm_host(vm, true)
    return {
        # "Name, owner, owner id, group id"
        'NAME' => vm_hash['NAME'], 'OWNER' => vm_hash['UNAME'], 'OWNERID' => vm_hash['UID'], 'GROUPID' => vm_hash['GID'],
        # IP, host and vm state
        'IP' => GetIP(vmid), 'HOST_ID' => host_id, 'HOST' => hostname, 'STATE' => vm.lcm_state != 0 ? vm.lcm_state_str : vm.state_str,
        # VM specs
        'CPU' => vm_hash['TEMPLATE']['VCPU'], 'RAM' => vm_hash['TEMPLATE']['MEMORY'],
        'DS_TYPE' => begin DatastoresMonitoring('sys').detect{|el| el['id'] == get_vm_ds(vmid).to_i}['type'] rescue nil end,
        'DRIVE' =>
        begin
            vm_hash['TEMPLATE']['DISK']['SIZE']
        rescue TypeError
            vm_hash['TEMPLATE']['DISK'].inject(0){|summ, disk| summ += disk['SIZE'].to_i }
        rescue
            nil
        end,
        # VM creation hist
        'IMPORTED' => vm_hash['TEMPLATE']['IMPORTED'].nil? ? 'NO' : 'YES'
    }
rescue => e
    return e.message
end

#get_vm_ds(vmid) ⇒ String | nil

Returns datastore name, where VM has been deployed

Examples:

=> String('example-ds-vcenter') => Host was found
=> nil => Host wasn't found

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (String | nil)


107
108
109
110
111
112
113
114
# File 'lib/useful_things/main.rb', line 107

def get_vm_ds vmid
    onblock(:vm, vmid, @client) do | vm |
        h = vm.to_hash!['VM']["HISTORY_RECORDS"]['HISTORY'] # Searching hostname at VM allocation history
        return h['DS_ID'] if h.class == Hash # If history consists of only one line - returns it
        return h.last['DS_ID'] if h.class == Array # If history consists of 2 or more lines - returns last
        nil # Returns NilClass if did not found anything - possible if vm is at HOLD or PENDING state
    end
end

#get_vm_host(vm, hid = false) ⇒ String | nil

Returns host name, where VM has been deployed

Examples:

=> String('example-node-vcenter') => Host was found
=> nil => Host wasn't found

Parameters:

  • vm (Integer)
    • VM ID

  • hid (Boolean) (defaults to: false)
    • returns host id if true

Returns:

  • (String | nil)


93
94
95
96
97
98
99
100
# File 'lib/useful_things/main.rb', line 93

def get_vm_host vm, hid = false
      vm = onblock(:vm, vm, @client) if vm.class == Fixnum
      history = vm.to_hash!['VM']["HISTORY_RECORDS"]['HISTORY'] # Searching hostname at VM allocation history
      history = history.last if history.class == Array # If history consists of 2 or more lines - returns last
      return hid ? [history['HOSTNAME'], history['HID']] : history['HOSTNAME']
rescue
      return nil # Returns NilClass if did not found anything - possible if vm is at HOLD or PENDING state
end

#get_vm_hotadd_conf(vmid, 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:

  • vmid (Integer)

    VM ID

  • name (String) (defaults to: nil)

    VM name on vCenter node

Returns:

  • (Hash | String)

    Returns limits Hash if success or exception message if fails



284
285
286
# File 'lib/useful_things/main.rb', line 284

def get_vm_hotadd_conf(vmid, name = nil)
    onblock(:vm, vmid).hotAddEnabled? name
end

#get_vms_by_uid(uid) ⇒ Array<Hash>

Returns user vms by user id

Examples:

=> [{:id => ..., :name => ...}, {:id => ..., :name => ...}, ...]

Parameters:

  • uid (Integer)
    • owner id

Returns:



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/useful_things/main.rb', line 40

def get_vms_by_uid(uid)
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'get_vm_by_uid') }
    vmp, vms = VirtualMachinePool.new(@client), []
    vmp.info_all!
    vmp.each do | vm |
        vms << { :id => vm.id.to_i, :name => vm.name } if vm.uid(false) == uid
    end
    vms
end

#GetAnsiblePlaybook(id) ⇒ Hash

Returns playbook from DB by id

Parameters:

  • id (Fixnum)
    • Playbook id in DB

Returns:

  • (Hash)

    Playbook data



99
100
101
# File 'modules/ansible/main.rb', line 99

def GetAnsiblePlaybook id
    AnsiblePlaybook.new(id:id).to_hash
end

#GetAnsiblePlaybook_ControllerRunnable(id, vars = {}) ⇒ Hash

Returns playbook in AnsibleController acceptable form

Parameters:

  • id (Fixnum)

Returns:



133
134
135
# File 'modules/ansible/main.rb', line 133

def GetAnsiblePlaybook_ControllerRunnable id, vars = {}
    AnsiblePlaybook.new(id:id).runnable vars
end

#GetAnsiblePlaybookProcess(id) ⇒ Hash

Returns AnsblePlaybook run Process by id as Hash with humanreadable state

Parameters:

  • id (Fixnum)
    • Process id

Returns:



167
168
169
# File 'modules/ansible/main.rb', line 167

def GetAnsiblePlaybookProcess id
    AnsiblePlaybookProcess.new(proc_id:id).human
end

#GetAnsiblePlaybookVariables(id) ⇒ Hash

Returns variables from playbook(from vars section in playbook body)

Parameters:

  • id (Fixnum)

Returns:

  • (Hash)

    Variables with default values



127
128
129
# File 'modules/ansible/main.rb', line 127

def GetAnsiblePlaybookVariables id
    AnsiblePlaybook.new(id:id).vars        
end

#getglogObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns current server session LOG



275
276
277
# File 'lib/useful_things/main.rb', line 275

def getglog
    $log
end

#GetIP(vm_ref, private_allowed = false) ⇒ String

Returns VM's IP by ID

Parameters:

  • vm_ref (Integer)
    • VM ID

Returns:

  • (String)

    IP address



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/vminfo/main.rb', line 22

def GetIP(vm_ref, private_allowed = false)
    vm = case vm_ref
         when OpenNebula::VirtualMachine
            vm_ref.to_hash
         when Fixnum, String
            onblock(:vm, vm_ref).to_hash!
         when Hash
            vm_ref
         end['VM']
    begin
        # If VM was created using OpenNebula template
        nic = vm['TEMPLATE']['NIC']
        if nic.class == Hash then
            nic = [ nic ]
        elsif nic.class != Array then
            raise
        end
        nic.map! { |el| IPAddr.new el['IP'] }
        nic.delete_if { |el| !(el.ipv4? && (!el.local? || private_allowed)) }
        nic.map! { |el| el.to_s}
        
        return nic.size == 1 ? nic.last : nic
    rescue # If not, this action will raise HashRead exception
    end
    begin
        # Also IP can be stored at the another place in monitoring, but here all IP's are stored 
        ips = vm['MONITORING']['GUEST_IP_ADDRESSES'].split(',').map! { |ip| IPAddr.new ip }
        return ips.detect { |ip| ip.ipv4? && (!ip.local? || private_allowed) }.to_s
    rescue
    end
    begin
        # If VM was imported correctly, IP address will be readed by the monitoring system
        ip = IPAddr.new vm['MONITORING']['GUEST_IP']
        # Monitoring can read IPv6 address, so let us make the check
        return ip.to_s if ip.ipv4? && (!ip.local? || private_allowed)
    rescue
    end
    return ""
end

#GetSnapshotList(vmid) ⇒ Array<Hash> | Hash

Getting snapshot list for given VM

Parameters:

  • vmid (Integer)
    • VM ID

Returns:



139
140
141
142
143
144
145
146
# File 'lib/vminfo/main.rb', line 139

def GetSnapshotList(vmid)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'GetSnapshotList') }
         
    onblock(:vm, vmid).list_snapshots
end

#GetStatistics(params = {}) ⇒ Object

Returns calls statisctics



30
31
32
33
34
35
36
37
38
39
# File 'modules/stat/main.rb', line 30

def GetStatistics(params = {})
    return JSON.pretty_generate($data) if params['method'].nil? && params['json'] == true
    return $data if params['method'].nil?
    begin
        return JSON.pretty_generate($data[params['method']]) if params['json'] == true
        $data[params['method']]
    rescue => e
        e.message
    end
end

#GetUserInfo(userid) ⇒ String

Returns User template in XML

Parameters:

  • userid (Integer)

Returns:

  • (String)

    XML



194
195
196
197
198
199
200
201
202
203
# File 'lib/useful_things/main.rb', line 194

def GetUserInfo(userid)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'GetUserInfo') }
    onblock(:u, userid) do |user|
        user.info!
        user.to_xml
    end
end

#GetvCenterIOpsConfObject

Returns current IOps conf from `/etc/one/ione.conf`



327
328
329
# File 'lib/useful_things/main.rb', line 327

def GetvCenterIOpsConf
    $ione_conf['vCenter']['drives-iops']
end

#GetVMIDbyIP(ip) ⇒ Integer | nil

Getting VM ID by IP

Parameters:

  • ip (String)
    • IP address

Returns:

  • (Integer | nil)
    • VM ID if found, nil if not



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/vminfo/main.rb', line 64

def GetVMIDbyIP(ip)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'GetVMIDbyIP') }
    vm_pool = VirtualMachinePool.new(@client)
    vm_pool.info_all!
    vm_pool.each do |vm|
        break if nil
        begin
            return vm.id if ip.chomp == GetIP(vm.id).chomp
        rescue
        end
    end
    nil
end

#HostsMonitoringArray<Hash>

Returns monitoring information about nodes

Examples:

HostsMonitoring() => {"id"=>0, "name"=>"vCloud", "full_size"=>"875.76GB", "reserved"=>"636.11GB", "running_vms"=>179, "cpu"=>"16.14%"}

Returns:



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
# File 'lib/useful_things/main.rb', line 244

def HostsMonitoring()
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'HostsMonitoring') }

    # @!visibility private
    # Converts MB to GB
    def sizeConvert(mb)
        if mb.to_f / 1048576 > 768 then
            return "#{(mb.to_f / 1073741824.0).round(2).to_s}TB"
        else
            return "#{(mb.to_f / 1048576.0).round(2).to_s}GB" 
        end
    end

    host_pool, mon = HostPool.new(@client), []
    host_pool.info!
    host_pool.each do | host |
        host = host.to_hash['HOST']
        mon << { 
            :id => host['ID'].to_i, :name => host['NAME'], :full_size => sizeConvert(host.to_hash['HOST_SHARE']['TOTAL_MEM']),
            :reserved => sizeConvert(host.to_hash['HOST_SHARE']['MEM_USAGE']),
            :running_vms => host.to_hash['HOST_SHARE']['RUNNING_VMS'].to_i,
            :cpu => "#{(host.to_hash['HOST_SHARE']['USED_CPU'].to_f / host.to_hash['HOST_SHARE']['TOTAL_CPU'].to_f * 100).round(2).to_s}%"
        }
    end
    mon
end

#IaaS_Gate(params) ⇒ Object

Does very complicated things, don't think about it)))))

Parameters:

Options Hash (params):

  • 'uid' (Integer)
    • UserID

  • 'time' (Integer)
    • Start point to collect Showback data

  • 'vms' (Array<Integer>)
    • VMs filter

  • 'balance' (Float)
    • New balance for User



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/accounting/main.rb', line 59

def IaaS_Gate params
    params['vms'] = params['vms'] || []
    showback = CalculateShowback(*params.get('uid', 'time'))

    user = onblock :u, params['uid']
    user.balance = params['balance']
    balance = user.balance
    alert, alert_at = user.alert

    return {
        'showback' => showback,
        'balance'  => balance,
        'alert'    => alert,
        'alert_at' => alert_at
    }
rescue OpenNebula::VirtualMachine::ShowbackError => e
    return {
        'error'    => e.message,
        'time'     => e.params,
        'type'     => e.class
    }
rescue OpenNebula::User::UserNotExistsError => e
    return {
        'error'    => e.message,
        'uid'      => params['uid'],
        'type'     => e.class
    }
end

#IaaS_Gate_new(params) ⇒ Object

Does more complicated things, don't think about it)))))



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/accounting/main.rb', line 88

def IaaS_Gate_new params
    LOG_DEBUG params
    response = []

    params["users"].each do | u |
        u['vms'] = u['vms'] || []
        showback = CalculateShowback(u['uid'], u['time'])
        
        user = onblock :u, u['uid']
        user.balance = u['balance']
        balance = user.balance
        alert, alert_at = user.alert

        response << {
            'showback' => showback,
            'balance'  => balance,
            'alert'    => alert,
            'alert_at' => alert_at
        }
    end

    return response
rescue OpenNebula::VirtualMachine::ShowbackError => e
    return {
        'error'    => e.message,
        'time'     => e.params,
        'type'     => e.class
    }
rescue OpenNebula::User::UserNotExistsError => e
    return {
        'error'    => e.message,
        'uid'      => params['uid'],
        'type'     => e.class
    }
end

#IMPORT(params) ⇒ Object

Imports wild VM



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/data_import_handler/main.rb', line 4

def IMPORT(params)
    LOG_DEBUG params
    # return nil
    if params.class == Hash
        begin
        userid = UserCreate(params['username'], params['password'])
        if userid == 0 then
            up = UserPool.new(@client)
            up.info_all!
            up.each do |u|
                if u.name == params['username'] then
                    userid = u.id
                    break
                end
            end
        end
        params['vmid'] = GetVMIDbyIP(params['ip']) if params['vmid'].nil?
        return { params['serviceid'].to_s => [userid, nil] } if params['vmid'].nil?
        vm = get_pool_element(VirtualMachine, params['vmid'], @client)
        vm.chown(userid, USERS_GROUP)
        user = User.new(User.build_xml(userid), @client)
        used = vm.to_hash!['VM']['TEMPLATE']
        user_quota = user.to_hash!['USER']['VM_QUOTA']
        begin
            user.set_quota(
                "VM=[
                CPU=\"#{(used['CPU'].to_i + user_quota['CPU_USED'].to_i).to_s}\", 
                MEMORY=\"#{(used['MEMORY'].to_i + user_quota['MEMORY_USED'].to_i).to_s}\", 
                SYSTEM_DISK_SIZE=\"-1\", 
                VMS=\"#{(user_quota['VMS_USED'].to_i + 1).to_s}\" ]")
        rescue
        end
        vm.rename("user_#{params['serviceid'].to_s}_vm")
        return { params['serviceid'].to_s => [userid, params['vmid']] }
        rescue
            LOG_DEBUG params
            LOG_DEBUG userid
        end
    end
    params.map! do |el|
        el = IMPORT(el)
    end
end

#LCM_STATE(vmid) ⇒ Integer

Getting VM LCM state number by ID

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (Integer)

    State



95
96
97
# File 'lib/vminfo/main.rb', line 95

def LCM_STATE(vmid)
    onblock(:vm, vmid.to_i).lcm_state!
end

#LCM_STATE_STR(vmid) ⇒ String

Getting VM LCM state string by ID

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (String)

    State



101
102
103
# File 'lib/vminfo/main.rb', line 101

def LCM_STATE_STR(vmid)
    onblock(:vm, vmid.to_i).lcm_state_str!
end

#ListAnsiblePlaybookProcessesArray<AnsiblePlaybookProcess>

Returns all AnsiblePlaybook Processes as Array of Hashes



196
197
198
# File 'modules/ansible/main.rb', line 196

def ListAnsiblePlaybookProcesses
    AnsiblePlaybookProcess.list
end

#ListAnsiblePlaybooksArray<Hash>

Returns all playbooks from DB

Returns:



138
139
140
# File 'modules/ansible/main.rb', line 138

def ListAnsiblePlaybooks
    AnsiblePlaybook.list
end

#locks_stat(key = nil) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns thread locks stats



9
10
11
12
13
14
15
# File 'lib/server/main.rb', line 9

def locks_stat(key = nil)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'locks_stat') }
    $thread_locks
end

#log(msg) ⇒ String

Logs given message to ione.log

Parameters:

  • msg (String)
    • your message

Returns:

  • (String)

    returns given message



156
157
158
159
160
# File 'service/log.rb', line 156

def log(msg)
    LOG_STAT()        
    LOG(msg, "RemoteLOG")
    msg
end

#MKSnapshot(vmid, name, log = true) ⇒ Integer | OpenNebula::Error

Making new snapshot for given VM with given name

Parameters:

  • vmid (Integer)
    • VM ID

  • name (String)
    • Name for new VM

  • log (Boolean) (defaults to: true)
    • Making no logs if false

Returns:

  • (Integer | OpenNebula::Error)

    New snapshot ID



300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/vmcontrol/main.rb', line 300

def MKSnapshot(vmid, name, log = true)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'MKSnapshot') }

    LOG "Snapshot create-query accepted", 'SnapController' if log
    vm = onblock :vm, vmid
    r = vm.info!
    raise r if OpenNebula.is_error? r
    vm.snapshot_create(name)
rescue => e
    return e.message
end

#procObject

Returns active processes list



35
36
37
# File 'lib/server/main.rb', line 35

def proc
    $PROC
end

#Reboot(vmid, hard = false) ⇒ Object

Reboots Virtual Machine

Parameters:

  • vmid (Integer)
    • VirtualMachine ID to reboot

  • hard (Boolean) (defaults to: false)
    • uses reboot-hard if true

Returns:

  • nil



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/vmcontrol/main.rb', line 159

def Reboot(vmid, hard = false)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Reboot') }
              
    return "VMID cannot be nil!" if vmid.nil?     
    LOG "Rebooting VM#{vmid}", "Reboot"
    LOG "Params: vmid = #{vmid}, hard = #{hard}", "DEBUG" #if DEBUG
    vm = onblock :vm, vmid
    r = vm.info!
    raise r if OpenNebula.is_error? r
    vm.reboot(hard) # reboots 'hard' if true
rescue => e
    return e.message
end

#Reinstall(params, trace = ["Reinstall method called:#{__LINE__}"]) ⇒ Hash, ...

Creates VM for Old OpenNebula account and with old IP address

Examples:

Example out

Success: { 'vmid' => 124, 'vmid_old' => 123, 'ip' => '0.0.0.0', 'ip_old' => '0.0.0.0' }
Some params not given: String('ReinstallError - some params are nil')
Debug turn method off: nil
Debug return fake data: { 'vmid' => rand(params['vmid'].to_i + 1000), 'vmid_old' => params['vmid'], 'ip' => '0.0.0.0', 'ip_old' => '0.0.0.0' } 

Parameters:

  • params (Hash)
    • all needed data for VM reinstall

  • trace (Array<String>) (defaults to: ["Reinstall method called:#{__LINE__}"])
    • public trace log

Options Hash (params):

  • :vmid (Integer)
    • VirtualMachine for Reinstall ID

  • :userid (Integer)
    • new Virtual Machine owner

  • :groupid (Integer)
    • new Virtual Machine group

  • :username (String)
    • Administrator username for Windows Machines

  • :passwd (String)

    Password for new Virtual Machine

  • :templateid (Integer)
    • templateid for Instantiate

  • :cpu (Integer)

    vCPU cores amount for new VM

  • :iops (Integer)

    IOPS limit for new VM's drive

  • :units (String)

    Units for RAM and drive size, can be 'MB' or 'GB'

  • :ram (Integer)

    RAM size for new VM

  • :drive (Integer)

    Drive size for new VM

  • :ds_type (String)

    VM deploy target datastore drives type, 'SSD' ot 'HDD'

  • :release (Bool) — default: false

    VM will be started on HOLD if false

Returns:

  • (Hash, nil, String)


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/creative_funcs/main.rb', line 59

def Reinstall(params, trace = ["Reinstall method called:#{__LINE__}"])
    LOG_STAT()
        params.to_s!
        LOG_DEBUG params.merge!({ :method => 'Reinstall' }).debug_out
        return nil if params['debug'] == 'turn_method_off'
        return { 'vmid' => rand(params['vmid'].to_i + 1000), 'vmid_old' => params['vmid'], 'ip' => '0.0.0.0', 'ip_old' => '0.0.0.0' } if params['debug'] == 'data'   

        LOG "Reinstalling VM#{params['vmid']}", 'Reinstall'
        trace << "Checking params:#{__LINE__ + 1}"
        if params.get('vmid', 'groupid', 'userid', 'templateid').include?(nil) then
            LOG "ReinstallError - some params are nil", 'Reinstall'
            LOG_DEBUG params.get('vmid', 'groupid', 'userid', 'templateid')
            return "ReinstallError - some params are nil", params
        end
        params['vmid'], params['groupid'], params['userid'], params['templateid'] = params.get('vmid', 'groupid', 'userid', 'templateid').map { |el| el.to_i }
        
        params['cpu'], params['ram'], params['drive'], params['iops'] = params.get('cpu', 'ram', 'drive', 'iops').map { |el| el.to_i }
        
        begin
            params['iops'] = $ione_conf['vCenter']['drives-iops'][params['ds_type']]
            LOG_DEBUG "IOps: #{params['iops'].class.to_s}(#{params['iops']})"
        rescue
            LOG_DEBUG "No vCenter configuration found"
        end
        
        params['username'] = params['username'] || 'Administrator'
        trace << "Checking template:#{__LINE__ + 1}"
        template = onblock(:t, params['templateid']) do | t |
            result = t.info!
            if result != nil then
                LOG_ERROR "Error: TemplateLoadError" 
                return {'error' => "TemplateLoadError", 'trace' => (trace << "TemplateLoadError:#{__LINE__ - 3}")}
            end
            params['extra'] = params['extra'] || {'type' => t['/VMTEMPLATE/TEMPLATE/HYPERVISOR']}
            t
        end
        win = template.win?

        LOG_DEBUG 'Initializing vm object'
        trace << "Initializing old VM object:#{__LINE__ + 1}"            
        vm = onblock(:vm, params['vmid'])
        LOG_DEBUG 'Collecting data from old template'
        trace << "Collecting data from old template:#{__LINE__ + 1}"            
        context = vm.to_hash!['VM']['TEMPLATE']
        
        LOG_DEBUG 'Generating new template'
        trace << "Generating credentials and network context:#{__LINE__ + 1}"
        context['CONTEXT'] = {
            'PASSWORD' => params['passwd'],
            'NETWORK' => context['CONTEXT']['NETWORK'],
            'SSH_PUBLIC_KEY' => context['CONTEXT']['SSH_PUBLIC_KEY']
        }
        context['CONTEXT']['USERNAME'] = params['username'] if win
        context['NIC'] = [context['NIC']] if context['NIC'].class == Hash
        context['NIC'].map! do |nic| 
            nic.without(
                'TARGET', 'MAC', 'NAME', 'SECURITY_GROUPS',
                'BRIDGE', 'BRIDGE_TYPE', 'NIC_ID', 'VN_MAD',
                'CLUSTER_ID', 'AR_ID', 'NETWORK', 'NETWORK_UNAME'
            )
        end
        context['NIC'] = context['NIC'].last if context['NIC'].size == 1
        trace << "Generating specs configuration:#{__LINE__ + 1}"
        context.merge!({
            "VCPU" => params['cpu'],
            "MEMORY" => params['ram'] * (params['units'] == 'GB' ? 1024 : 1),
            "DRIVE" => params['ds_type'],
            "DISK" => {
                "IMAGE_ID" => template.to_hash['VMTEMPLATE']['TEMPLATE']['DISK']['IMAGE_ID'],
                "SIZE" => params['drive'] * (params['units'] == 'GB' ? 1024 : 1),
                "OPENNEBULA_MANAGED" => "NO"
            }
        })
        context['TEMPLATE_ID'] = params['templateid']

        context = context.without('GRAPHICS').to_one_template
        LOG_DEBUG "Resulting capacity template:\n#{context}"
        
        trace << "Terminating VM:#{__LINE__ + 1}"            
        vm.terminate(true)
        LOG_COLOR 'Waiting until terminate process will over', 'Reinstall', 'light_yellow'
        trace << ":#{__LINE__ + 1}"            
        until STATE_STR(params['vmid']) == 'DONE' do
            sleep(0.2)
        end if params['release']
        LOG_COLOR "Terminate process is over, new VM is deploying now", 'Reinstall', 'green'
        LOG_DEBUG 'Creating new VM'
        trace << "Instantiating template:#{__LINE__ + 1}"
        vmid = template.instantiate(
            ( params['login'] || onblock(:u, params['userid']){ |u| u.info!; u.name }) + '_vm', false, context)

        LOG_DEBUG "New VM ID or an OpenNebula::Error: #{begin vmid.to_str rescue vmid.to_s end}"
        begin    
            if vmid.class != Fixnum && vmid.include?('IP/MAC') then
                trace << "Retrying template instantiation:#{__LINE__ + 1}"                
                sleep(3)
                vmid = template.instantiate(params['login'] + '_vm', false, context)
            end
        rescue => e
            return vmid.class, vmid.message if vmid.class != Fixnum
            return vmid.class
        end           

        return vmid.message if vmid.class != Fixnum

        trace << "Changing VM owner:#{__LINE__ + 1}"
        onblock(:vm, vmid).chown(params['userid'], USERS_GROUP)

        #####   PostDeploy Activity define   #####
        Thread.new do

            host =  if params['host'].nil? then
                JSON.parse(@db[:settings].as_hash(:name, :body)['NODES_DEFAULT'])[params['extra']['type'].upcase]
            else
                params['host']
            end

            vm = onblock(:vm, vmid)
            LOG_DEBUG "Deploying VM to the host ##{host}"
            vm.deploy(host, false, ChooseDS(params['ds_type']))
            LOG_DEBUG 'Waiting until VM will be deployed'
            vm.wait_for_state

            postDeploy = PostDeployActivities.new @client

            #TrialController
            if params['trial'] then
                trace << "Creating trial counter thread:#{__LINE__ + 1}"
                postDeploy.TrialController(params, vmid, host)
            end
            #endTrialController
            #AnsibleController
            
            if params['ansible'] && params['release'] then
                trace << "Creating Ansible Installer thread:#{__LINE__ + 1}"
                postDeploy.AnsibleController(params, vmid, host)
            end

            #endAnsibleController

        end if params['release']
        ##### PostDeploy Activity define END #####

        return { 'vmid' => vmid, 'vmid_old' => params['vmid'], 'ip' => GetIP(vmid, true), 'ip_old' => GetIP(vm) }
rescue => e
    LOG_ERROR "Error ocurred while Reinstall: #{e.message}"
    return e.message, trace
end

#ReinstallTest(params, trace = []) ⇒ Object

Reinstall method based on vm.recover(recreate)

Parameters:

  • params (Hash)
  • trace (Array) (defaults to: [])

Options Hash (params):

  • vmid (Integer)
  • templateid (Integer)
  • cpu (Integer)
    • CPU cores

  • ram (Integer)
    • RAM in MB or GB depending on 'units'

  • units (String)
    • GB or MB

  • ds_type (String)
    • Datastore type to choose from, e.g. SSD/HDD



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/creative_funcs/main.rb', line 216

def ReinstallTest params, trace = []
    vmid = params['vmid']
    
    vm = onblock :vm, vmid

    vm.info!
    raise "Multi-disk VMs aren't supported" if vm.to_hash['VM']['TEMPLATE']['DISK'].class != Hash

    # Deleting old VM
    vm.recover 4
    vm.wait_for_state 1, 0
    vm.info!

    # Getting VM template
    body = @db[:vm_pool].where(oid: vmid).select(:body).to_a.last[:body]
    body = Nokogiri::XML(body)
    body_old = body.clone

    # Collecting data
    host = get_vm_host vm, true
    template = onblock :t, params['templateid']
    template.info!
    img = onblock :i, template['/VMTEMPLATE/TEMPLATE/DISK/IMAGE_ID']
    img.info!
    ds = onblock :ds, img['/IMAGE/DATASTORE_ID']
    ds.info!

    modify = {
        '//DEPLOY_ID' => '',
        '//TEMPLATE/VCPU' => params['cpu'],
        '//TEMPLATE/MEMORY' => params['ram'] * (params['units'] == 'GB' ? 1024 : 1),
        '//TEMPLATE/TEMPLATE_ID' => params['templateid'],
        '//TEMPLATE/DISK/CLUSTER_ID' => ds.to_hash['DATASTORE']['CLUSTERS']['ID'].join(','),
        '//TEMPLATE/DISK/DATASTORE' => ds.name,
        '//TEMPLATE/DISK/DATASTORE_ID' => ds.id,
        '//TEMPLATE/DISK/IMAGE' => img.name,
        '//TEMPLATE/DISK/IMAGE_ID' => img.id,
        '//TEMPLATE/DISK/SOURCE' => img['/IMAGE/SOURCE']
    }
    remove = [
        # '//TEMPLATE/DISK'
    ]
    
    modify.each do | at, to |
        body.at(at).content = to
    end
    remove.each do | at |
        body.at(at).remove unless body.at(at).nil?
    end

    # disk_node = Nokogiri::XML::Node.new("DISK", body)
    # disk_attrs = {
    #     'IMAGE_ID' => img.id,
    #     'SIZE' => params['drive'] * (params['units'] == 'GB' ? 1024 : 1),
    #     'OPENNEBULA_MANAGED' => 'NO',
    #     'VCENTER_DS_REF' => ds['/DATASTORE/TEMPLATE/VCENTER_DS_REF'],
    #     'VCENTER_INSTANCE_ID' => ds['/DATASTORE/TEMPLATE/VCENTER_INSTANCE_ID'],
    #     'SOURCE' => img['/IMAGE/SOURCE'],
    #     'DATASTORE_ID' => ds.id,

    # }
    # disk_attrs.each do | attr, val |
    #     node = Nokogiri::XML::Node.new(attr, body)
    #     node.content = val
    #     disk_node.add_child node
    # end

    # body.at('//TEMPLATE').add_child(disk_node)

    puts body = body.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XML | Nokogiri::XML::Node::SaveOptions::NO_DECLARATION | Nokogiri::XML::Node::SaveOptions::NO_EMPTY_TAGS).strip
 
    unless Nokogiri::XML(body).errors.empty?
        puts body
        raise "XML-build failed"
    end

    @db[:vm_pool].where(oid: vmid).update(body: body)

    vm.deploy(host.last, false, ChooseDS(params['ds_type']))

    return { 'vmid' => vmid, 'ip' => GetIP(vmid, true), 'old_body' => body_old }
end

#Resume(vmid, trial = false) ⇒ nil | OpenNebula::Error

Powers On given VM if powered off, or unsuspends if suspended by ID

Parameters:

  • vmid (Integer)

Returns:

  • (nil | OpenNebula::Error)


266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/vmcontrol/main.rb', line 266

def Resume(vmid, trial = false)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Resume') }

    onblock(:vm, vmid.to_i) do | vm |
        r = vm.info!
        raise r if OpenNebula.is_error? r
        vm.unschedule(0) if trial
        vm.resume
    end
rescue => e
    return e.message
end

#RevSnapshot(vmid, snapid, log = true) ⇒ nil | OpenNebula::Error

Reverts choosen snapshot for given VM

Parameters:

  • vmid (Integer)
    • VM ID

  • snapid (Integer)
    • Snapshot ID

  • log (Boolean) (defaults to: true)
    • Making no logs if false

Returns:

  • (nil | OpenNebula::Error)


319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/vmcontrol/main.rb', line 319

def RevSnapshot(vmid, snapid, log = true)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'RevSnapshot') }
    
    LOG "Snapshot revert-query accepted", 'SnapController' if log
    vm = onblock :vm, vmid
    r = vm.info!
    raise r if OpenNebula.is_error? r
    vm.snapshot_revert(snapid.to_i)
rescue => e
    return e.message
end

#RMSnapshot(vmid, snapid, log = true) ⇒ nil | OpenNebula::Error

Removes choosen snapshot for given VM

Parameters:

  • vmid (Integer)
    • VM ID

  • snapid (Integer)
    • Snapshot ID

  • log (Boolean) (defaults to: true)
    • Making no logs if false

Returns:

  • (nil | OpenNebula::Error)


286
287
288
289
290
291
292
293
294
# File 'lib/vmcontrol/main.rb', line 286

def RMSnapshot(vmid, snapid, log = true)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'RMSnapshot') }

    LOG "Deleting snapshot(ID: #{snapid.to_s}) for VM#{vmid.to_s}", "SnapController" if log
    onblock(:vm, vmid.to_i).snapshot_delete(snapid.to_i)
end

#RunAnsiblePlaybookProcess(id) ⇒ NilClass | Thread

Runs given AnsiblePlaybookProcess in PENDING state

Parameters:

  • id (Fixnum)
    • Process id

Returns:

  • (NilClass | Thread)
    • returns Thread if everything's fine, nil if wrong state



179
180
181
# File 'modules/ansible/main.rb', line 179

def RunAnsiblePlaybookProcess id
    AnsiblePlaybookProcess.new(proc_id:id).run
end

#set_vm_hotadd_conf(params) ⇒ true | String

Sets resources hot add settings

Parameters:

Options Hash (params):

  • :vmid (Boolean)

    VM ID

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

    VM name on vCenter node

Returns:

  • (true | String)


294
295
296
297
# File 'lib/useful_things/main.rb', line 294

def set_vm_hotadd_conf(params)
    params.to_sym!
    onblock(:vm, params[:vmid]).hotResourcesControlConf(params)
end

#SetVMResourcesLimits(vmid, host, params) ⇒ Object

temp



335
336
337
# File 'lib/vmcontrol/main.rb', line 335

def SetVMResourcesLimits vmid, host, params
    PostDeployActivities.new(@client).LimitsController(params, vmid, host)
end

#Shutdown(vmid) ⇒ nil | OpenNebula::Error

Note:

Don't use OpenNebula::VirtualMachine#shutdown - thoose method deletes VM's

Powering off VM

Parameters:

  • vmid (Integer)
    • VM to shutdown

Returns:

  • (nil | OpenNebula::Error)


218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/vmcontrol/main.rb', line 218

def Shutdown(vmid)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Shutdown') }
            
    LOG "Shutting down VM#{vmid}", "Shutdown"
    vm = onblock :vm, vmid
    r = vm.info!
    raise r if OpenNebula.is_error? r
    vm.poweroff
rescue => e
    return e.message
end

#STATE(vmid) ⇒ Integer

Getting VM state number by ID

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (Integer)

    State



83
84
85
# File 'lib/vminfo/main.rb', line 83

def STATE(vmid) 
    onblock(:vm, vmid.to_i).state!
end

#STATE_STR(vmid) ⇒ String

Getting VM state string by ID

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (String)

    State



89
90
91
# File 'lib/vminfo/main.rb', line 89

def STATE_STR(vmid)
    onblock(:vm, vmid.to_i).state_str!
end

#Suspend(params, log = true, trace = ["Suspend method called:#{__LINE__}"]) ⇒ NilClass | Array

Suspends VirtualMachine and makes it uncontrollable for Owner(except Admins)

Parameters:

  • params (Hash)
    • income data

  • log (Boolean) (defaults to: true)
    • logs process if true

  • trace (Array<String>) (defaults to: ["Suspend method called:#{__LINE__}"])

Options Hash (params):

  • :vmid (Integer)

    VirtualMachine ID for blocking

Returns:



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/vmcontrol/main.rb', line 13

def Suspend(params, log = true, trace = ["Suspend method called:#{__LINE__}"])
    trace << "Generating sys objects:#{__LINE__ + 1}"
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Suspend') }
    begin
        trace << "Printing debug info:#{__LINE__ + 1}"
        LOG "Suspending VM#{params['vmid']}", "Suspend" if log
        LOG "Params: #{params.inspect} | log = #{log}", "Suspend" if log
        trace << "Creating VM object:#{__LINE__ + 1}"
        onblock(:vm, params['vmid'].to_i) do | vm |
            r = vm.info!
            raise r if OpenNebula.is_error? r
            begin
                trace << "Suspending VM:#{__LINE__ + 1}"
                vm.suspend
            rescue
                trace << "Some exception raised while suspending VM:#{__LINE__ - 2}"
                LOG_AUTO "VM wasn't suspended, but rights will be changed" if log
            end
            trace << "Changing user rights:#{__LINE__ + 1}"
            vm.chmod(
                -1,  0, -1,
                -1, -1, -1,
                -1, -1, -1
                )
        end
        trace << "Killing proccess:#{__LINE__ + 1}"
        0
    rescue => e
        return e.message, trace
    end
end

#SuspendUser(uid, vms = []) ⇒ NilClass

Suspends all given users VMs

Parameters:

  • uid (Integer)
    • User ID

  • vms (Array) (defaults to: [])
    • VMs filter

Returns:



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/vmcontrol/main.rb', line 61

def SuspendUser uid, vms = []
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'SuspendUser') }
    LOG "Suspend Query for User##{uid} received", "Suspend"

    user = onblock :u, uid
    user.vms(@db).each do | vm |
        next if vms.include? vm.id
        begin
            LOG "Suspending VM##{vm.id}", "Suspend"
            vm.chmod(
                -1,  0, -1,
                -1, -1, -1,
                -1, -1, -1  )
            vm.suspend
        rescue => e
            LOG "Error occured while suspending VM##{vm.id}\nCheck Debug log for error-codes and backtrace", "Suspend"
            LOG_DEBUG e.message
            LOG_DEBUG e.backtrace
        end
    end

    nil
rescue => e
    return e.message
end

#SuspendVM(vmid) ⇒ NilClass

Suspends VirtualMachine only

Parameters:

  • vmid (Integer)
    • VirtualMachine ID

Returns:



50
51
52
53
54
55
56
# File 'lib/vmcontrol/main.rb', line 50

def SuspendVM(vmid)
    r = vm.info!
    raise r if OpenNebula.is_error? r
    onblock(:vm, vmid.to_i).suspend
rescue => e
    return e.message
end

#Terminate(userid, vmid) ⇒ nil | OpenNebula::Error

Terminates(deletes) user account and VM

Parameters:

  • userid (Integer)
    • user to delete

  • vmid (Integer)
    • VM to delete

Returns:

  • (nil | OpenNebula::Error)


179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/vmcontrol/main.rb', line 179

def Terminate(userid, vmid)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Terminate') }
              
    LOG "Terminate query call params: {\"userid\" => #{userid}, \"vmid\" => #{vmid}}", "Terminate"
    # If userid will be nil oneadmin account can be broken
    if userid == nil || vmid == nil then
        LOG "Terminate query rejected! 1 of 2 params is nilClass!", "Terminate"
        return 1
    elsif userid == 0 then
        LOG "Terminate query rejected! Tryed to delete root-user(oneadmin)", "Terminate"
    end
    Delete(userid)
    LOG "Terminating VM#{vmid}", "Terminate"
    vm = onblock(:vm, vmid)
    r = vm.info!
    raise r if OpenNebula.is_error? r
    Thread.new do
        begin
            rc = vm.resume
            raise rc if OpenNebula.is_error? rc
            vm.wait_for_state
        rescue
        ensure
            vm.recover(4)
            vm.wait_for_state 1, 0
            vm.terminate(true)
        end
    end
    true
rescue => err
    return err.messages
end

#Test(msg, log = "Test") ⇒ String('DONE') | String('PONG')

Logs sent message into ione.log and gives data about availability

Examples:

ZmqJsonRpc::Client.new(uri, 50).Test('PING') => 'PONG' -> Service available
                                             => Exception -> Service down

Parameters:

  • msg (String)
    • message to log

Returns:

  • (String('DONE') | String('PONG'))


8
9
10
11
12
13
14
15
16
17
# File 'lib/useful_things/main.rb', line 8

def Test(msg, log = "Test")
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Test') }
    LOG "Test message received, text: #{msg}", log if msg != 'PING'
    if msg == "PING" then
        return "PONG"
    end
    "DONE"
end

#Unsuspend(params, trace = ["Resume method called:#{__LINE__}"]) ⇒ nil | Array

Note:

May be used as PowerON method like #Resume

Unsuspends VirtualMachine and makes it uncontrollable for Owner(except Admins)

Parameters:

  • params (Hash)
    • income data

  • trace (Array<String>) (defaults to: ["Resume method called:#{__LINE__}"])

Options Hash (params):

  • :vmid (Integer)

    VirtualMachine ID for blocking

Returns:

  • (nil | Array)

    Returns message and trace if Exception



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/vmcontrol/main.rb', line 95

def Unsuspend(params, trace = ["Resume method called:#{__LINE__}"])
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Unsuspend') }
    result = 
        begin
            LOG "Resuming VM ##{params['vmid']}", "Resume"
            trace << "Creating VM object:#{__LINE__ + 1}"            
            onblock(:vm, params['vmid'].to_i) do | vm |
                r = vm.info!
                raise r if OpenNebula.is_error? r
                trace << "Resuming VM:#{__LINE__ + 1}"                
                vm.resume
                trace << "Changing user rights:#{__LINE__ + 1}"                
                vm.chmod(
                    -1,  1, -1,
                    -1, -1, -1,
                    -1, -1, -1
                )
            end
            trace << "Killing proccess:#{__LINE__ + 1}"            
            0
        rescue => e
            return e.message, trace
        end
    result
end

#UnsuspendUser(uid, vms = []) ⇒ NilClass

Unsuspends all users VMs

Parameters:

  • uid (Integer)
    • User ID

  • vms (Array) (defaults to: [])
    • VMs filter

Returns:



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
# File 'lib/vmcontrol/main.rb', line 127

def UnsuspendUser uid, vms = []
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'UnsuspendUser') }
    LOG "Unsuspend Query for User##{uid} received", "Unsuspend"

    user = onblock :u, uid
    user.vms(@db).each do | vm |
        next if vms.include? vm.id
        begin
            LOG "Unsuspending VM##{vm.id}", "Unsuspend"
            vm.chmod(
                1,  1, 1,
                -1, -1, -1,
                -1, -1, -1  )
            vm.resume
        rescue => e
            LOG "Error occured while unsuspending VM##{vm.id}\nCheck Debug log for error-codes and backtrace", "Unsuspend"
            LOG_DEBUG e.message
            LOG_DEBUG e.backtrace
        end
    end

    nil
rescue => e
    return e.message
end

#UpdateAnsiblePlaybook(args = {}) ⇒ Object

Updates playbook using given data by id

Parameters:

  • args (Hash) (defaults to: {})
    • id and keys for updates

Options Hash (args):

  • id (Fixnum)
    • ID of playbook to update (Mandatory)

  • name (String)
  • uid (Integer)
    • Owner id

  • gid (Integer)
    • Group id

  • description (String)
  • body (String)
  • extra_data (String)


111
112
113
114
115
116
117
# File 'modules/ansible/main.rb', line 111

def UpdateAnsiblePlaybook args = {}
    ap = AnsiblePlaybook.new id:args.delete('id')
    args.each do | key, value |
        ap.send(key + '=', value)
    end
    ap.update
end

#uptimeString

Returns IONe Cloud Server uptime(formated)

Returns:

  • (String)


27
28
29
30
31
32
33
# File 'lib/server/main.rb', line 27

def uptime
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'uptime') }
    fmt_time(Time.now.to_i - STARTUP_TIME)
end

#user_exists(uid) ⇒ Object

Checks if User exists



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

def user_exists uid
    onblock(:u, uid).exists?
end

#UserCreate(login, pass, groupid = nil, locale = nil, client: @client, object: false, type: 'vcenter') ⇒ Integer | Integer, OpenNebula::User

Creates new user account

Examples:

Examples

Success:                    777
    Object set to true:     777, OpenNebula::User(777)
Error:                      "[one.user.allocation] Error ...", maybe caused if user with given name already exists
Error:                      0

Parameters:

  • login (String)
    • login for new OpenNebula User

  • pass (String)
    • password for new OpenNebula User

  • groupid (Integer) (defaults to: nil)
    • Secondary group for new user

  • client (OpenNebula::Client)
  • object (Boolean)
    • Returns userid of the new User and object of new User

  • locale (String) (defaults to: nil)
    • Sets given locale for Sunstone

Returns:



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/creative_funcs/main.rb', line 15

def UserCreate(, pass, groupid = nil, locale = nil, client:@client, object:false, type:'vcenter')
    id = id_gen()
    LOG_CALL(id, true)
    defer { LOG_CALL(id, false, 'UserCreate') }
    user = User.new(User.build_xml(0), client) # Generates user template using oneadmin user object
    allocation_result =
        begin
            user.allocate(, pass, "core", groupid.nil? ? [USERS_GROUP] : [groupid]) # Allocating new user with login:pass
        rescue => e
            e.message
        end
    if !allocation_result.nil? then
        LOG_DEBUG allocation_result.message #If allocation was successful, allocate method returned nil
        return 0
    end
    attributes = "SUNSTONE=[ LANG=\"#{locale || $ione_conf['OpenNebula']['users-default-lang']}\" ]"
    attributes += "AZURE_TOKEN=\"#{}\"" if type == 'azure'
    attributes += "BALANCE=\"0\"\nLABELS=\"IaaS\"" if groupid.to_i == $db[:settings].where(:name => 'IAAS_GROUP_ID').to_a.last[:body].to_i
    user.update(attributes, true)
    return user.id, user if object
    user.id
end

#UserDelete(uid) ⇒ Object

Deletes user and all his VMs



315
316
317
318
319
320
321
322
323
324
# File 'lib/useful_things/main.rb', line 315

def UserDelete uid
    u = onblock(:u, uid)
    u.vms(@db).each do | vm |
        vm.terminate true
    end
    u.delete
    true
rescue => e
    LOG_DEBUG e.message
end

#versionString

Returns current running IONe Cloud Server version

Returns:

  • (String)


18
19
20
21
22
23
24
# File 'lib/server/main.rb', line 18

def version
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'version') }
    VERSION
end

#vm_hotadd(params) ⇒ Boolean | String

Note:

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

Resize VM without powering off the VM

Parameters:

Options Hash (params):

  • :vmid (Boolean)

    VM ID

  • :cpu (Integer)

    CPU amount to set

  • :ram (Integer)

    RAM amount in MB to set

  • :name (String)

    VM name on vCenter node

Returns:

  • (Boolean | String)


306
307
308
309
# File 'lib/useful_things/main.rb', line 306

def vm_hotadd(params)
    params.to_sym!
    onblock(:vm, params[:vmid]).hot_resize(params)
end

#VM_XML(vmid) ⇒ String

Returns VM template XML

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (String)

    XML



10
11
12
13
14
15
16
17
18
# File 'lib/vminfo/main.rb', line 10

def VM_XML(vmid)
    LOG_STAT()
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'VM_XML') }
    vm = onblock(:vm, vmid)
    vm.info! || vm.to_xml
end