class Rake::Proxmox::ProxmoxApi

ProxmoxApi adopted from github.com/nledez/proxmox rubocop:disable Metrics/ClassLength

Attributes

connection_status[R]

Return connection status

  • connected

  • error

Public Class Methods

new(pve_cluster, node, username, password, realm, ssl_options) click to toggle source
→ Proxmox

Create a object to manage a Proxmox server through API

Example:

Proxmox::Proxmox.new('https://the-proxmox-server:8006/api2/json/',
                     'node', 'root', 'secret', 'pam',
                     {verify_ssl: false})

rubocop:disable Metrics/ParameterLists rubocop:disable Metrics/AbcSize

# File lib/rake/proxmox/proxmox_api.rb, line 31
def initialize(pve_cluster, node, username, password, realm,
               ssl_options = {}, logger = nil)
  @pve_cluster = pve_cluster
  @node = node
  @username = username
  @password = password
  @realm = realm
  @ssl_options = ssl_options
  @connection_status = 'error'
  use_default_logger = logger.nil?
  logger ||= Logger.new STDERR
  # set default loglevel
  logger.level = Logger::WARN if use_default_logger
  user_agent = "rake-proxmox #{Rake::Proxmox::VERSION}"
  @site = Faraday.new(url: @pve_cluster, headers: {
                        user_agent: user_agent
                      }) do |conn|
    # POST/PUT params encoders:
    conn.request :multipart
    conn.request :url_encoded

    # allow Faraday to retry request
    conn.request :retry, max: 3, interval: 0.05,
                         interval_randomness: 0.5, backoff_factor: 2,
                         exceptions: %w[HTTPClient::KeepAliveDisconnected
                                        Timeout::Error]

    conn.response :json, content_type: /\bjson$/
    conn.response :logger, logger do |log|
      log.filter(/(Csrfpreventiontoken:)\s+(.*)$/, '\1 "[REMOVED]"')
      log.filter(/(Cookie:)\s+(.*)$/, '\1 "[REMOVED]"')
    end

    # Last middleware must be the adapter:
    conn.adapter :httpclient do |client| # yields HTTPClient
      client.cookie_manager = nil
    end
  end
  @auth_params = create_ticket
end

Public Instance Methods

cluster_resources_get(type) click to toggle source

cluster Methods

# File lib/rake/proxmox/proxmox_api.rb, line 458
def cluster_resources_get(type)
  http_action_get("cluster/resources?type=#{type}")
end
cluster_status() click to toggle source

get cluster status

# File lib/rake/proxmox/proxmox_api.rb, line 463
def cluster_status
  http_action_get('cluster/status')
end
delete(path) click to toggle source
# File lib/rake/proxmox/proxmox_api.rb, line 84
def delete(path)
  http_action_delete(path)
end
fetch_backup_job(backupid) click to toggle source

fetch one backup job

# File lib/rake/proxmox/proxmox_api.rb, line 500
def fetch_backup_job(backupid)
  http_action_get("cluster/backup/#{backupid}")
end
fetch_backup_jobs() click to toggle source

get backup job list

# File lib/rake/proxmox/proxmox_api.rb, line 495
def fetch_backup_jobs
  http_action_get('cluster/backup')
end
get(path, args = {}) click to toggle source
# File lib/rake/proxmox/proxmox_api.rb, line 72
def get(path, args = {})
  http_action_get(path, args)
end
list_storage(node = @node, storage = 'local') click to toggle source

list storage

# File lib/rake/proxmox/proxmox_api.rb, line 485
def list_storage(node = @node, storage = 'local')
  http_action_get("nodes/#{node}/storage/#{storage}/content")
end
lxc_config(vmid) → String click to toggle source

Get CT config

Return a string as task ID

Example:

lxc_config(200)

Example return:

{
  'quotaugidlimit' => 0,
  'disk' => 0,
  'ostemplate' => 'ubuntu-10.04-standard_10.04-4_i386.tar.gz',
  'hostname' => 'test.test.com',
  'nameserver' => '127.0.0.1 192.168.1.1',
  'memory' => 256,
  'searchdomain' => 'domain.com',
  'onboot' => 0,
  'cpuunits' => 1000,
  'swap' => 256,
  'quotatime' => 0,
  'digest' => 'e7e6e21a215af6b9da87a8ecb934956b8983f960',
  'cpus' => 1,
  'storage' => 'local'
}
# File lib/rake/proxmox/proxmox_api.rb, line 360
def lxc_config(vmid, node = @node)
  http_action_get "nodes/#{node}/lxc/#{vmid}/config"
end
lxc_config_set(vmid, parameters) → Nil click to toggle source

Set CT config

Return nil

Example:

lxc_config(200, { 'swap' => 2048 })

Example return:

nil
# File lib/rake/proxmox/proxmox_api.rb, line 379
def lxc_config_set(vmid, data, node = @node)
  http_action_put("nodes/#{node}/lxc/#{vmid}/config", data)
end
lxc_delete(vmid) → String click to toggle source

Delete CT

Return a string as task ID

Example:

lxc_delete(200)

Example return:

UPID:localhost:000BC66A:1279E395:521EFC4E:vzdelete:200:root@pam:
# File lib/rake/proxmox/proxmox_api.rb, line 250
def lxc_delete(vmid, node = @node)
  http_action_delete "nodes/#{node}/lxc/#{vmid}"
end
lxc_get → Hash click to toggle source

Get CT list

Return a Hash of all lxc container

Example:

lxc_get

Example return:

{
  '101' => {
        'maxswap' => 536870912,
        'disk' => 405168128,
        'ip' => '192.168.1.5',
        'status' => 'running',
        'netout' => 272,
        'maxdisk' => 4294967296,
        'maxmem' => 536870912,
        'uptime' => 3068073,
        'swap' => 0,
        'vmid' => '101',
        'nproc' => '10',
        'diskread' => 0,
        'cpu' => 0.00031670581100007,
        'netin' => 0,
        'name' => 'test2.domain.com',
        'failcnt' => 0,
        'diskwrite' => 0,
        'mem' => 22487040,
        'type' => 'lxc',
        'cpus' => 1
  },
  [...]
}
# File lib/rake/proxmox/proxmox_api.rb, line 200
def lxc_get(node = @node)
  data = http_action_get "nodes/#{node}/lxc"
  ve_list = {}
  data.each do |ve|
    ve_list[ve['vmid']] = ve
  end
  ve_list
end
lxc_post(ostemplate, vmid) → String click to toggle source
lxc_post(ostemplate, vmid, options) → String

Create CT container

Return a String as task ID

Examples:

lxc_post('ubuntu-10.04-standard_10.04-4_i386', 200)
lxc_post('ubuntu-10.04-standard_10.04-4_i386', 200, \
  {'hostname' => 'test.test.com', 'password' => 'testt' })

Example return:

UPID:localhost:000BC66A:1279E395:521EFC4E:vzcreate:200:root@pam:
# File lib/rake/proxmox/proxmox_api.rb, line 227
def lxc_post(ostemplate, vmid, config = {}, node = @node)
  config['vmid'] = vmid
  config['ostemplate'] = ostemplate
  vm_definition = config.to_a.map { |v| v.join '=' }.join '&'

  http_action_post("nodes/#{node}/lxc", vm_definition)
end
lxc_shutdown(vmid) → String click to toggle source

Shutdown CT

Return a string as task ID

Example:

lxc_shutdown(200)

Example return:

UPID:localhost:000BC66A:1279E395:521EFC4E:vzshutdown:200:root@pam:
# File lib/rake/proxmox/proxmox_api.rb, line 326
def lxc_shutdown(vmid, node = @node)
  http_action_post "nodes/#{node}/lxc/#{vmid}/status/shutdown"
end
lxc_snapshot(vmid, snapname, desc, node = @node) click to toggle source

LXC snapshot

# File lib/rake/proxmox/proxmox_api.rb, line 384
def lxc_snapshot(vmid, snapname, desc, node = @node)
  data = {
    snapname: snapname,
    description: desc
  }
  http_action_post("nodes/#{node}/lxc/#{vmid}/snapshot", data)
end
lxc_snapshot_delete(vmid, snapname, node = @node) click to toggle source

LXC snapshot delete

# File lib/rake/proxmox/proxmox_api.rb, line 398
def lxc_snapshot_delete(vmid, snapname, node = @node)
  http_action_delete("nodes/#{node}/lxc/#{vmid}/snapshot/#{snapname}")
end
lxc_snapshot_list(vmid, node = @node) click to toggle source

LXC snapshot list

# File lib/rake/proxmox/proxmox_api.rb, line 393
def lxc_snapshot_list(vmid, node = @node)
  http_action_get("nodes/#{node}/lxc/#{vmid}/snapshot")
end
lxc_start(vmid) → String click to toggle source

Start CT

Return a string as task ID

Example:

lxc_start(200)

Example return:

UPID:localhost:000BC66A:1279E395:521EFC4E:vzstart:200:root@pam:
# File lib/rake/proxmox/proxmox_api.rb, line 288
def lxc_start(vmid, node = @node)
  http_action_post "nodes/#{node}/lxc/#{vmid}/status/start"
end
lxc_delete(vmid) → String click to toggle source

Get CT status

Return a string as task ID

Example:

lxc_delete(200)

Example return:

UPID:localhost:000BC66A:1279E395:521EFC4E:vzdelete:200:root@pam:
# File lib/rake/proxmox/proxmox_api.rb, line 269
def lxc_status(vmid, node = @node)
  http_action_get "nodes/#{node}/lxc/#{vmid}/status/current"
end
lxc_stop(vmid) → String click to toggle source

Stop CT

Return a string as task ID

Example:

lxc_stop(200)

Example return:

UPID:localhost:000BC66A:1279E395:521EFC4E:vzstop:200:root@pam:
# File lib/rake/proxmox/proxmox_api.rb, line 307
def lxc_stop(vmid, node = @node)
  http_action_post "nodes/#{node}/lxc/#{vmid}/status/stop"
end
post(path, args = {}) click to toggle source
# File lib/rake/proxmox/proxmox_api.rb, line 76
def post(path, args = {})
  http_action_post(path, args)
end
put(path, args = {}) click to toggle source
# File lib/rake/proxmox/proxmox_api.rb, line 80
def put(path, args = {})
  http_action_put(path, args)
end
qemu_config(vmid) click to toggle source

Get VM config

# File lib/rake/proxmox/proxmox_api.rb, line 448
def qemu_config(vmid)
  http_action_get "nodes/#{@node}/qemu/#{vmid}/config"
end
qemu_config_set(vmid, data) click to toggle source

Set VM config

# File lib/rake/proxmox/proxmox_api.rb, line 453
def qemu_config_set(vmid, data)
  http_action_put("nodes/#{@node}/qemu/#{vmid}/config", data)
end
qemu_delete(vmid) click to toggle source

Delete VM

# File lib/rake/proxmox/proxmox_api.rb, line 423
def qemu_delete(vmid)
  http_action_delete "nodes/#{@node}/qemu/#{vmid}"
end
qemu_get() click to toggle source

Get VM list

# File lib/rake/proxmox/proxmox_api.rb, line 403
def qemu_get
  data = http_action_get "nodes/#{@node}/qemu"
  ve_list = {}
  data.each do |ve|
    ve_list[ve['vmid']] = ve
  end
  ve_list
end
qemu_post(template, vmid, config = {}) click to toggle source

Create VM container

# File lib/rake/proxmox/proxmox_api.rb, line 413
def qemu_post(template, vmid, config = {})
  config['vmid'] = vmid
  config['template'] = "local%3Aisol%2F#{template}.iso"
  config['kvm'] = 1
  vm_definition = config.to_a.map { |v| v.join '=' }.join '&'

  http_action_post("nodes/#{@node}/qemu", vm_definition)
end
qemu_shutdown(vmid) click to toggle source

Shutdown VM

# File lib/rake/proxmox/proxmox_api.rb, line 443
def qemu_shutdown(vmid)
  http_action_post "nodes/#{@node}/qemu/#{vmid}/status/shutdown"
end
qemu_start(vmid) click to toggle source

Start VM

# File lib/rake/proxmox/proxmox_api.rb, line 433
def qemu_start(vmid)
  http_action_post "nodes/#{@node}/qemu/#{vmid}/status/start"
end
qemu_status(vmid) click to toggle source

Get VM status

# File lib/rake/proxmox/proxmox_api.rb, line 428
def qemu_status(vmid)
  http_action_get "nodes/#{@node}/qemu/#{vmid}/status/current"
end
qemu_stop(vmid) click to toggle source

Stop VM

# File lib/rake/proxmox/proxmox_api.rb, line 438
def qemu_stop(vmid)
  http_action_post "nodes/#{@node}/qemu/#{vmid}/status/stop"
end
storage_volume_delete(volume, node = @node, storage = 'local') click to toggle source

delete volume from storage

# File lib/rake/proxmox/proxmox_api.rb, line 490
def storage_volume_delete(volume, node = @node, storage = 'local')
  http_action_delete "nodes/#{node}/storage/#{storage}/content/#{volume}"
end
task_log(upid, node = @node, start = 0, limit = 20) click to toggle source

get task log

# File lib/rake/proxmox/proxmox_api.rb, line 117
def task_log(upid, node = @node, start = 0, limit = 20)
  data = {
    start: start,
    limit: limit
  }
  http_action_get("nodes/#{node}/tasks/#{URI.encode upid}/log", data)
end
task_status(task-id) → String click to toggle source

Get task status

  • taksstatus

  • taskstatus:exitstatus

Example:

taskstatus \
  'UPID:localhost:00051DA0:119EAABC:521CCB19:vzcreate:203:root@pam:'

Examples return:

- running
- stopped:OK
# File lib/rake/proxmox/proxmox_api.rb, line 105
def task_status(upid, node = @node)
  data = http_action_get "nodes/#{node}/tasks/#{URI.encode upid}/status"
  status = data['status']
  exitstatus = data['exitstatus']
  if exitstatus
    "#{status}:#{exitstatus}"
  else
    status.to_s
  end
end
templates → Hash click to toggle source

Get template list

Return a Hash of all templates

Example:

templates

Example return:

 {
   'ubuntu-10.04-standard_10.04-4_i386' => {
       'format' => 'tgz',
       'content' => 'vztmpl',
       'volid' => 'local:vztmpl/ubuntu-10.04-...d_10.04-4_i386.tar.gz',
       'size' => 142126884
   },
   'ubuntu-12.04-standard_12.04-1_i386' => {
       'format' => 'tgz',
       'content' => 'vztmpl',
       'volid' => 'local:vztmpl/ubuntu-12.04-...d_12.04-1_i386.tar.gz',
        'size' => 130040792
   }
}
# File lib/rake/proxmox/proxmox_api.rb, line 153
def templates
  data = http_action_get "nodes/#{@node}/storage/local/content"
  template_list = {}
  data.each do |ve|
    name = ve['volid'].gsub(%r{local:vztmpl\/(.*).tar.gz}, '\1')
    template_list[name] = ve
  end
  template_list
end
update_backup_job(jobid, data) click to toggle source

update backup job

# File lib/rake/proxmox/proxmox_api.rb, line 505
def update_backup_job(jobid, data)
  http_action_put("cluster/backup/#{jobid}", data)
end
upload_template(filename, node = @node, storage = 'local') click to toggle source

upload lxc template

# File lib/rake/proxmox/proxmox_api.rb, line 510
def upload_template(filename, node = @node, storage = 'local')
  "Template #{filename} does not exist locally" unless File.file? filename
  data = {
    content: 'vztmpl',
    filename: Faraday::UploadIO.new(filename, 'application/gzip')
  }
  http_action_post("nodes/#{node}/storage/#{storage}/upload", data)
end
vzdump_single(vmid, node = @node, storage = 'local', mode = 'snapshot', compress = 1, remove = 1, pigz = 1, lockwait = 5) click to toggle source

Backup VM

# File lib/rake/proxmox/proxmox_api.rb, line 468
def vzdump_single(vmid, node = @node, storage = 'local',
                  mode = 'snapshot', compress = 1, remove = 1, pigz = 1,
                  lockwait = 5)
  data = {
    all: 0,
    compress: compress,
    storage: storage,
    remove: remove,
    pigz: pigz,
    mode: mode,
    lockwait: lockwait,
    vmid: vmid
  }
  http_action_post("nodes/#{node}/vzdump", data)
end

Private Instance Methods

check_response(response) click to toggle source

Extract data or return error

# File lib/rake/proxmox/proxmox_api.rb, line 557
def check_response(response)
  if response.success?
    json_decode(response)['data']
  else
    "NOK: error code = '#{response.status}' data = '#{response.body}'\n"
  end
end
create_ticket() click to toggle source

Methods manages auth

# File lib/rake/proxmox/proxmox_api.rb, line 522
def create_ticket
  post_param = { username: @username, realm: @realm, password: @password }
  resp = @site.post('access/ticket', post_param)
  if resp.success?
    extract_ticket resp
  else
    @connection_status = 'error'
  end
end
extract_ticket(response) click to toggle source

Method create ticket

# File lib/rake/proxmox/proxmox_api.rb, line 533
def extract_ticket(response)
  data = response.body
  ticket = data['data']['ticket']
  csrf_prevention_token = data['data']['CSRFPreventionToken']
  unless ticket.nil?
    token = 'PVEAuthCookie=' + ticket.gsub!(/:/, '%3A').gsub!(/=/, '%3D')
  end
  @connection_status = 'connected'
  {
    CSRFPreventionToken: csrf_prevention_token,
    cookie: token
  }
end
http_action_delete(url) click to toggle source
# File lib/rake/proxmox/proxmox_api.rb, line 587
def http_action_delete(url)
  resp = @site.delete(url) do |req|
    req.headers.merge!(@auth_params)
  end
  check_response resp
end
http_action_get(url, data = {}) click to toggle source
# File lib/rake/proxmox/proxmox_api.rb, line 580
def http_action_get(url, data = {})
  resp = @site.get(url, data) do |req|
    req.headers.merge!(@auth_params)
  end
  check_response resp
end
http_action_post(url, payload = {}) click to toggle source

Methods manage http dialogs

# File lib/rake/proxmox/proxmox_api.rb, line 566
def http_action_post(url, payload = {})
  resp = @site.post(url, payload) do |req|
    req.headers.merge!(@auth_params)
  end
  check_response resp
end
http_action_put(url, data = {}) click to toggle source
# File lib/rake/proxmox/proxmox_api.rb, line 573
def http_action_put(url, data = {})
  resp = @site.put(url, data) do |req|
    req.headers.merge!(@auth_params)
  end
  check_response resp
end
json_decode(response) click to toggle source
# File lib/rake/proxmox/proxmox_api.rb, line 547
def json_decode(response)
  if response.headers.include?('Content-Type') &&
     response.headers['Content-Type'] =~ /\bjson/
    response.body
  else
    JSON.parse(response.body)
  end
end