Class: IONe

Inherits:
Object
  • Object
show all
Includes:
Deferable
Defined in:
server/debug_lib.rb,
server/debug_lib.rb,
server/ione.rb,
server/ione.rb,
server/lib/server/main.rb,
server/lib/vminfo/main.rb,
server/lib/vmcontrol/main.rb,
server/lib/accounting/main.rb,
server/lib/useful_things/main.rb,
server/lib/creative_funcs/main.rb,
server/lib/data_import_handler/main.rb,
server/modules/stat/main.rb,
server/modules/ansible/main.rb,
server/modules/updatesmanager/main.rb,
server/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)


99
100
101
102
103
# File 'server/debug_lib.rb', line 99

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

Instance Method Details

#activity_logString

Get log from activities.log file

Returns:



153
154
155
156
157
158
# File 'server/service/log.rb', line 153

def activity_log()
    LOG_STAT()        
    LOG "Log file content has been copied remotely", "activity_log"
    log = File.read("#{LOG_ROOT}/activities.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
81
82
83
84
85
86
87
# File 'server/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']
    return if DEBUG
    ip, err = host.split(':').first, ""
    Thread.new do
        playbooks.each do |service, playbook|
            installid = id_gen().crypt(service[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' 
                    $pbexec = ssh.exec!("ansible-playbook /tmp/#{installid}.yml -i /tmp/#{installid}.ini").split(/\n/)
                    LOG 'PB has been Executed', 'AnsibleController' 
                    # def status(regexp)
                        # return $pbexec.last[regexp].split(/=/).last.to_i
                    # end
                    LOG_DEBUG 'PB execution result:'
                    LOG_DEBUG $pbexec.join("\n")
                    # LOG 'Creating log-ticket', '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

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



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

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, true), :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 }
                leases = vn['LEASES']['LEASE'].map {|lease| lease['IP']}
                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

#confString

Returns CONF Hash as JSON, with crypted private data

Returns:



36
37
38
39
40
41
42
# File 'server/lib/server/main.rb', line 36

def conf
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'conf') }
    CONF.privatise.out
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)

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

Returns:

  • (Fixnum)

    new playbook id



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

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



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
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
# File 'server/lib/creative_funcs/main.rb', line 216

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
        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 ? CONF['vCenter']['drive-types'][params['ds-type']] : params['iops']
        rescue
            LOG_DEBUG "No vCenter configuration found"
        end

        params['username'] = params['username'] || 'Administrator'
        params['extra'] = params['extra'] || {'type' => 'vcenter'}
        ###################### Doing some important system stuff ###############################################################
        
        return nil if DEBUG
        LOG_TEST "CreateVMwithSpecs for #{params['login']} Order Accepted! #{params['trial'] == true ? "VM is Trial" : nil}"
        
        LOG_DEBUG "Params: #{params.out}"
        
        trace << "Checking template:#{__LINE__ + 1}"
        onblock(:t, params['templateid']) do | t |
            result = t.info!
            if params['templateid'] == 0 || result != nil then
                LOG_ERROR "Error: TemplateLoadError" 
                return {'error' => "TemplateLoadError", 'trace' => (trace << "TemplateLoadError:#{__LINE__ - 1}")}
            end
        end
        
        #####################################################################################################################
        
        #####   Initializing useful variables   #####
        userid, vmid = 0, 0
        ##### Initializing useful variables END #####
        
        
        #####   Creating new User   #####
        LOG_TEST "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_TEST "New User account created"

        ##### Creating new User END #####
        
        #####   Creating and Configuring VM   #####
        LOG_TEST "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']}\n" \
                        "MEMORY = #{params['ram'] * (params['units'] == 'GB' ? 1024 : 1)}\n" \
                        "DISK = [ \n" \
                        "IMAGE_ID = \"#{t.to_hash['VMTEMPLATE']['TEMPLATE']['DISK']['IMAGE_ID']}\",\n" \
                        "SIZE = \"#{params['drive'] * (params['units'] == 'GB' ? 1024 : 1)}\",\n" \
                        "OPENNEBULA_MANAGED = \"NO\"\t]"

            elsif t['/VMTEMPLATE/TEMPLATE/HYPERVISOR'] == 'AZURE' then
                specs = "OS_DISK_SIZE = \"#{params['drive']}\"\n" \
                        "SIZE = \"#{params['extra']['instance_size']}\"\n" \
                        "VM_USER_NAME = \"#{params['username']}\"\n" \
                        "PASSWORD = \"#{params['passwd']}\"\n" \
                        "VCPU = #{params['cpu']}\n" \
                        "MEMORY = #{params['ram'] * (params['units'] == 'GB' ? 1024 : 1)}\n"
            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'
            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_TEST '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 params['extra']['type'] == 'vcenter' 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=\"#{(CONF['OpenNebula']['base-vnc-port'] + vmid).to_s}\", TYPE=\"VNC\" ]"
                    ) # Configuring VNC
                rescue => e
                    LOG_DEBUG "VNC configuring error: #{e.message}"
                end
            end

            if params['extra']['type'] == 'vcenter' then
                trace << "Deploying VM:#{__LINE__ + 1}"
                vm.deploy(host, false, ChooseDS(params['ds_type']))
            else
                trace << "Deploying VM:#{__LINE__ + 1}"
                vm.deploy(host, false)
            end if params['release']
            # vm.deploy($default_host, false, params['datastore'].nil? ? ChooseDS(params['ds_type']): params['datastore']) 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

            #LimitsController

            LOG_DEBUG "Executing LimitsController for VM#{vmid} | Cluster type: #{ClusterType(host)}"
            trace << "Executing LimitsController for VM#{vmid} | Cluster type: #{ClusterType(host)}:#{__LINE__ + 1}"
            postDeploy.LimitsController(params, vmid, host)

            #endLimitsController
            #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_TEST 'Post-Deploy joblist defined, basic installation job ended'
        return out = {'userid' => userid, 'vmid' => vmid, 'ip' => GetIP(vmid)}
    rescue => e
        out = { :exception => e.message, :trace => trace << 'END_TRACE' }
        LOG_DEBUG out.debug_out
        return out
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:



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

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']
        } 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)


216
217
218
219
220
221
222
223
224
225
226
227
# File 'server/lib/vmcontrol/main.rb', line 216

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(User, userid).delete
end

#DeleteAnsiblePlaybook(id) ⇒ NilClass

Deletes playbook from DB by id

Parameters:

  • id (Fixnum)

Returns:



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

def DeleteAnsiblePlaybook id
    AnsiblePlaybook.new(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:

Returns:

  • (Integer| 'none')


57
58
59
60
61
62
63
64
65
66
67
# File 'server/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 'server/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, true) == 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:

Returns:



74
75
76
77
78
79
80
81
# File 'server/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)
    { :vmid => vmid, :userid => userid, :ip => GetIP(vmid) }
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)



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 'server/lib/vminfo/main.rb', line 98

def get_vm_data(vm)
    vm = onblock(:vm, vm) if vm.class == Fixnum || vm.class == String
    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'
    }
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:



103
104
105
106
107
108
109
110
# File 'server/lib/useful_things/main.rb', line 103

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:



89
90
91
92
93
94
95
96
# File 'server/lib/useful_things/main.rb', line 89

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



280
281
282
# File 'server/lib/useful_things/main.rb', line 280

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 'server/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



106
107
108
# File 'server/modules/ansible/main.rb', line 106

def GetAnsiblePlaybook id
    return { "ANSIBLE" => AnsiblePlaybook.new(id:id).to_hash }
end

#GetAnsiblePlaybook_ControllerRunnable(id) ⇒ Hash

Returns playbook in AnsibleController acceptable form

Parameters:

  • id (Fixnum)

Returns:



140
141
142
# File 'server/modules/ansible/main.rb', line 140

def GetAnsiblePlaybook_ControllerRunnable id
    AnsiblePlaybook.new(id:id).runnable
end

#GetAnsiblePlaybookVariables(id) ⇒ Hash

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

Parameters:

  • id (Fixnum)

Returns:

  • (Hash)

    Variables with default values



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

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



271
272
273
# File 'server/lib/useful_things/main.rb', line 271

def getglog
    $log
end

#GetIP(vm_ref) ⇒ String

Returns VM's IP by ID

Parameters:

  • vm_ref (Integer)
    • VM ID

Returns:



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 'server/lib/vminfo/main.rb', line 22

def GetIP(vm_ref)
    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
        ip = IPAddr.new vm['TEMPLATE']['NIC']['IP']
        return ip.to_s if ip.ipv4? && !ip.local?
    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? }.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?
    rescue
    end
    return ""
end

#GetMonitoringShowbackData(uid, time, vms = []) ⇒ Object



172
173
174
175
176
177
178
179
# File 'server/lib/accounting/main.rb', line 172

def GetMonitoringShowbackData uid, time, vms = []
    user_monitoring = UserMonitoring.new(uid, vms)
    user_monitoring.filter_by_time(time)
    user_monitoring.parse
    user_monitoring.calculate

    user_monitoring.showback
end

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

Getting snapshot list for given VM

Parameters:

  • vmid (Integer)
    • VM ID

Returns:



126
127
128
129
130
131
132
133
# File 'server/lib/vminfo/main.rb', line 126

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

#GetStatistics(params = {}) ⇒ Object

Returns calls statisctics



30
31
32
33
34
35
36
37
38
39
# File 'server/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:



191
192
193
194
195
196
197
198
199
200
# File 'server/lib/useful_things/main.rb', line 191

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

#GetVMIDbyIP(ip) ⇒ Integer | nil

Getting VM ID by IP

Parameters:

Returns:

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



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'server/lib/vminfo/main.rb', line 55

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:



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

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



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'server/lib/accounting/main.rb', line 187

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

    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
    }
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 'server/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

#IONeUpdate(token, trace = ["Update Process starter:#{__LINE__}"]) ⇒ Object

Updates IONe from Github



3
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
47
# File 'server/modules/updatesmanager/main.rb', line 3

def IONeUpdate(token, trace = ["Update Process starter:#{__LINE__}"])
    return 'Wrong token!' if token != CONF['UpdatesManager']['update-token']
    LOG_TEST "IONe update query accepted"
    Thread.new do
        begin
            trace << "Creating temporary dirs:#{__LINE__ + 1}"
            `mkdir /tmp/ione`
            `mkdir /tmp/ione_current#{STARTUP_TIME}`

            trace << "Creating backup:#{__LINE__ + 1}"
            `cp -rf #{ROOT}/* /tmp/ione_current/` 

            trace << "Cloning git repository to temporary dir:#{__LINE__ + 1}"
            `git clone --branch #{CONF['UpdatesManager']['branch']} #{CONF['UpdatesManager']['repo']} /tmp/ione`

            trace << "Replacing the old server:#{__LINE__ + 1}"
            `cp -rf /tmp/ione/server/* #{ROOT}/`

            `cp -f /tmp/ione_current/config.yml #{ROOT}/`

            "Starting bundler:#{__LINE__ + 1}"
            `bundle install --gemfile /tmp/ione/Gemfile`

            trace << "Replacing cli utility:#{__LINE__ + 1}"
            `cp /tmp/ione/utils/ione /usr/bin`
            `chmod +x /usr/bin/ione`


            trace << "Replacing systemd service:#{__LINE__ + 1}"
            `mv /tmp/ione/utils/ione.service /lib/systemd/system/ione.service`
            `systemctl daemon-reload`
            
            trace << "Cleaning temporary dir:#{__LINE__ + 1}"
            `rm -rf /tmp/ione`
            `rm -rf #{ROOT}/../utils`

            LOG_COLOR "Update successful, current version: #{File.read("#{ROOT}/meta/version.txt").chomp}\nChanges will be applied after rebooting the server.", 'IONeUpdate', 'lightgreen'
        rescue => e
            LOG_ERROR "Update unsuccessful!!! Nothing will changed. Error: #{e.message}. Traceback is at debug.log"
            LOG trace.join(",\n")
            `cp -rf /tmp/ione_current/* #{ROOT}/`                
        end
    end
    'Update proccess started, check logs for information'
end

#LCM_STATE(vmid) ⇒ Integer

Getting VM LCM state number by ID

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (Integer)

    State



86
87
88
# File 'server/lib/vminfo/main.rb', line 86

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:



92
93
94
# File 'server/lib/vminfo/main.rb', line 92

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

#ListAnsiblePlaybooksArray<Hash>

Returns all playbooks from DB

Returns:



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

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 'server/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 activities.log

Parameters:

  • msg (String)
    • your message

Returns:

  • (String)

    returns given message



162
163
164
165
166
# File 'server/service/log.rb', line 162

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



261
262
263
264
265
266
267
268
269
# File 'server/lib/vmcontrol/main.rb', line 261

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
    onblock(VirtualMachine, vmid.to_i).snapshot_create(name)
end

#procObject

Returns active processes list



48
49
50
# File 'server/lib/server/main.rb', line 48

def proc
    $PROC
end

#reboot(pa) ⇒ 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.



44
45
46
# File 'server/lib/server/main.rb', line 44

def reboot(pa)
    `sh #{ROOT}/service/handlers/reboot_key.sh &` if pa['ss']
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



151
152
153
154
155
156
157
158
159
160
161
# File 'server/lib/vmcontrol/main.rb', line 151

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
    onblock(VirtualMachine, vmid.to_i).reboot(hard) # reboots 'hard' if true
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

  • :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:



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
# File 'server/lib/creative_funcs/main.rb', line 62

def Reinstall(params, trace = ["Reinstall method called:#{__LINE__}"])
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true)
    defer { LOG_CALL(id, false, 'Reinstall') }
        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'
            return "ReinstallError - some params are nil"
        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'] = CONF['vCenter']['drive-types'][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'
        

        LOG_DEBUG 'Initializing vm object'
        trace << "Initializing old VM object:#{__LINE__ + 1}"            
        vm = onblock(VirtualMachine, params['vmid'])
        LOG_DEBUG 'Collecting data from old template'
        trace << "Collecting data from old template:#{__LINE__ + 1}"            
        nic, context = vm.to_hash!['VM']['TEMPLATE']['NIC'], vm.to_hash['VM']['TEMPLATE']['CONTEXT']
        
        LOG_DEBUG 'Initializing template obj'
        LOG_DEBUG 'Generating new template'
        trace << "Generating NIC context:#{__LINE__ + 1}"
        context = "NIC = [\n\tIP=\"#{nic['IP']}\",\n\tDNS=\"#{nic['DNS']}\",\n\tGATEWAY=\"#{nic['GATEWAY']}\",\n\tNETWORK=\"#{nic['NETWORK']}\",\n\tNETWORK_UNAME=\"#{nic['NETWORK_UNAME']}\"\n]\n"
        trace << "Generating template object:#{__LINE__ + 1}"            
        template = onblock(Template, params['templateid'])
        template.info!
        trace << "Checking OS type:#{__LINE__ + 1}"            
        win = template.win?
        trace << "Generating credentials and network context:#{__LINE__ + 1}"
        context += "CONTEXT = [\n\tPASSWORD=\"#{params['passwd']}\",\n\tETH0_IP=\"#{nic['IP']}\",\n\tETH0_GATEWAY=\"#{nic['GATEWAY']}\",\n\tETH0_DNS=\"#{nic['DNS']}\",\n\tNETWORK=\"YES\"#{ win ? ",\n\tUSERNAME = \"#{params['username']}\"" : nil}\t]\n"
        trace << "Generating specs configuration:#{__LINE__ + 1}"
        context += "VCPU = #{params['cpu']}\n" \
                    "MEMORY = #{params['ram'] * (params['units'] == 'GB' ? 1024 : 1)}\n" \
                    "DISK = [ \n" \
                    "IMAGE_ID = \"#{template.to_hash['VMTEMPLATE']['TEMPLATE']['DISK']['IMAGE_ID']}\",\n" \
                    "SIZE = \"#{params['drive'] * (params['units'] == 'GB' ? 1024 : 1)}\",\n" \
                    "OPENNEBULA_MANAGED = \"NO\"\t]"
        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, vmid.class, vmid.message if vmid.class != Fixnum
            return vmid, 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 = params['host'].nil? ? $default_host : params['host']

            onblock(:vm, vmid) do | vm |
                LOG_DEBUG 'Deploying VM to the host'
                vm.deploy(host, false, ChooseDS(params['ds_type']))
                LOG_DEBUG 'Waiting until VM will be deployed'
                vm.wait_for_state
            end

            postDeploy = PostDeployActivities.new @client

            #LimitsController

            LOG_DEBUG "Executing LimitsController for VM#{vmid} | Cluster type: #{ClusterType(host)}"
            trace << "Executing LimitsController for VM#{vmid} | Cluster type: #{ClusterType(host)}:#{__LINE__ + 1}"
            postDeploy.LimitsController(params, vmid, host)

            #endLimitsController
            #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), 'ip_old' => nic['IP'] }
    rescue => e
        LOG_ERROR "Error ocurred while Reinstall: #{e.message}"
        return e.message, trace
end

#ReinstallTestMethod(params, vmid) ⇒ Object



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'server/lib/creative_funcs/main.rb', line 405

def ReinstallTestMethod(params, vmid)
    postDeploy = PostDeployActivities.new @client
    #####   PostDeploy Activity define   #####

        host = params['host'].nil? ? $default_host : params['host']

        #AnsibleController
        
        if params['ansible'] && params['release'] then
            postDeploy.AnsibleController(params, vmid, host)
        end

        #endAnsibleController

    ##### PostDeploy Activity define END #####
rescue => e
    return e.message
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)


231
232
233
234
235
236
237
238
239
240
241
# File 'server/lib/vmcontrol/main.rb', line 231

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

    onblock(VirtualMachine, vmid.to_i) do | vm |
        vm.unschedule(0) if trial
        vm.resume
    end
end

#RetrieveShowback(user_id, start_time = [-1, -1], end_time = [-1, -1], filter = []) ⇒ Object



164
165
166
167
168
169
170
171
# File 'server/lib/accounting/main.rb', line 164

def RetrieveShowback user_id, start_time = [-1, -1], end_time = [-1, -1], filter = []
    LOG_DEBUG [user_id, start_time, end_time, filter].inspect
    showback = UserShowback.new user_id, start_time, end_time

    showback.filter filter unless filter.nil? || filter == []

    return showback.data, showback.total_cost
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)


275
276
277
278
279
280
281
282
283
# File 'server/lib/vmcontrol/main.rb', line 275

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
    onblock(VirtualMachine, vmid.to_i).snapshot_revert(snapid.to_i)
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)


247
248
249
250
251
252
253
254
255
# File 'server/lib/vmcontrol/main.rb', line 247

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(VirtualMachine, vmid.to_i).snapshot_delete(snapid.to_i)
end

#RunAnsiblePlaybook(id, host, vars = {}) ⇒ 200

Runs given playbook at given host with given variables

Parameters:

  • id (Fixnum)
  • host (String)
    • where ti run playbook in hostname:port format

  • vars (Hash) (defaults to: {})
    • variables values to fill playbook with, where key is variable name

Returns:

  • (200)


153
154
155
# File 'server/modules/ansible/main.rb', line 153

def RunAnsiblePlaybook id, host, vars = {}
    AnsiblePlaybook.new(id:id).run host, vars
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:



290
291
292
293
# File 'server/lib/useful_things/main.rb', line 290

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

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

Note:

Don't user OpenNebula::VirtualMachine#shutdown - this method deletes VM's

Powering off VM

Parameters:

  • vmid (Integer)
    • VM to shutdown

Returns:

  • (nil | OpenNebula::Error)


193
194
195
196
197
198
199
200
201
# File 'server/lib/vmcontrol/main.rb', line 193

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"
    onblock(VirtualMachine, vmid).poweroff
end

#sleep_test(timeout) ⇒ Object



2
3
4
5
# File 'server/lib/creative_funcs/main.rb', line 2

def sleep_test(timeout)
    sleep(timeout)
    return 'DONE'
end

#STATE(vmid) ⇒ Integer

Getting VM state number by ID

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (Integer)

    State



74
75
76
# File 'server/lib/vminfo/main.rb', line 74

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:



80
81
82
# File 'server/lib/vminfo/main.rb', line 80

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
# File 'server/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(VirtualMachine, params['vmid'].to_i) do | vm |
            begin
                trace << "Suspending VM:#{__LINE__ + 1}"
                vm.suspend
            rescue
                trace << "Some exception raised while suspending VM:#{__LINE__ - 2}"
                LOG_TEST "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:



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'server/lib/vmcontrol/main.rb', line 55

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.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:



48
49
50
# File 'server/lib/vmcontrol/main.rb', line 48

def SuspendVM(vmid)
    onblock(VirtualMachine, vmid.to_i).suspend
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)


166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'server/lib/vmcontrol/main.rb', line 166

def Terminate(userid, vmid)
    LOG_STAT()
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Terminate') }
              
    begin
        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"
        onblock(VirtualMachine, vmid).recover 3
    rescue => err
        return err
    end
    0
end

#Test(msg) ⇒ String('DONE') | String('PONG')

Logs sent message into activities.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:



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

def Test(msg)
    id = id_gen()
    LOG_CALL(id, true, __method__)
    defer { LOG_CALL(id, false, 'Test') }
    LOG "Test message received, text: #{msg}", "Test" 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



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'server/lib/vmcontrol/main.rb', line 89

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(VirtualMachine, params['vmid'].to_i) do | vm |
                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:



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

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.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)
  • extradata (String)


118
119
120
121
122
123
124
# File 'server/modules/ansible/main.rb', line 118

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:



27
28
29
30
31
32
33
# File 'server/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

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



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'server/lib/creative_funcs/main.rb', line 19

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
    groupid = nil
    allocation_result =
        begin
            user.allocate(, pass, "core", groupid.nil? ? [USERS_GROUP] : [groupid, USERS_GROUP]) # 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 || CONF['OpenNebula']['users-default-lang']}\" ]"
    attributes += "AZURE_TOKEN=\"#{}\"" if type == 'azure'
    user.update(attributes, true)
    return user.id, user if object
    user.id
end

#versionString

Returns current running IONe Cloud Server version

Returns:



18
19
20
21
22
23
24
# File 'server/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:



302
303
304
305
# File 'server/lib/useful_things/main.rb', line 302

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:



10
11
12
13
14
15
16
17
18
# File 'server/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(VirtualMachine, vmid)
    vm.info! || vm.to_xml
end