Class: IONe

Inherits:
Object
  • Object
show all
Includes:
Deferable
Defined in:
ione_server.rb,
ione_server.rb,
lib/server/main.rb,
lib/vminfo/main.rb,
lib/vntools/main.rb,
lib/vmcontrol/main.rb,
lib/accounting/main.rb,
lib/template_info/main.rb,
lib/useful_things/main.rb,
lib/creative_funcs/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

VirtualMachines Info collapse

Users Info collapse

Billing collapse

Templates Info collapse

User Control collapse

VirtualMachines info collapse

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:



147
148
149
150
151
# File 'ione_server.rb', line 147

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(method, *args, &block) ⇒ Object

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



154
155
156
157
158
159
160
161
# File 'ione_server.rb', line 154

def method_missing method, *args, &block
  obj, method = method.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:



120
121
122
123
124
# File 'service/log.rb', line 120

def activity_log()
  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)


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
# File 'modules/ansible/main.rb', line 33

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
        nil
      end
    end
    Thread.exit
  end
  return 200
end

#AnsiblePlaybookProcessInfo(id) ⇒ Hash

Returns AnsblePlaybook run Process by id as Hash

Parameters:

  • id (Integer)
    • Process id

Returns:



217
218
219
# File 'modules/ansible/main.rb', line 217

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

#AnsiblePlaybookProcessStatus(id) ⇒ String

Returns given AnsiblePlaybookProcess state

Parameters:

  • id (Integer)
    • Process id

Returns:



210
211
212
# File 'modules/ansible/main.rb', line 210

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 (Integer)
    • Playbook ID

  • uid (Integer)
    • 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



175
176
177
178
179
180
181
182
183
184
# File 'modules/ansible/main.rb', line 175

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

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

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

  • stream_data (Sinatra::Stream) (defaults to: nil)
    • sinatra stream object

Returns:



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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/accounting/main.rb', line 15

def calculate_showback 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 = {
    'computing' => {},
    'networking' => {}
  }
  stream = !stream_data.nil?

  if stream then
    stream_data << '"computing": {'
  end

  index = 0
  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['computing'][vm.id] = r
      if stream then
        stream_data << (index != 0 ? ',' : '') << ' ' << "\"#{vm.id}\": " << JSON.generate(r)
        index += 1
      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

  if stream then
    stream_data << '}, "networking":'
  end

  networking = onblock(:u, uid).calculate_networking_showback(stime, etime)
  showback['networking'] = networking
  if stream then
    stream_data << JSON.generate(networking) << ', '
  end

  showback['computing']['TOTAL'] = showback['computing'].inject(0) { | result, (_id, vm) | result + vm[:TOTAL] }
  showback['TOTAL'] =     showback['computing']['TOTAL']
  showback['TOTAL'] +=    showback['networking']['TOTAL']
  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



164
165
166
# File 'modules/ansible/main.rb', line 164

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:



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

def compare_info vms = []
  info = []
  infot = Thread.new do
    unless vms.empty? then
      vm_pool = vms.map! do |vmid|
        onblock(:vm, vmid, @client) { | 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
        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
        nil
      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 = {}) ⇒ Integer

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:

  • (Integer)

    new playbook id



95
96
97
# File 'modules/ansible/main.rb', line 95

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

#CreateVMwithSpecs(params, trace = ["#{__method__} 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__} method called:#{__LINE__}"])
    • public trace log

Options Hash (params):

  • :login (String)

    Username for new OpenNebula account

  • :password (String)

    Password for new OpenNebula account

  • :vm_name (String)

    New VM instance name(otherwise old name is going to be used)

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

  • :ips (Integer)

    Public IPs amount(default: 1)

  • :trial (Boolean) — default: false

    VM will be suspended after IONe::Settings

  • :release (Boolean) — default: false

    VM will be started on HOLD if false

  • :user-template (Hash)

    Addon template, you may append to default template

  • :allow_snapshots (Boolean)

    Allow user to create snapshots

Returns:

  • (Hash, nil)

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



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

def CreateVMwithSpecs(params, trace = ["#{__method__} method called:#{__LINE__}"])
  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 }
  params['ips'] = params['ips'].nil? ? 1 : params['ips'].to_i
  params['user-template'] = {} if params['user-template'].nil?

  begin
    params['iops'] = params['iops'] == 0 ? IONe::Settings['VCENTER_DRIVES_IOPS'][params['ds-type']] : params['iops']
  rescue
    LOG_DEBUG "No vCenter configuration found"
  end

  paas_vnet = IONe::Settings['PUBLIC_NETWORK_DEFAULTS']['PAAS']
  return { error: "VNetNotConfigured" } if paas_vnet.nil? || paas_vnet == ""

  params['vm_name'] = params['vm_name'] || "#{params['login']}_vm"
  ###################### 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'], IONe::Settings['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!
    params['username'] = params['username'] || (t.win? ? 'Administrator' : 'root')
    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 = {
        "CPU" => 1,
        "VCPU" => params['cpu'],
        "MEMORY" => params['ram'] * (params['units'] == 'GB' ? 1024 : 1),
        "DRIVE" => params['ds_type'],
        "DISK" => {
          "DEV_PREFIX" => "vd",
            "DRIVER" => "qcow2",
            "SIZE" => params['drive'] * (params['units'] == 'GB' ? 1024 : 1),
            "OPENNEBULA_MANAGED" => "NO"
        }
      }
      key = t.to_hash['VMTEMPLATE']['TEMPLATE']['DISK']['IMAGE_ID'].nil? ? 'IMAGE' : 'IMAGE_ID'
      specs['DISK'][key] = t.to_hash['VMTEMPLATE']['TEMPLATE']['DISK'][key]
    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'

    unless params['allow_snapshots'].nil? then
      params['user-template']['SNAPSHOTS_ALLOWED'] = params['allow_snapshots'].to_s.upcase
    end

    trace << "Setting up NICs:#{__LINE__ + 1}"
    specs['NIC'] = []

    params['ips'].times do
      specs['NIC'] << { NETWORK_ID: paas_vnet }
    end

    host = params['host']
    if host.nil? then
      host = IONe::Settings['NODES_DEFAULT'][params['extra']['type'].upcase]
    end
    if host.class == Array then
      host = host.map { | h | "ID=\"#{h}\"" }.join(" | ")
    else
      host = "ID=\"#{host}\""
    end

    specs['SCHED_REQUIREMENTS'] = host

    ds = ChooseDS(params['ds_type'], params['extra']['type'])
    specs['SCHED_DS_REQUIREMENTS'] = "ID=\"#{ds}\""

    LOG_DEBUG "Resulting capacity template:\n" + specs.debug_out
    specs = specs.to_one_template
    vmid = t.instantiate(params['vm_name'], !params['release'], specs + "\n" + params['user-template'].to_one_template)
  end

  raise "Template instantiate Error: #{vmid.message}" if OpenNebula.is_error? vmid

  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, IONe::Settings['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
      trace << "Setting VM context:#{__LINE__ + 2}"
      begin
        vm.updateconf(
          {
            CONTEXT: {
              NETWORK: "YES",
              PASSWORD: params['passwd'],
              SSH_PUBLIC_KEY: "$USER[SSH_PUBLIC_KEY]",
              USERNAME: params['username']
            }
          }.to_one_template
        )
      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::Settings['BASE_VNC_PORT'] + vmid),
              TYPE: "VNC"
            }
          }.to_one_template
        ) # Configuring VNC
      rescue => e
        LOG_DEBUG "VNC configuring error: #{e.message}"
      end
    end
  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"

    post_deploy = PostDeployActivities.new @client

    # TrialController

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

    # endTrialController
    # AnsibleController

    if params['ansible'] && params['release'] then
      trace << "Creating Ansible Installer thread:#{__LINE__ + 1}"
      post_deploy.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 { 'userid' => userid, 'vmid' => vmid, 'ip' => GetIP(vmid) }
rescue => e
  begin
    out = { :exception => e.message, :trace => trace << 'END_TRACE' }
    LOG_DEBUG e.backtrace
    LOG_DEBUG out.debug_out
    out[:params] = params
    return out
  ensure
    onblock(:vm, vmid).recover(3) if (defined? vmid) && !(OpenNebula.is_error? vmid)
    user.delete if defined? user
  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:



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

def DatastoresMonitoring(type)
  return "WrongTypeExeption: type '#{type}' not exists" if type != 'sys' && type != 'img'

  # @!visibility private
  # Converts MB to GB
  size_convert = lambda do | mb |
    if mb.to_f / 1024 > 768 then
      return "#{(mb.to_f / 1048576.0).round(2)}TB"
    else
      return "#{(mb.to_f / 1024.0).round(2)}GB"
    end
  end

  ds_pool, mon = DatastorePool.new(@client), []
  ds_pool.info_all!

  allow_system_ds = IONe::Settings['ALLOW_USING_SYSTEM_DATASTORES']
  ds_pool.each do | ds |
    mon << {
      'id' => ds.id, 'name' => ds.name.split('(').first, :full_size => size_convert[ds.to_hash['DATASTORE']['TOTAL_MB']],
        'used' => size_convert[ds.to_hash['DATASTORE']['USED_MB']],
        'type' => ds.to_hash['DATASTORE']['TEMPLATE']['DRIVE_TYPE'],
        'deploy' => ds.to_hash['DATASTORE']['TEMPLATE']['DEPLOY'],
        'hypervisor' => ds.to_hash['DATASTORE']['TEMPLATE']['HYPERVISOR']
    } if ds.short_type_str == type && (allow_system_ds || ds.id > 2)
  end
  mon
end

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

Deletes given user by ID

Parameters:

  • userid (Integer)

Returns:

  • (nil | OpenNebula::Error)


214
215
216
217
218
219
220
221
# File 'lib/vmcontrol/main.rb', line 214

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

#DeleteAnsiblePlaybook(id) ⇒ NilClass

Deletes playbook from DB by id

Parameters:

  • id (Integer)

Returns:



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

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

#DeleteAnsiblePlaybookProcess(id) ⇒ NilClass

Deletes given AnsiblePlaybookProcess

Parameters:

  • id (Integer)
    • Process id

Returns:



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

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

#get_all_settingsHash

Returns whole IONe settings table if user is Admin

Returns:



21
22
23
# File 'lib/server/main.rb', line 21

def get_all_settings
  return @db[:settings].as_hash(:name, :body) if onblock(:u, -1, @client).admin?
end

#get_available_vms(chunks = nil, page = 0) ⇒ Array<Integer>

Returns all vms available with given credentials

Parameters:

  • chunks (Integer) (defaults to: nil)
    • number of chunks per page

  • page (Integer) (defaults to: 0)
    • page number(shift)

Returns:



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

def get_available_vms chunks = nil, page = 0
  vmp = VirtualMachinePool.new(@client)
  vmp.info_all!

  if chunks.nil? then
    vmp.inject([]) do |r, vm|
      r << {
        id: vm.id,
            name: vm.name,
            ip: GetIP(vm),
            state: vm.state_str,
            lcm_state: vm.lcm_state_str,
            host: get_vm_host(vm)
      }
    end
  else
    vmp.inject([]) { |r, vm| r << vm }.each_slice(chunks).to_a[page].map do | vm |
      {
        id: vm.id,
            name: vm.name,
            ip: GetIP(vm),
            state: vm.state_str,
            lcm_state: vm.lcm_state_str,
            host: get_vm_host(vm)
      }
    end
  end
end

#get_templates_list(group_id = nil) ⇒ Array

Obtains the list of all available Templates(and filters by groupd_id if given)

Parameters:

  • group_id (Integer) (defaults to: nil)
    • group if to filter by(optional)

Returns:



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/template_info/main.rb', line 7

def get_templates_list group_id = nil
  tp_pool = TemplatePool.new(@client)
  tp_pool.info_all!
  tp_pool.inject([]) do | res, tp |
    res << {
      id: tp.id,
      name: tp.name,
      description: tp.to_hash['VMTEMPLATE']['TEMPLATE']['DESCRIPTION'],
      logo: tp.to_hash['VMTEMPLATE']['TEMPLATE']['LOGO'],
      uid: tp.to_hash['VMTEMPLATE']['UID'],
      gid: tp.to_hash['VMTEMPLATE']['GID'],
    } if group_id.nil? or group_id.to_i == tp.to_hash['VMTEMPLATE']['GID'].to_i
    res
  end
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')


62
63
64
65
66
67
68
69
# File 'lib/useful_things/main.rb', line 62

def get_uid_by_name(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_user_vmsArray<Hash>

Returns all @client User vms

Returns:



150
151
152
153
# File 'lib/vminfo/main.rb', line 150

def get_user_vms
  r = VirtualMachinePool.new(@client, -1).get_hash['VM_POOL']
  r.empty? ? [] : r['VM']
end

#get_user_vms_extArray<Hash>

Returns all @client User vms with extended info

Returns:



156
157
158
159
160
161
162
163
# File 'lib/vminfo/main.rb', line 156

def get_user_vms_ext
  u = onblock(:u, -1, @client)
  r = u.info!

  raise r if OpenNebula.is_error? r

  u.vms $db
end

#get_user_vnetsArray<Hash>

Returns all @client User vnets

Returns:



84
85
86
87
88
89
# File 'lib/vntools/main.rb', line 84

def get_user_vnets
  onblock(:u, -1, @client) do | u |
    u.info!
    u.vns(@db).map { |vn| vn.to_hash }
  end
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')


29
30
31
32
33
34
35
36
# File 'lib/useful_things/main.rb', line 29

def get_vm_by_uid(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:

Returns:



81
82
83
84
85
86
87
88
89
# File 'lib/useful_things/main.rb', line 81

def get_vm_by_uname name
  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)



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

def get_vm_data(vm)
  vm = onblock(:vm, vm) if vm.class == Integer || vm.class == String
  r = vm.info!
  raise r if OpenNebula.is_error? r

  vmid = vm.id
  vm_hash = vm.to_hash!['VM']
  host_id, hostname = vm.host
  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:



113
114
115
116
117
118
119
120
121
# File 'lib/useful_things/main.rb', line 113

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:



98
99
100
101
102
103
104
105
# File 'lib/useful_things/main.rb', line 98

def get_vm_host vm, hid = false
  vm = onblock(:vm, vm, @client) if vm.class == Integer
  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:

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



286
287
288
# File 'lib/useful_things/main.rb', line 286

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:



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

def get_vms_by_uid(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 (Integer)
    • Playbook id in DB

Returns:

  • (Hash)

    Playbook data



102
103
104
# File 'modules/ansible/main.rb', line 102

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

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

Returns playbook in AnsibleController acceptable form

Parameters:

  • id (Integer)

Returns:



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

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 (Integer)
    • Process id

Returns:



189
190
191
# File 'modules/ansible/main.rb', line 189

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 (Integer)

Returns:

  • (Hash)

    Variables with default values



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

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

#GetIP(vm_ref, private_allowed = false) ⇒ String

Returns VM's IP by ID

Parameters:

  • vm_ref (Integer)
    • VM ID

Returns:



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
48
49
50
51
52
53
# File 'lib/vminfo/main.rb', line 12

def GetIP(vm_ref, private_allowed = false)
  vm = case vm_ref
       when OpenNebula::VirtualMachine
         vm_ref.to_hash
       when Integer, 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
    nil
  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
    nil
  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
    nil
  end
  return ""
end

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

Getting snapshot list for given VM

Parameters:

  • vmid (Integer)
    • VM ID

Returns:



140
141
142
# File 'lib/vminfo/main.rb', line 140

def GetSnapshotList(vmid)
  onblock(:vm, vmid).list_snapshots
end

#GetUserInfo(userid) ⇒ String

Returns User template in XML

Parameters:

  • userid (Integer)

Returns:



208
209
210
211
212
213
# File 'lib/useful_things/main.rb', line 208

def GetUserInfo(userid)
  onblock(:u, 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



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/vminfo/main.rb', line 60

def GetVMIDbyIP(ip)
  vm_pool = VirtualMachinePool.new(@client)
  vm_pool.info_all!
  vm_pool.each do |vm|
    begin
      return vm.id if ip.chomp == GetIP(vm.id).chomp
    rescue
      nil
    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:



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/useful_things/main.rb', line 256

def HostsMonitoring()
  # @!visibility private
  # Converts MB to GB
  size_convert = lambda do | mb |
    if mb.to_f / 1048576 > 768 then
      return "#{(mb.to_f / 1073741824.0).round(2)}TB"
    else
      return "#{(mb.to_f / 1048576.0).round(2)}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 => size_convert[host.to_hash['HOST_SHARE']['TOTAL_MEM']],
        :reserved => size_convert[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)}%"
    }
  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



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

def IaaS_Gate params
  params['vms'] = params['vms'] || []
  user = onblock :u, params['uid'], @client
  e = user.info!
  return 401 unless e.nil?

  showback = calculate_showback(*params.get('uid', 'time'))

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



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

def IaaS_Gate_new params
  LOG_DEBUG params
  response = []

  one_user = onblock :u, 0, @client
  e = one_user.info!
  return 401 unless e.nil?

  params["users"].each do | u |
    u['vms'] = u['vms'] || []
    showback = calculate_showback(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

#LCM_STATE(vmid) ⇒ Integer

Getting VM LCM state number by ID

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (Integer)

    State



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

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:



99
100
101
# File 'lib/vminfo/main.rb', line 99

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

#ListAnsiblePlaybookProcesses(chunks = nil, page = 0) ⇒ Array<Hash>

Returns all AnsiblePlaybook Processes as Array of Hashes

Parameters:

  • chunks (Integer) (defaults to: nil)
    • number of processes per page(chunk)

  • page (Integer) (defaults to: 0)
    • page number(shift)

Returns:



225
226
227
228
229
230
231
232
# File 'modules/ansible/main.rb', line 225

def ListAnsiblePlaybookProcesses chunks = nil, page = 0
  pool = AnsiblePlaybookProcess.list
  pool.delete_if { |apc| !@client.user!.groups.include?(0) && apc['uid'] != @client.user_id }

  return pool if chunks.nil?

  pool.each_slice(chunks).to_a[page]
end

#ListAnsiblePlaybooks(chunks = nil, page = 0) ⇒ Array<Hash>

Returns Playbooks from DB

Parameters:

  • chunks (Integer) (defaults to: nil)
    • number of playbooks per page(chunk)

  • page (Integer) (defaults to: 0)
    • page number(shift)

Returns:



152
153
154
155
156
157
158
159
# File 'modules/ansible/main.rb', line 152

def ListAnsiblePlaybooks chunks = nil, page = 0
  pool = AnsiblePlaybook.list
  pool.delete_if { |pb| !ansible_check_permissions(pb, @client.user, 0) } # Deletes playbooks, which aren't under user access

  return pool if chunks.nil?

  pool.each_slice(chunks).to_a[page]
end

#log(msg) ⇒ String

Logs given message to ione.log

Parameters:

  • msg (String)
    • your message

Returns:

  • (String)

    returns given message



129
130
131
132
# File 'service/log.rb', line 129

def log(msg)
  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



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

def MKSnapshot(vmid, name, log = true)
  LOG "Snapshot create-query accepted", 'SnapController' if log
  vm = onblock :vm, vmid
  r = vm.info!
  raise r if OpenNebula.is_error? r

  r = vm.snapshot_create(name)
  raise r if OpenNebula.is_error? r

  r
rescue => e
  return e.message
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



141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/vmcontrol/main.rb', line 141

def Reboot(vmid, hard = false)
  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

#Recreate(params, trace = ["Recreate method called:#{__LINE__}"]) ⇒ TrueClass, Integer

Recreates VM - leaves same ID, same IP addresses, amount of resources, etc, but recreates on host

Parameters:

  • params (Hash)
  • deploy (Hash)

    a customizable set of options

Options Hash (params):

  • :vm (Integer)
  • :passwd (String) — default: optional

Returns:

  • (TrueClass, Integer)
    • true and host where VM been deployed before recreate



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

def Recreate(params, trace = ["Recreate method called:#{__LINE__}"])
  params.to_sym!
  LOG "Recreating VM#{params[:vm]}", 'Recreate'

  trace << "Getting VM:#{__LINE__}"
  vm = onblock(:vm, params[:vm])
  vm.info!
  trace << "Checking access rights:#{__LINE__}"
  onblock(:u, -1, @client) do | u |
    u.info!
    if u.id != vm.uid && !u.groups.include?(0) then
      raise StandardError.new("Not enough access to perform Recreate")
    end
  end
  trace << "Getting VM host:#{__LINE__}"
  host, _ = vm.host
  trace << "Recovering VM:#{__LINE__}"
  vm.recover(4)

  if params[:passwd] then
    trace << "Changing VM password#{__LINE__}"
    vm.passwd params[:passwd]
  end

  if params[:deploy] then
    trace << "Waiting for state PENDING to deploy VM:#{__LINE__}"
    vm.wait_state("PENDING", 120)
    trace << "Deploying VM:#{__LINE__}"
    vm.deploy(host.to_i)
  end

  return true, host.to_i
rescue => e
  LOG_ERROR "Error ocurred while Reinstall: #{e.message}"
  raise e
end

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

Recreates VM with same NICs for same user

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

  • :vm_name (String)

    New VM instance name(otherwise old name is going to be used)

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



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
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/creative_funcs/main.rb', line 66

def Reinstall(params, trace = ["Reinstall method called:#{__LINE__}"])
  params.to_s!
  LOG_DEBUG params.merge!({ :method => 'Reinstall' }).debug_out
  return nil if params['debug'] == 'turn_method_off'

  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::Settings['VCENTER_DRIVES_IOPS'][params['ds_type']]
    LOG_DEBUG "IOps: #{params['iops'].class}(#{params['iops']})"
  rescue
    LOG_DEBUG "No vCenter configuration found"
  end

  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

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

  params['username'] = params['username'] || vm['//CONTEXT/USERNAME']
  params['vm_name']  = params['vm_name']  || vm.name

  LOG_DEBUG 'Generating new template'
  trace << "Generating credentials and network context:#{__LINE__ + 1}"
  context['CONTEXT'] = {
    'USERNAME' => params['username'],
      'PASSWORD' => params['passwd'] || vm['//CONTEXT/PASSWORD'],
      'NETWORK' => context['CONTEXT']['NETWORK'],
      'SSH_PUBLIC_KEY' => context['CONTEXT']['SSH_PUBLIC_KEY']
  }
  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']

  host = params['host']
  if host.nil? then
    host = IONe::Settings['NODES_DEFAULT'][params['extra']['type'].upcase]
  end
  if host.class == Array then
    host = host.map { | h | "ID=\"#{h}\"" }.join(" | ")
  else
    host = "ID=\"#{host}\""
  end

  context['SCHED_REQUIREMENTS'] = host

  ds = ChooseDS(params['ds_type'], params['extra']['type'])
  context['SCHED_DS_REQUIREMENTS'] = "ID=\"#{ds}\""

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

    return vmid.class
  end

  return vmid.message if vmid.class != Integer

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

  #####   PostDeploy Activity define   #####
  Thread.new do
    vm = onblock(:vm, vmid)
    LOG_DEBUG 'Waiting until VM will be deployed'
    vm.wait_for_state

    post_deploy = PostDeployActivities.new @client

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

    if params['ansible'] && params['release'] then
      trace << "Creating Ansible Installer thread:#{__LINE__ + 1}"
      post_deploy.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

#release_public_ip(params) ⇒ TrueClass

Releases Public IP back to supernet-pool. Repeats OpenNebula::VirtualNetwork#rm_ar method, but with creating Record in :records storage

Parameters:

Options Hash (params):

  • vn (Integer)
    • Virtual Network ID

  • ar (Integer)
    • Address Range ID

Returns:

  • (TrueClass)


68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/vntools/main.rb', line 68

def release_public_ip params
  params.to_sym!

  vn = onblock(:vn, params[:vn], @client)
  vn.info!

  if vn.rm_ar(params[:ar]).nil? then
    AR.where(vnid: params[:vn], arid: params[:ar], owner: vn['//UID']).update(etime: Time.now.to_i)
    true
  else
    false
  end
end

#reserve_public_ip(params) ⇒ Integer

Reserves Public IP or IPs to user private netpool

Parameters:

Options Hash (params):

  • n (Integer)
    • number of addresses to reserve

  • u (Integer)
    • user id

Returns:

  • (Integer)


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
48
49
50
51
52
53
54
55
56
57
# File 'lib/vntools/main.rb', line 11

def reserve_public_ip params
  params.to_sym!

  vnet = onblock(:vn, IONe::Settings['PUBLIC_NETWORK_DEFAULTS']['IAAS'], @client)
  vnet.info!

  u = onblock(:u, params[:u], @client)
  u.info!

  if (uvnet = u.vns(@db).select { |v| v.type == 'PUBLIC' }.first) then
    uvnet = uvnet.id
  end

  params[:n].times do
    if uvnet then
      uvnet = vnet.reserve(nil, 1, nil, nil, uvnet)
    else
      uvnet = vnet.reserve("user-#{params[:u]}-pub-vnet", 1, nil, nil, uvnet)

      onblock(:vn, uvnet, @client) do | vn |
        vn.update('TYPE="PUBLIC"', true)
      end

      clusters = vnet.to_hash['VNET']['CLUSTERS']['ID']
      clusters = [clusters] if clusters.class != Array
      for c in clusters do
        onblock(:c, c).addvnet(uvnet)
      end
    end
    if OpenNebula.is_error?(uvnet) && uvnet.errno == 2048 then
      return { error: "No free addresses left" }
    end

    ar = onblock(:vn, uvnet, @client).ar_pool.last
    AR.create do | r |
      r.vnid  = uvnet
      r.arid  = ar['AR_ID']
      r.stime = Time.now.to_i
      r.owner = params[:u]
    end
  end

  vn = onblock(:vn, uvnet, $client)
  vn.chown(u.id, u.groups.first)
  vn.chmod(1, 1, 1, 0, 0, 0, 0, 0, 0)
  return vn.id
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)


226
227
228
229
230
231
232
233
234
235
236
# File 'lib/vmcontrol/main.rb', line 226

def Resume(vmid, trial = false)
  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)


272
273
274
275
276
277
278
279
280
281
# File 'lib/vmcontrol/main.rb', line 272

def RevSnapshot(vmid, snapid, log = true)
  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)


243
244
245
246
# File 'lib/vmcontrol/main.rb', line 243

def RMSnapshot(vmid, snapid, log = true)
  LOG "Deleting snapshot(ID: #{snapid}) for VM#{vmid}", "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 (Integer)
    • Process id

Returns:

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



203
204
205
# File 'modules/ansible/main.rb', line 203

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:



297
298
299
300
# File 'lib/useful_things/main.rb', line 297

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

#SetVMResourcesLimits(vmid, host, params) ⇒ Object

temp UPD: not really :)



285
286
287
# File 'lib/vmcontrol/main.rb', line 285

def SetVMResourcesLimits vmid, host, params
  PostDeployActivities.new(@client).LimitsController(params, vmid, onblock(:h, 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)


187
188
189
190
191
192
193
194
195
196
# File 'lib/vmcontrol/main.rb', line 187

def Shutdown(vmid)
  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

#StartVMRC(vmid) ⇒ Object

Generates VMRC ticket for given VM



290
291
292
293
294
295
# File 'lib/vmcontrol/main.rb', line 290

def StartVMRC vmid
  r = onblock(:vm, vmid, @client).info!
  raise "" if OpenNebula.is_error? r

  onblock(:vm, vmid).start_vmrc
end

#STATE(vmid) ⇒ Integer

Getting VM state number by ID

Parameters:

  • vmid (Integer)
    • VM ID

Returns:

  • (Integer)

    State



78
79
80
# File 'lib/vminfo/main.rb', line 78

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:



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

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

def Suspend params, log = true, trace = ["Suspend method called:#{__LINE__}"]
  trace << "Generating sys objects:#{__LINE__ + 1}"
  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
        trace << "Locking VM:#{__LINE__ + 1}"
        vm.lock 2
      rescue
        trace << "Some exception raised while suspending VM:#{__LINE__ - 2}"
        LOG_AUTO "VM wasn't suspended, but rights will be changed" if log
      end
    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:



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

def SuspendUser uid, vms = []
  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.suspend
      LOG "Locking VM##{vm.id}", "Suspend"
      vm.lock 2
    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:



44
45
46
47
48
49
50
51
# File 'lib/vmcontrol/main.rb', line 44

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)


159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/vmcontrol/main.rb', line 159

def Terminate(userid, vmid)
  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"
    return 1
  end
  Delete(userid)
  LOG "Terminating VM#{vmid}", "Terminate"
  vm = onblock(:vm, vmid)
  r = vm.info!
  raise r if OpenNebula.is_error? r

  vm.unlock # Ensure VM is unlocked
  vm.terminate true

  true
rescue => e
  return e.messages
end

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

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

Examples:

api = 'http://localhost:8009/ione/Test'
req = Net::HTTP::Post.new(api)
req.basic_auth('oneadmin:password')
r = Net::HTTP.start(api.hostname, api.port, use_ssl: api.scheme == 'https', verify_mode: OpenSSL::SSL::VERIFY_NONE) do | http |
  http.request(req)
end

Parameters:

  • msg (String)
    • message to log

Returns:



12
13
14
15
16
17
18
19
# File 'lib/useful_things/main.rb', line 12

def Test(msg, log = "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



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/vmcontrol/main.rb', line 87

def Unsuspend(params, trace = ["Resume method called:#{__LINE__}"])
  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 << "Unlocking VM:#{__LINE__ + 1}"
        vm.unlock
        trace << "Resuming VM:#{__LINE__ + 1}"
        vm.resume
      end
      trace << "Killing proccess:#{__LINE__ + 1}"
      0
    rescue => e
      [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:



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/vmcontrol/main.rb', line 113

def UnsuspendUser uid, vms = []
  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 "Unlocking VM##{vm.id}", "Unsuspend"
      vm.unlock
      LOG "Resuming VM##{vm.id}", "Unsuspend"
      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 (Integer)
    • ID of playbook to update (Mandatory)

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

  • gid (Integer)
    • Group id

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


115
116
117
118
119
120
121
# File 'modules/ansible/main.rb', line 115

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:



15
16
17
# File 'lib/server/main.rb', line 15

def uptime
  fmt_time(Time.now.to_i - STARTUP_TIME)
end

#user_exists(uid) ⇒ Object

Checks if User exists



318
319
320
# File 'lib/useful_things/main.rb', line 318

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

#UserCreate(login, pass, groupid = nil, locale = nil, balace = 0, 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

  • balance (Integer)
    • Balance to be set by default

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

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

Returns:



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

def UserCreate(, pass, groupid = nil, locale = nil, balace = 0, client: @client, object: false, type: 'vcenter')
  user = User.new(User.build_xml(0), client) # Generates user template using oneadmin user object
  allocation_result =
    begin
      user.allocate(, pass, "core", groupid.nil? ? [IONe::Settings['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

  attrs = {
    SUNSTONE: {
      LANG: locale || IONe::Settings['USERS_DEFAULT_LANG'] || 'en_US'
    }
  }
  attrs['AZURE_TOKEN'] =  if type == 'azure'
  attrs.merge! BALANCE: balace, LABELS: "IaaS" if groupid.to_i == IONe::Settings['IAAS_GROUP_ID']

  user.update(attrs.to_one_template, true)
  return user.id, user if object

  user.id
end

#UserDelete(uid) ⇒ Object

Deletes user and all his VMs



327
328
329
330
331
332
333
334
335
336
# File 'lib/useful_things/main.rb', line 327

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:



9
10
11
# File 'lib/server/main.rb', line 9

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



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

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