pve initialized

This commit is contained in:
Denis Knauf 2021-04-19 20:35:39 +02:00
commit 626e4b60b3
19 changed files with 1716 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*.sw[pomnqrst]
*.gem

6
Gemfile Normal file
View file

@ -0,0 +1,6 @@
source 'https://rubygems.org'
gem 'dencli'
gem 'rest-client'
gem 'ipaddress'
gem 'activesupport'
gem 'pmap'

49
Gemfile.lock Normal file
View file

@ -0,0 +1,49 @@
GEM
remote: https://rubygems.org/
specs:
activesupport (6.1.3.1)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 1.6, < 2)
minitest (>= 5.1)
tzinfo (~> 2.0)
zeitwerk (~> 2.3)
concurrent-ruby (1.1.8)
dencli (0.3.1)
domain_name (0.5.20190701)
unf (>= 0.0.5, < 1.0.0)
http-accept (1.7.0)
http-cookie (1.0.3)
domain_name (~> 0.5)
i18n (1.8.10)
concurrent-ruby (~> 1.0)
ipaddress (0.8.3)
mime-types (3.3.1)
mime-types-data (~> 3.2015)
mime-types-data (3.2021.0225)
minitest (5.14.4)
netrc (0.11.0)
pmap (1.1.1)
rest-client (2.1.0)
http-accept (>= 1.7.0, < 2.0)
http-cookie (>= 1.0.2, < 2.0)
mime-types (>= 1.16, < 4.0)
netrc (~> 0.8)
tzinfo (2.0.4)
concurrent-ruby (~> 1.0)
unf (0.1.4)
unf_ext
unf_ext (0.0.7.7)
zeitwerk (2.4.2)
PLATFORMS
x86_64-linux
DEPENDENCIES
activesupport
dencli
ipaddress
pmap
rest-client
BUNDLED WITH
2.2.15

22
README.adoc Normal file
View file

@ -0,0 +1,22 @@
Proxmox Virtual Environment High Level API for Ruby
===================================================
This is a limited, but easier to use library for ruby.
It provides additional a command line interface for administration named `pvecli`.
The Rest-API will be used for controlling your server.
You need to provide a config-file `/etc/pve/pvecli.yml`:
auth:
username: USERNAME
password: PASSWORD
realm: pve or something like that
connect:
verify_tls: no if you do not use known CA-signed X509-Certificates
pvecli
======
This tool should usable like PVE-WebGUI, instead of low-level-tools like `pct`
or user-unfriendlier tools like `pvesh`.
So `pvecli` provides a global control over your cluster on command line.

5
bin/pvecli Executable file
View file

@ -0,0 +1,5 @@
#!/usr/bin/env ruby
require 'pathname'
$:.unshift Pathname.new(__FILE__).dirname.dirname.join('lib').to_s
require 'pve/cli'
PVE::Cli.new.call *ARGV

4
lib/pve.rb Executable file
View file

@ -0,0 +1,4 @@
module PVE
end
require_relative 'pve/proxmox'

159
lib/pve/cli.rb Normal file
View file

@ -0,0 +1,159 @@
require 'dencli'
require 'yaml'
require 'pve'
require_relative 'helper'
require_relative 'cli/base'
require_relative 'cli/ct'
require_relative 'cli/ha'
require_relative 'cli/task'
require_relative 'cli/qm'
require_relative 'cli/node'
class UsageError <RuntimeError
end
class PVE::Cli
attr_reader :cfg, :cli
def connect
@conn ||=
Proxmox.connect cfg[:auth][:username], cfg[:auth][:password],
realm: cfg[:auth][:realm], **cfg[:connect]
#RestClient.log = STDERR
@conn
end
def initialize config_file = nil
config_file ||= '/etc/pve/pvecli.yml'
@cfg =
YAML.safe_load File.read( config_file), [], [], false,
config_file, symbolize_names: true
@cli = DenCli.new File.basename($0), "PVE CLI"
@interactive = false
prepare
end
def interactive?
@interactive
end
def enter host, *args
r = host.enter *args
STDERR.puts "! #{$?.exitstatus}" unless r
end
def wait_state host, state, timeout: nil, lock: nil
spinners = %w[- / | \\]
spin = 0
r =
host.wait state, lock: lock, timeout: timeout, secs: 0.2 do |state, lock|
lock = " (locked: #{lock})" if lock
STDERR.printf "\r[%s] %s Still %s%s...\e[J\n", host.name, spinners[spin = (spin + 1) % 4], state, lock
end
STDERR.printf "\r\e[J"
exit 1 unless interactive? and r
end
def wait task, secs: nil, text: nil
secs ||= 0.1
spinners, spin, logn = "▖▘▝▗", 0, 0
STDERR.puts task.upid
loop do
s = task.status
if s[:exitstatus]
STDERR.printf "\r[%s] %s %s\e[J\n",
task.host ? task.host.name : s[:id],
case s[:exitstatus]
when "OK" then "\e[32;1m✓\e[0m"
else "\e[31;1m✗\e[0m"
end,
s[:status]
return task
end
log = task.log start: logn
log = [] if [{n: 1, t: 'no content'}] == log
unless log.empty?
STDERR.printf "\r\e[J"
log.each {|l| puts l[:t] }
logn = log.last[:n]
end
STDERR.printf "\r[%s] \e[33;1m%s\e[0m %s...\e[J", task.host ? task.host.name : s[:id], spinners[spin = (spin + 1) % 4], text || "Working"
sleep secs
end
end
def start host, node: nil, timeout: nil, fire: nil, secs: nil
timeout ||= 30
if node
task = host.migrate Proxmox::Node.find_by_name!( node)
wait task, text: "Migrating"
end
if host.running?
STDERR.puts "Already running."
return
end
task = host.start
unless fire
wait task, text: "Starting"
end
end
def stop host, timeout: nil, fire: nil, secs: nil
timeout ||= 30
if host.stopped?
STDERR.puts "Already stopped."
return
end
task = host.stop
unless fire
wait task, text: "Stopping"
end
end
def create klass, template, timeout: nil, fire: nil, secs: nil, start: nil, **options
options[:start] = true if fire and start
task = klass.create template, **options
return if fire
wait task, text: "Creating"
host = task.host.refresh!
start host, timeout: timeout, secs: secs
end
def destroy ct, timeout: nil, fire: nil, secs: nil
task = ct.destroy
unless fire
wait task, text: "Destroying"
end
end
def help cl, *args
STDERR.puts cl.help( *args)
exit 1 unless interactive?
end
def opts_wait cl
cl.
opt( :timeout, "-t", "--timeout=TIMEOUT", "Wait for max TIMEOUT seconds (default: endless)", default: nil).
opt( :secs, "-s", "--seconds=SECONDS", "Check every SECONDS for state (default: 0.2)", default: 0.2).
opt( :fire, "-f", "--[no-]fire", "Do not wait till running", default: false)
end
def prepare
cli_node
cli_ct
cli_qm
cli_task
cli_ha
cli_base
end
def call *argv
cli.call *argv
rescue RestClient::ExceptionWithResponse
STDERR.puts "#$! - #{$!.response} (#{$!.class})", $!.backtrace.map {|b|" #{b}"}
rescue UsageError, DenCli::UsageError
STDERR.puts $!
exit 1
end
end

187
lib/pve/cli/base.rb Normal file
View file

@ -0,0 +1,187 @@
require 'pmap'
class PVE::Cli
def cli_base
cli.cmd :list, "List CT/VM-IDs", aliases: ['ls'], &lambda {|target=nil|
connect
nodes = Proxmox::Node.all
nodes.
flat_map {|n| [ n.method(:lxc), n.method(:qemu) ] }.
flat_pmap {|m| m.call.map {|c| c.vmid.to_i } }.
sort.
each {|c| puts c }
}
cli.cmd( :status, "Lists Nodes/VMs/CTs with status", &lambda {|target=nil, sort: 'n', node: nil|
connect
node &&= /\A#{node}\z/
to = TablizedOutput.new %w[Status HA ID Name Host Uptime CPU/% Mem/MiB Mem/% Disk/MiB Disk/%]
push =
if target
target = /\A#{target}\z/
lambda {|n| to.virt n if n === target }
else
lambda {|n| to.virt n }
end
nodes = Proxmox::Node.all
nodes.
select {|n| not node or n === node }.
flat_map {|n| [ n.method(:lxc), n.method(:qemu) ] }.
each {|m| m.call.each &push }
to.print order: sort.each_char.map {|c| (2*c.ord[5]-1) * (' sainhucmd'.index( c.downcase)) }
}).
opt( :sort, '-s', '--sort=COLUMNS', "Sort by COLUMNs eg hn for host and name ([s]tatus, h[a], [i]d, [n]ame (default), [h]ost, [u]ptime, [c]pu, [m]em, [d]isk)").
opt( :node, '-n', '--node=NODE', "List only hosted by this NODE")
def prepare_show_config cnf
r = {}
cnf.each do |k,v|
case k
when :network
v.each do |net|
s =
net.
reject {|k, v| :card == k }.
sort_by {|k, v| :name == k ? :AAAAAAAAA : k }.
map {|k, v| case v when true then [k,1] when false then [k,0] else [k,v] end }.
map {|k, v| "#{k}=#{v}" }
r[net[:card].to_sym] = s.join(",")
end
when :sshkeys
r[k] = CGI.unescape(v).gsub( /^/, " "*14).gsub /\A {14}|\n\z/, ''
else
case v
when true then v = 1
when false then v = 0
end
r[k] = v.to_s.gsub( /$^/, " "*14).gsub /\n\z/, ''
end
end
r
end
def show_config cnf, old = nil
cnf = prepare_show_config cnf
if old
old = prepare_show_config old
(cnf.keys+old.keys).uniq.sort.each do |k|
v, o = cnf[k], old[k]
if v == o
puts "#{k}:#{' ' * (12-k.length)} #{v}"
else
puts "\e[31m#{k}:#{' ' * (12-k.length)} #{o}\e[0m" unless o.nil?
puts "\e[32m#{k}:#{' ' * (12-k.length)} #{v}\e[0m" unless v.nil?
end
end
else
cnf.sort_by{|k,v|k}.each do |k,v|
puts "#{k}:#{' ' * (12-k.length)} #{v}"
end
end
end
cli.sub :config, "CT/VM Configuration", min: 2, aliases: %w[cnf] do |ccli|
ccli.cmd 'help', '', aliases: [nil, '-h', '--help'], &lambda {|*args| help ccli, *args }
ccli.cmd :show, "Show Config of CT/VM", &lambda {|name_or_id|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
show_config th.config
}
ccli.cmd :set, "Set Configs for CT/VM", &lambda {|name_or_id, *args|
if %w[-h --help].include? name_or_id
STDERR.puts "Usage: set -h|--help # Show help"
STDERR.puts " set ct|vm --CNF1=VAL1 --CNF2=VAL2 ... # Set config-value. Empty value clears field."
exit 1
end
opts = {}
until args.empty?
case arg = args.shift
when /\A--(\w+)=(.*)\z/
opts[$1.to_sym] = $2
when /\A--(\w+)\z/
opts[$1.to_sym] = args.shift
else
raise UsageError, "Expection option to set. What do you mean with: #{arg}"
end
end
opts.each do |k, v|
opts[k] =
case v = opts[k]
when '' then nil
else v
end
end
%i[migrate_downtime].each do |k|
next unless opts.has_key? k
opts[k] =
case v = opts[k]
when nil, '', 'nil' then nil
else v.to_f
end
end
%i[memory background_delay balloon cores cpulimit cpuunits migrate_speed shares smp sockets vcpus swap tty].each do |k|
next unless opts.has_key? k
opts[k] =
case v = opts[k]
when nil, '', 'nil' then nil
else v.to_i
end
end
%i[unprivileged debug onboot protection template].each do |k|
next unless opts.has_key? k
opts[k] =
case v = opts[k]
when *%w[1 T TRUE t true True Y YES y yes Yes] then true
when *%w[0 F FALSE f false False N NO n no No] then false
when '', 'nil', nil then nil
else raise UsageError, "Boolean expected, given: #{v.inspect}"
end
end
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
old = th.config
opts[:digest] ||= old[:digest]
th.cnfset opts
show_config th.config, old
}
end
cli.cmd :enter, "Enter Console of CT/Node", &lambda {|name_or_id|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Node.find_by_name( name_or_id)
raise UsageError, "Container or Node not found: #{name_or_id}" unless th
STDERR.puts "! #{$?.exitstatus}" unless th.enter
}
cli.cmd :run, "Starts CT/VM", aliases: %w[start star], &lambda {|name_or_id|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "Container or Node not found: #{name_or_id}" unless th
start th
}
#cli.cmd :reboot, "Reboot CT/VM (not implemented, yet)", min: 6, &lambda {|name_or_id|
# connect
# th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
# raise UsageError, "Container or Node not found: #{name_or_id}" unless th
# reboot th
#}
cli.cmd :stop, "Stops CT/VM", min: 4, &lambda {|name_or_id|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "Container or Node not found: #{name_or_id}" unless th
stop th
}
cli.cmd 'help', '', aliases: ['-h', '--help'], &lambda {|*args| help cli, *args }
cli.cmd 'cli', 'Opens interactive console', min: 3, aliases: [nil], &lambda {
@interactive = true
cli.interactive( File.basename($0,'.rb')).run
}
end
end

115
lib/pve/cli/ct.rb Normal file
View file

@ -0,0 +1,115 @@
class PVE::Cli
def cli_ct
cli.sub :ct, "Containers", aliases: %w[lx lxc] do |ct_cli|
ct_cli.cmd :list, "List CT-IDs", aliases: ['ls'], &lambda {|node=nil|
connect
nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node
nodes.flat_map do |n|
n.lxc.map {|c| c.vmid.to_i }
end.sort.each {|c| puts c }
}
ct_cli.cmd :status, "List CTs with status", aliases: [nil], &lambda {|node=nil|
connect
to = TablizedOutput.new %w[Status HA ID Name Host Uptime CPU Mem/MiB Disk/MiB]
nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node
nodes.each do |n|
n.lxc.each &to.method( :virt)
end
to.print order: [3]
}
ct_cli.cmd :enter, "Enter Console of CT", &lambda {|name_or_id|
connect
STDERR.puts "! #{$?.exitstatus}" unless Proxmox::LXC.find!( name_or_id).enter
}
ct_cli.cmd :exec, "Executes Command in CT", min: 4, &lambda {|name_or_id, *command|
connect
STDERR.puts "! #{$?.exitstatus}" unless Proxmox::LXC.find!( name_or_id).exec *command
}
ct_cli.cmd( :start, "Starts CT", min: 3, &lambda {|name_or_id, node: nil, fire:, timeout:, secs:|
connect
ct = Proxmox::LXC.find! name_or_id
start ct, node: node, fire: fire, timeout: timeout, secs: secs
}).
opt( :node, "-nNODE", "--node=NODE", "On NODE (default, as is, so without migration)").
tap {|c| opts_wait c }
ct_cli.cmd( :stop, "Stops CT", min: 3, &lambda {|name_or_id, fire: nil, timeout:, secs:|
connect
ct = Proxmox::LXC.find! name_or_id
stop ct, fire: fire, timeout: timeout, secs: secs
}).tap {|c| opts_wait c }
ct_cli.cmd( :wait, "Wait till CT is in state", &lambda {|name_or_id, state, timeout: nil, secs: nil|
connect
ct = Proxmox::LXC.find! name_or_id
wait ct, state, timeout: timeout, secs: secs
}).
opt( :timeout, "-tTIMEOUT", "--timeout=TIMEOUT", "Wait for max TIMEOUT seconds (default: endless)", default: nil).
opt( :secs, "-sSECONDS", "--seconds=SECONDS", "Check every SECONDS for state (default: 0.2)", default: 0.2)
ct_cli.cmd( :create, "Creates a new container", &lambda {|template, *options| #, fire:, timeout:, secs:, start:|
if %w[-h --help].include? template
STDERR.puts "Usage: ct create TEMPLATE -h # Shows template-related options"
STDERR.puts " ct create TEMPLATE [OPTIONS] # Creates a container"
exit 1
end
ctopts = {}
OptionParser.new do |opts|
opts.banner = <<EOU
Usage: ct create #{template} [options]
Options: (*=Required)
EOU
opts.on '-h', '--help', " Help!" do
STDERR.puts opts
exit 1 unless interactive?
return
end
opts.on( '-r', '--[no-]-start', " Start container after creation") {|v| ctopts[:start] = v }
opts.on( '-f', '--[no-]-fire', " Do not wait till running") {|v| ctopts[:start] = v }
opts.on( '-t', '--timeout=TIMEOUT', " Wait for max TIMEOUT seconds (default: endless)") {|v| ctopts[:timeout] = v }
opts.on( '-s', '--seconds=SECONDS', " Check every SECONDS for state (default: 0.2)") {|v| ctopts[:seconds] = v }
ctt = PVE::CTTemplate.const_get template.classify
ctt.requirements.each do |name, (type, req, desc, *args)|
req = req ? "*" : " "
case type
when :boolean
opts.on( "--[no-]#{name}", "#{req}#{desc}") {|v| ctopts[name] = v }
when :string, :numeric
opts.on( "--#{name}=#{type.upcase}", "#{req}#{desc}") {|v| ctopts[name] = v }
when :enum
opts.on( "--#{name}=#{type.upcase}", "#{req}#{desc} (#{args.first.join ', '})") do |v|
ctopts[name] = v
end
end
end
end.parse! options
connect
create Proxmox::LXC, template, **ctopts
})
ct_cli.cmd( :config, '', &lambda {|name_or_id|
connect
ct = Proxmox::LXC.find! name_or_id
STDOUT.puts ct.config.to_json
})
ct_cli.cmd( :destroy, '', min: 7, &lambda {|name_or_id, fire:, secs:, timeout:, i_really_want_to_destroy:|
raise UsageError, "Name/ID is not what you want to destroy" unless name_or_id == i_really_want_to_destroy
connect
ct = Proxmox::LXC.find! name_or_id
raise UsageError, "Container is not stopped" unless ct.stopped?
destroy ct, fire: fire, timeout: timeout, secs: secs
}).tap {|c| opts_wait c }.
opt( :i_really_want_to_destroy, "--i-really-want-to-destroy=NAMEORID", "Repeat the name/ID")
ct_cli.cmd( :help, '', aliases: ['-h', '--help']) {|*args| help ct_cli, *args }
end
end
end

78
lib/pve/cli/ha.rb Normal file
View file

@ -0,0 +1,78 @@
class PVE::Cli
def opts_ha cl
cl.
opt( :group, "-gGROUP", "--group=GROUP", "Put host in GROUP", default: 'all').
opt( :comment, "-cCOMMENT", "--comment=COMMENT", "Set comment").
opt( :max_relocate, "-lCOUNT", "--max-relocate=COUNT", "How often host can be relocate before givingup?", default: 2).
opt( :max_restart, "-rCOUNT", "--max-restart=COUNT", "How often host can be restarted before givingup?", default: 2).
opt( :state, "-sSTATE", "--state=STATE", "Host should have STATE. If you start/stop be `pct/qm/e start/stop` STATE will be set before action.", default: "started")
end
def cli_ha
cli.sub :ha, "Inspect High-Availability" do |hacli|
hacli.cmd( :create, "Create HA for CT/VM", &lambda {|name_or_id, group:, comment: nil, max_relocate:, max_restart:, state:|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "Container or VirtualMachine not found: #{name_or_id}" unless th
ha = th.ha
raise UsageError, "#{th.sid} is already High-Available" unless ha.active?
ha.create group: group, comment: comment, max_relocate: max_relocate, max_restart: max_restart
}).tap {|cl| opts_ha cl }
hacli.cmd :remove, "Remove CT/VM from HA", &lambda {|name_or_id|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "Container or VirtualMachine not found: #{name_or_id}" unless th
ha = th.ha
raise UsageError, "#{th.sid} is not High-Available" if ha.active?
ha.delete
}
hacli.cmd( :active, "CT/VM should be high-available. Options are only for defaults, if not activated, yet.", &lambda {|name_or_id, group:, comment: nil, max_relocate:, max_restart:, state:|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "Container or VirtualMachine not found: #{name_or_id}" unless th
ha = th.ha
ha.create group: group, comment: comment, max_relocate: max_relocate, max_restart: max_restart if ha.active?
}).tap {|cl| opts_ha cl }
hacli.cmd :deactive, "CT/VM should NOT be high-available.", &lambda {|name_or_id|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "Container or VirtualMachine not found: #{name_or_id}" unless th
ha = th.ha
ha.delete unless ha.active?
}
hacli.cmd( :started, "CT/VM should be in state started. By stopping CT/VM via pct/e state will be changed in HA, too.", &lambda {|name_or_id, force: nil|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "Container or VirtualMachine not found: #{name_or_id}" unless th
ha = th.ha
ha = ha.create unless ha.active?
ha.disabled! if force and ha.error?
ha.started!
}).opt( :force, "-f", "--force", "If CT/VM is in error-state, first disable HA, than try to start.")
hacli.cmd :stopped, "CT/VM should be in state stopped. By starting CT/VM via pct/e state will be changed in HA, too.", min: 3, &lambda {|name_or_id|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "Container or VirtualMachine not found: #{name_or_id}" unless th
ha = th.ha
ha = ha.create unless ha.active?
ha.stopped!
}
hacli.cmd :reset, "If state of CT/VM is failed, Proxmox will not start/stop it anyway. You have to reset state (state=disabled), first", &lambda {|name_or_id|
connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "Container or VirtualMachine not found: #{name_or_id}" unless th
ha = th.ha
raise UsageError, "#{th.sid} is not High-Available" if ha.active?
ha.state = :disabled
}
hacli.cmd 'help', '', aliases: ['-h', '--help'], &lambda {|*args| help hacli, *args }
end
end
end

46
lib/pve/cli/node.rb Normal file
View file

@ -0,0 +1,46 @@
class PVE::Cli
def cli_node
cli.sub :node, "Nodes" do |nod_cli|
nod_cli.cmd :status, "Lists nodes with status", aliases: [nil], &lambda {|node=nil|
connect
to = TablizedOutput.new %w[Status Node Uptime CPU Mem/MiB Disk/MiB]
nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node
nodes.each do |n|
to.push [
n.status,
n.node,
Measured.seconds( n.uptime),
"%.02f/%d" % [n.cpu, n.maxcpu],
"#{Measured.bytes( n.mem)}/#{Measured.bytes( n.maxmem)}",
"#{Measured.bytes( n.disk)}/#{Measured.bytes( n.maxdisk)}",
]
end
to.print order: [1]
}
nod_cli.cmd :exec, "Executes command on node", min: 4 do |name, *args|
connect
STDERR.puts "! #{$?.exitstatus}" unless Proxmox::Node.find_by_name!( name).exec *args
end
nod_cli.cmd :enter, "Enter Console of node" do |name, *args|
connect
STDERR.puts "! #{$?.exitstatus}" unless Proxmox::Node.find_by_name!( name).enter *args
end
nod_cli.sub :task, "Inspect tasks" do |tcli|
tcli.cmd :list, "List done tasks", aliases: [nil, 'ls'], &lambda {|node|
connect
Proxmox::Node.find_by_name!( node).
tasks.
map( &:upid).
sort.
each {|upid| puts upid }
}
end
nod_cli.cmd( 'help', '', aliases: ['-h', '--help']) {|*args| help nod_cli, *args }
end
end
end

32
lib/pve/cli/qm.rb Normal file
View file

@ -0,0 +1,32 @@
class PVE::Cli
def cli_qm
cli.sub :qm, "Virtual Machines", aliases: %w[v vm qemu], &lambda {|qm|
qm.cmd :list, "List VM-IDs", aliases: ['ls'], &lambda {|node=nil|
connect
nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node
nodes.flat_map do |n|
n.qemu.map {|c| c.vmid.to_i }
end.sort.each {|c| puts c }
}
qm.cmd :status, "List VMs with status", aliases: [nil], &lambda {|node=nil|
connect
to = TablizedOutput.new %w[Status HA ID Name Host Uptime CPU Mem/MiB Disk/MiB]
nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node
nodes.each do |n|
n.qemu.each &to.method( :virt)
end
to.print order: [3]
}
qm.cmd :exec, "Executes Command in VM via qemu-guest-agent", min: 4, &lambda {|name_or_id, *command|
connect
STDERR.puts "! #{$?.exitstatus}" unless Proxmox::Qemu.find!( name_or_id).exec *command
}
qm.cmd 'help', '', aliases: ['-h', '--help'], &lambda {|*args| help qm, *args }
}
end
end

26
lib/pve/cli/task.rb Normal file
View file

@ -0,0 +1,26 @@
class PVE::Cli
def cli_task
cli.sub :task, "Inspect tasks" do |tcli|
tcli.cmd :list, "List done tasks", &lambda {|node=nil|
connect
nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node
nodes.flat_map do |n|
n.tasks.map &:upid
end.sort.each {|upid| puts upid }
}
tcli.cmd :get, "Inspect a task", &lambda {|upid|
connect
Proxmox::Node.all.each do |n|
n.tasks.each do |t|
next unless t.upid == upid
puts t.upid
t.log.each {|l| puts l[:l] }
return
end
end
}
end
end
end

167
lib/pve/helper.rb Normal file
View file

@ -0,0 +1,167 @@
class Measured
class <<self
def bytes1 v
v = v.to_f
return "%d B" % v if 512 > v
%w[KiB MiBy GiByt TiByte ExiByte PetiByte].each_with_index do |m|
v /= 1024
#return "%.1f %s" % [v, m] if 10 > v
#return "%d %s" % [v, m] if 512 > v
return "%.1f %s" % [v, m] if 512 > v
end
"%d PetiByte" % v
end
def bytes2 v
r = (v.to_i / 1024 / 1024).to_s
return '·' if 0 == r
r.
reverse.
each_char.
each_slice( 3).
to_a.
reverse.
map {|a| a.reverse.join }.
join " "
end
alias bytes bytes2
def seconds i
i = i.to_i
return '·' if 0 == i
return "%d s" % i if 90 > i
i /= 60
return "%d mi" % i if 90 > i
i /= 60
return "%d hou" % i if 36 > i
i /= 24
return "%d days" % i if 14 > i
j = i / 7
return "%d weeks" % j if 25 > j
i /= 365
return "%.1f years" if 550 > i
"%dy" % i
end
end
end
class ColoredString
attr_reader :string, :color_codes
def initialize string, color_codes
@string, @color_codes = string, color_codes
end
def inspect
"#<ColoredString #{@color_codes} #{@string.inspect}>"
end
def length() @string.length end
alias size length
#def to_str() self end
def to_s() "\e[#{@color_codes}m#{@string}\e[0m" end
alias to_str to_s
#alias inspect to_str
include Comparable
def <=>(o) @string <=> o.string end
end
class TablizedOutput
def initialize header, stdout: nil
@header = header.map &:to_s
@columnc = header.size
@maxs = header.map &:length
@stdout ||= STDOUT
@lines = []
end
class B
include Comparable
def <=>(o) @v <=> o.v end
end
class V < B
attr_reader :v, :s
def initialize( v, s=nil) @v, @s = v, s || "#{v}" end
def to_s() @s end
def length() @s.length end
def inspect() "#<TO:V #{@v.inspect} #{@s.inspect}>" end
end
class Percentage < B
attr_reader :v, :w
def initialize( v, w=nil) @v, @w = v, w || 10 end
def length() @w end
def inspect() "#<TO:Percentage #{@v}%>" end
def to_s
y = w - (v*w).round
x = (100*v).round
r = "%*s" % [w, 0==x ? '·' : x]
"\e[0m#{r[0...y]}\e[1;4;#{0.75>v ? 32 : 31}m#{r[y..-1]}\e[0m"
end
end
def push fields
fields =
fields.map do |x|
case x
when String, ColoredString, B then x
else V.new x
end
end
@maxs = @columnc.times.map {|i| [@maxs[i], fields[i].length].max }
@lines.push fields
end
def pushs lines
lines.each &method( :push)
end
def print order: nil
format = "#{(["\e[%%sm%% %ds\e[0m"] * @columnc).join( ' ') % @maxs}\n"
ls = @lines
if order
eval <<-EOC, binding, __FILE__, 1+__LINE__
ls = ls.sort {|a,b|
[#{order.map {|i| 0 < i ? "a[#{i-1}]" : "b[#{-i-1}]" }.join ', '}] <=>
[#{order.map {|i| 0 < i ? "b[#{i-1}]" : "a[#{-i-1}]" }.join ', '}]
}
EOC
end
#ls = ls.sort_by {|e| p e; order.map &e.method(:[]) } if order
@stdout.printf format, *@header.flat_map {|s|['',s]}
ls.each {|l| @stdout.printf format, *l.flat_map {|s| s.is_a?(ColoredString) ? [s.color_codes, s.string] : ["", s.to_s] } }
end
def virt v
ha = v.respond_to?( :ha) ? v.ha : nil
unknown = V.new 0, '-'
push [
case v.status
when "running", "online" then ColoredString.new v.status, "32"
when "stopped" then ColoredString.new v.status, "31"
else v.status
end,
ha&.state || '·',
case v.t
when "nd" then ColoredString.new v.sid, "33"
when "qm" then ColoredString.new v.sid, "35"
when "ct" then ColoredString.new v.sid, "36"
else v.sid
end,
v.name, v.node.is_a?(String) ? v.node : v.node.node,
v.respond_to?(:uptime) ? V.new( v.uptime, Measured.seconds( v.uptime)) : unknown,
v.respond_to?(:cpu) ? Percentage.new( v.cpu) : unknown,
v.respond_to?(:mem) ? V.new( v.mem, Measured.bytes( v.mem)) : unknown,
v.respond_to?(:maxmem) ? Percentage.new( v.mem/v.maxmem.to_f) : unknown,
v.respond_to?(:disk) ? V.new( v.disk.to_i, Measured.bytes( v.disk.to_i)) : unknown,
if v.respond_to?(:maxdisk) and 0 < v.maxdisk.to_i
Percentage.new( v.disk.to_f/v.maxdisk.to_f)
else unknown end,
]
end
end

597
lib/pve/proxmox.rb Normal file
View file

@ -0,0 +1,597 @@
require 'rest_client'
require 'cgi'
require 'json'
require 'ipaddress'
require 'shellwords'
require 'active_support/all'
module Proxmox
class Exception < ::Exception
end
class NotFound < Exception
end
class AlreadyExists < Exception
end
def self.connect username, password, realm: nil, verify_tls: nil, uri: nil
uri ||= 'https://localhost:8006/api2/json'
cred =
{
username: username,
password: password,
realm: realm || 'pve'
}
@@connection =
RestClient::Resource.new( uri, verify_ssl: ! ! verify_tls).tap do |rs|
resp = rs['/access/ticket'].post cred
case resp.code
when 200
data = JSON.parse resp.body, symbolize_names: true
@@api_ticket =
{
CSRFPreventionToken: data[:data][:CSRFPreventionToken],
cookie: "PVEAuthCookie=#{CGI.escape data[:data][:ticket]}"
}
else
raise Exception, "Authentication failed"
end
end
end
def self.connection
@@connection
end
def self.api_ticket
@@api_ticket
end
def self.find_by_name name
Proxmox::LXC.find_by_name( name) || Proxmox::Qemu.find_by_name( name) || Proxmox::Node.find_by_name( name)
end
def self.find_by_vmid vmid
Proxmox::LXC.find_by_vmid( vmid) || Proxmox::Qemu.find_by_vmid( vmid) || Proxmox::Node.find_by_vmid( vmid)
end
def self.find name_or_id
Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find( name_or_id) || Proxmox::Node.find( name_or_id)
end
module RestConnection
def __response__ resp
case resp.code
when 200
JSON.parse( resp.body, symbolize_names: true)[:data]
when 500
nil
else
raise "Request failed of #{req.url} [#{resp.code}]: #{resp.body.inspect}"
end
end
def __headers__ **hdrs
Proxmox.api_ticket.merge( 'Accept' => 'application/json').merge( hdrs)
end
def __data__ **data
case data
when String
data
else
data.to_json
end
end
private :__response__, :__headers__, :__data__
def bench path
#t = Time.now
r = yield
#p path => Time.now-t
r
end
def rest_get path, **data, &exe
data = data.delete_if {|k,v|v.nil?}
path += "#{path.include?( ??) ? ?& : ??}#{data.map{|k,v|"#{CGI.escape k.to_s}=#{CGI.escape v.to_s}"}.join '&'}" unless data.empty?
__response__ Proxmox.connection[path].get( __headers__( :'Content-Type' => 'application/json'))
end
def rest_put path, **data, &exe
__response__ Proxmox.connection[path].put( __data__( data), __headers__( :'Content-Type' => 'application/json'))
end
def rest_del path, &exe
__response__ Proxmox.connection[path].delete( __headers__( :'Content-Type' => 'application/json'))
end
def rest_post path, **data, &exe
__response__ Proxmox.connection[path].post( __data__( data), __headers__( :'Content-Type' => 'application/json'))
end
end
class Base
include RestConnection
extend RestConnection
attr_reader :sid
class <<self
def __new__ data
n = allocate
n.send :__update__, data
end
private :__new__
end
def respond_to? method
super or instance_variable_defined?( "@#{method}")
end
def method_missing method, *args, &exe
if instance_variable_defined? "@#{method}"
instance_variable_get "@#{method}"
else
super
end
end
def __update__ data
instance_variables.each do |k|
remove_instance_variable k
end
data.each do |k,v|
instance_variable_set "@#{k}", v
end
initialize
self
end
def refresh!
__update__ rest_get( @rest_prefix)
end
end
class Node < Base
class <<self
def find_by_name name
all.each do |node|
return node if node.node == name
end
nil
end
def find_by_name! name
find_by_name( name) or raise( Proxmox::NotFound, "Node not found: #{name}")
end
def all
rest_get( '/nodes').map {|d| __new__ d.merge( t: 'nd') }
end
end
attr_reader :name
def === t
@name =~ t or @vmid.to_s =~ t or @sid =~ t
end
def initialize
@rest_prefix = "/nodes/#{@node}"
@sid = "nd:#{@node}"
@name = @node
end
def offline?() @status.nil? or 'offline' == @status end
def online?() 'online' == @status end
def lxc
return [] if offline?
rest_get( "#{@rest_prefix}/lxc").map {|d| LXC.send :__new__, d.merge( node: self, t: 'ct') }
end
def qemu
return [] if offline?
rest_get( "#{@rest_prefix}/qemu").map {|d| Qemu.send :__new__, d.merge( node: self, t: 'qm') }
end
def tasks
return [] if offline?
rest_get( "/#{@rest_prefix}/tasks").map {|d| Task.send :__new__, d.merge( node: self, t: 'task') }
end
def enter *command
Kernel.system 'ssh', '-t', node, command.map( &:to_s).shelljoin
end
def exec *command
Kernel.system 'ssh', node, command.map( &:to_s).shelljoin
end
end
class Task < Base
def initialize
@rest_prefix = "/nodes/#{@node.node}/tasks/#{upid}"
@sid = upid
end
def inspect
"#<#{self.class.name} #{upid}>"
end
#def finished?
# rest_get( "/nodes/#{node}/tasks/")
#end
def status
rest_get( "#{@rest_prefix}/status")
end
def log start: nil, limit: nil
rest_get( "#{@rest_prefix}/log", start: start, limit: limit)
end
end
class Hosted < Base
def refresh!
node, t = @node, @t
__update__ rest_get( "#{@rest_prefix}/status/current").merge( node: node, t: t)
end
def === t
@name =~ t or @vmid.to_s =~ t or @sid =~ t
end
def migrate node
node =
case node
when Node then node
else Node.find!( node.to_s)
end
Task.send :__new__, node: @node, host: self, upid: rest_post( "#{@rest_prefix}/migrate", target: node.node)
end
def start
Task.send :__new__, node: @node, host: self, upid: rest_post( "#{@rest_prefix}/status/start")
end
def stop
Task.send :__new__, node: @node, host: self, upid: rest_post( "#{@rest_prefix}/status/stop")
end
def destroy
Task.send :__new__, node: @node, host: self, upid: rest_del( "#{@rest_prefix}")
end
def current_status
rest_get "#{@rest_prefix}/status/current"
end
def running?
current_status[:status] == 'running'
end
def stopped?
current_status[:status] == 'stopped'
end
def wait forstatus, timeout: nil, secs: nil, lock: nil, &exe
forstatus = forstatus.to_s
secs ||= 0.2
b = Time.now + timeout.to_i + secs
loop do
d = current_status
return true if d[:status] == forstatus and (not lock or lock == d[:lock])
exe.call d[:status], d[:lock] if exe
return false if timeout and b <= Time.now
sleep secs
end
nil
end
def config
cnf = rest_get "#{@rest_prefix}/config"
cnf[:network] =
cnf.
keys.
map( &:to_s).
grep( /\Anet\d+\z/).
map do |k|
nc = {card: k}
cnf.delete( k.to_sym).
split( ',').
each do |f|
k, v = f.split( '=', 2)
nc[k.to_sym] = v
end
nc[:ip] &&= IPAddress::IPv4.new nc[:ip]
nc[:gw] &&= IPAddress::IPv4.new nc[:gw]
nc[:mtu] &&= nc[:mtu].to_i
nc[:tag] &&= nc[:tag].to_i
nc[:firewall] &&= 1 == nc[:firewall].to_i
nc
end
cnf[:unprivileged] &&= 1 == cnf[:unprivileged]
cnf[:memory] &&= cnf[:memory].to_i
cnf[:cores] &&= cnf[:cores].to_i
cnf
end
def cnfset **cnf
r = {delete: []}
cnf.each do |k,v|
case v
when true then r[k] = 1
when false then r[k] = 0
when nil then r[:delete].push k
else r[k] = v
end
end
r.delete :delete if r[:delete].empty?
rest_put "#{@rest_prefix}/config", r
end
end
class Qemu < Hosted
class <<self
def all
Node.all.flat_map {|n| n.qemu }
end
def find_by_vmid vmid
vmid = vmid.to_s
Node.all.each do |n|
n.qemu.each do |l|
return l if l.vmid == vmid
end
end
nil
end
def find_by_name name
Node.all.each do |n|
n.qemu.each do |l|
return l if l.name == name
end
end
nil
end
def find name_or_id = nil, name: nil, vmid: nil
if (name and vmid) or (name and name_or_id) or (name_or_id and vmid)
raise Proxmox::NotFound, "name xor vmid needed to find CT, not both."
elsif name
find_by_name name
elsif vmid
find_by_vmid vmid.to_i
elsif name_or_id =~ /\D/
find_by_name name_or_id
elsif name_or_id.is_a?( Numeric) or name_or_id =~ /\d/
find_by_vmid name_or_id.to_i
else
raise Proxmox::NotFound, "name xor vmid needed to find CT."
end
end
def find_by_vmid! name
find_by_vmid( name) or raise( Proxmox::NotFound, "Virtual Machine not found: #{name}")
end
def find_by_name! name
find_by_name( name) or raise( Proxmox::NotFound, "Virtual Machine not found: #{name}")
end
def find! name
find( name) or raise( Proxmox::NotFound, "Virtual Machine not found: #{name}")
end
end
def initialize
@rest_prefix = "/nodes/%s/qemu/%d" % [@node.node, @vmid]
@sid = "qm:#{@vmid}"
end
def ha
HA.find self
end
def exec *args
node.exec 'qm', 'guest', 'exec', vmid, '--', *args
end
end
class LXC < Hosted
class <<self
def all
Node.all.flat_map {|n| n.lxc }
end
def find_by_vmid vmid
vmid = vmid.to_s
Node.all.each do |n|
n.lxc.each do |l|
return l if l.vmid == vmid
end
end
nil
end
def find_by_name name
Node.all.each do |n|
n.lxc.each do |l|
return l if l.name == name
end
end
nil
end
def find name_or_id = nil, name: nil, vmid: nil
if (name and vmid) or (name and name_or_id) or (name_or_id and vmid)
raise ArgumentError, "name xor vmid needed to find CT, not both."
elsif name
find_by_name name
elsif vmid
find_by_vmid vmid.to_i
elsif name_or_id =~ /\D/
find_by_name name_or_id
elsif name_or_id.is_a?( Numeric) or name_or_id =~ /\d/
find_by_vmid name_or_id.to_i
else
raise ArgumentError, "name xor vmid needed to find CT."
end
end
def find_by_vmid! name
find_by_vmid( name) or raise( Proxmox::NotFound, "Container not found: #{name}")
end
def find_by_name! name
find_by_name( name) or raise( Proxmox::NotFound, "Container not found: #{name}")
end
def find! name
find( name) or raise( Proxmox::NotFound, "Container not found: #{name}")
end
def create template, **options
tmplt = PVE::CTTemplate.const_get( template&.classify || 'Default').new **options
name = tmplt.name
virts = Proxmox::LXC.all + Proxmox::Qemu.all
vmid = tmplt.vmid
if virt = virts.find {|v| v.vmid == vmid }
raise Proxmox::AlreadyExists, "VT/VM with vmid [#{vmid}] already exists: #{virt.name}"
end
already_exists = virts.select {|v| v.name == name }
unless already_exists.empty?
raise Proxmox::AlreadyExists, "CT/VM named [#{name}] already exists: vmid: #{already_exists.map( &:vmid).inspect}"
end
node = Proxmox::Node.find_by_name! tmplt.node
options = {
ostemplate: tmplt.ostemplate,
vmid: vmid.to_s,
arch: tmplt.arch,
cmode: tmplt.cmode,
cores: tmplt.cores.to_i,
description: tmplt.description,
hostname: tmplt.hostname,
memory: tmplt.memory,
net0: tmplt.net0&.map {|k,v| "#{k}=#{v}" }&.join(','),
net1: tmplt.net1&.map {|k,v| "#{k}=#{v}" }&.join(','),
net2: tmplt.net2&.map {|k,v| "#{k}=#{v}" }&.join(','),
net3: tmplt.net3&.map {|k,v| "#{k}=#{v}" }&.join(','),
ostype: tmplt.ostype,
:'ssh-public-keys' => tmplt.ssh_public_keys,
storage: tmplt.storage,
#rootfs: {
# volume: "root:vm-#{vmid}-disk-0", size: '4G'
#}.map {|k,v| "#{k}=#{v}" }.join( ','),
swap: tmplt.swap,
unprivileged: tmplt.unprivileged,
}.delete_if {|k,v| v.nil? }
@temp = LXC.send :__new__, node: node, vmid: options[:vmid], name: name, hostname: options[:hostname]
upid = rest_post( "/nodes/%s/lxc" % node.node, **options)
Task.send :__new__, node: node, host: @temp, upid: upid
end
end
def initialize
@rest_prefix = "/nodes/%s/lxc/%d" % [@node.node, @vmid]
@sid = "ct:#{@vmid}"
end
def ha
HA.find self
end
def exec *args
node.exec 'pct', 'exec', vmid, '--', *args
end
def enter
node.enter 'pct', 'enter', vmid
end
end
class HA < Base
def initialize
@rest_prefix = "/cluster/ha/resources/#{virt.sid}"
end
class <<self
def find host
ha = HA.send :__new__, digest: nil, state: nil, virt: host
ha.refresh!
end
def create host, **options
find( host).create **options
end
end
def refresh!
virt = @virt
__update__( {state: nil}.merge( rest_get( "/cluster/ha/resources/#{virt.sid}")).merge( virt: virt))
self
rescue RestClient::InternalServerError
__update__ digest: nil, state: nil, virt: virt
end
def create group: nil, comment: nil, max_relocate: nil, max_restart: nil, state: nil
options = {
sid: virt.sid,
group: group,
comment: comment,
max_relocate: max_relocate,
max_restart: max_restart,
state: state
}
options.delete_if {|k,v| v.nil? }
rest_post "/cluster/ha/resources", **options
refresh!
end
def delete
rest_del "#{@rest_prefix}"
end
def state= state
rest_put "#{@rest_prefix}", state: state.to_s
refresh!
end
def started!
self.state = :started
self
end
def stopped!
self.state = :stopped
self
end
def disabled!
self.state = :disabled
self
end
def started?
'started' == self.state
end
def stopped?
'stopped' == self.state
end
def error?
'error' == self.state
end
def active?
! ! digest
end
end
end
require_relative 'templates'

32
lib/pve/qm.rb Normal file
View file

@ -0,0 +1,32 @@
class PVE::Cli
def cli_qm
cli.sub :qm, "Virtual Machines", aliases: %w[v vm qemu], &lambda {|qm|
qm.cmd :list, "List VM-IDs", aliases: ['ls'], &lambda {|node=nil|
connect
nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node
nodes.flat_map do |n|
n.qemu.map {|c| c.vmid.to_i }
end.sort.each {|c| puts c }
}
qm.cmd :status, "List VMs with status", aliases: [nil], &lambda {|node=nil|
connect
to = TablizedOutput.new %w[Status HA ID Name Host Uptime CPU Mem/MiB Disk/MiB]
nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node
nodes.each do |n|
n.qemu.each &to.method( :virt)
end
to.print order: [3]
}
qm.cmd :exec, "Executes Command in VM via qemu-guest-agent", min: 4, &lambda {|name_or_id, *command|
connect
STDERR.puts "! #{$?.exitstatus}" unless Proxmox::Qemu.find!( name_or_id).exec *command
}
qm.cmd 'help', '', aliases: ['-h', '--help'], &lambda {|*args| help qm, *args }
}
end
end

154
lib/pve/templates.rb Normal file
View file

@ -0,0 +1,154 @@
require 'ostruct'
module PVE::CTTemplate
class Base
attr_reader :options
def initialize **opts
@options = OpenStruct.new opts
@virts = Proxmox::LXC.all + Proxmox::Qemu.all
end
def name() options.name end
def node() options.node end
def arch() options.arch || 'amd64' end
def vmid() options.vmid end
def ostype() options.ostype end
def cmode() options.cmode || 'shell' end
def cores() options.cores || 1 end
def description() options.description || '' end
def hostname() options.hostname || name end
def memory() options.memory || 1024 end
def swap() options.swap || 0 end
def unprivileged() options.unprivileged() || 1 end
def ssh_public_keys
options[:'ssh-public-keys'] ||
File.read( options[:'ssh-public-keys-file'] || '/root/.ssh/authorized_keys')
end
def net0()
if options.ipv4 || options.ipv6
ipv4 = IPAddress::IPv4.new options.ipv4
{
name: 'eth0',
bridge: 'vmbr1',
ip: ipv4.to_string,
gw: options.gateway || ipv4.hosts.last.to_s
}
end
end
def net1() nil end
def net2() nil end
def net3() nil end
end
class Default < Base
def self.requirements
{
node: [:string, false, "Create CT on this node."],
name: [:string, true, "Set (uniq) name"],
arch: [:enum, false, "Architecture", %w[amd64 i386 arm64 armhf]],
vmid: [:numeric, true, "VM-ID. Proxmox internal number (100...)"],
ostype: [:string, true, "OS-Type (OS or distribution)"],
cmode: [:enum, false, "Console-mode", %w[shell console tty]],
cores: [:numeric, false, "Count of cores"],
description: [:string, false, "Description. Eg. What should this CT do?"],
hostname: [:string, false, "Hostname"],
memory: [:numeric, false, "How much memory CT could use?"],
swap: [:numeric, false, "How much CT can swap?"],
unprivileged: [:boolean, false, "Unprivileged are restricted to own UID/GID-space."],
:'ssh-public-keys' => [:string, false, "SSH-Public-Keys, which should be added to root-user in CT."],
:'ssh-public-keys-file' => [:string, false, "Read SSH-Public-Keys from file."],
ipv4: [:string, false, "IPv4-Address with net-size."],
gateway4: [:string, false, "IPv4-Address of gateway."],
ipv6: [:string, false, "IPv6-Address with net-size."],
gateway6: [:string, false, "IPv6-Address of gateway."],
storage: [:string, false, "Device will be create on this Storage (default: local"],
}
end
end
class Datacenter < Base
def self.requirements
{
node: [:string, false, "Create CT on this node."],
name: [:string, true, "Set (uniq) name"],
arch: [:enum, false, "Architecture", %w[amd64 i386 arm64 armhf]],
vmid: [:numeric, true, "VM-ID. Proxmox internal number (100...)"],
ostype: [:string, true, "OS-Type (OS or distribution)"],
cmode: [:enum, false, "Console-mode", %w[shell console tty]],
cores: [:numeric, false, "Count of cores"],
description: [:string, false, "Description. Eg. What should this CT do?"],
hostname: [:string, false, "Hostname"],
memory: [:numeric, false, "How much memory CT could use?"],
swap: [:numeric, false, "How much CT can swap?"],
unprivileged: [:boolean, false, "Unprivileged are restricted to own UID/GID-space."],
:'ssh-public-keys' => [:string, false, "SSH-Public-Keys, which should be added to root-user in CT."],
:'ssh-public-keys-file' => [:string, false, "Read SSH-Public-Keys from file."],
:'network-id' => [:numeric, true, "Put Container to this VLAN and use a random IPv4-Address for this CT."],
ipv4: [:string, false, "IPv4-Address with net-size."],
gateway4: [:string, false, "IPv4-Address of gateway."],
ipv6: [:string, false, "IPv6-Address with net-size."],
gateway6: [:string, false, "IPv6-Address of gateway."],
storage: [:string, false, "Device will be create on this Storage (default: root)"],
}
end
def node() options.node || 'svc1' end
def ostype() options.ostype || 'debian' end
def memory() options.memory || 2048 end
def storage() options.storage || 'root' end
def network_id
return @network_id if @network_id
expect = 0..12
nid = options[:'network-id']
unless nid == nid.to_i.to_s && expect.include?( nid.to_i)
raise ArgumentError, "Network ID must be #{expect.inspect}. Given: #{nid.inspect}"
end
@network_id = nid.to_i
end
def net0
{
name: 'eth0',
bridge: 'vmbr1',
tag: 2000+network_id,
mtu: 9166,
firewall: 1,
ip: ipv4.to_string,
gw: ipv4.hosts.last.to_s,
}
end
def vmid
super || ((0...100).map {|i| "#{100*network_id+i}" } - @virts.map( &:vmid)).first
end
def network
IPAddress::IPv4.new "10.#{network_id}.255.0/24"
end
def ipv4
return options.ipv4 if options.ipv4
return @ipv4 if @ipv4
ipv4s = network.hosts
@virts.each do |v|
v.config[:network].each {|n| ipv4s.delete n[:ip] if n[:ip] }
end
@ipv4 = ipv4s.first
end
def ostemplate
@ostemplate ||=
options.ostemplate ||
case ostype
when 'debian'
'local:vztmpl/debian-10-standard_10.5-1_amd64.tar.gz'
else
raise ArgumentError, "OS-Template for ostype #{ostype} not found or ostemplate not provided."
end
end
end
end

3
lib/pve/version.rb Normal file
View file

@ -0,0 +1,3 @@
module PVE
VERSION = '0.1.1'
end

32
pve.gemspec Normal file
View file

@ -0,0 +1,32 @@
require_relative 'lib/pve/version'
Gem::Specification.new do |spec|
spec.name = "pve"
spec.version = PVE::VERSION
spec.authors = ["Denis Knauf"]
spec.email = ["git+pve@denkn.at"]
spec.licenses = ["LGPL-3.0"]
spec.summary = %q{Proxmox Virtual Environment higher level API }
spec.description = %q{Provides a higher level API with objects for controlling PVE}
spec.homepage = "https://git.denkn.at/deac/pve"
# Ruby3 interpret **opts in another way than before.
# 2.7.0 should work with both(?) behaviours.
# PVE based on debian, so ruby 2.5 is default.
spec.required_ruby_version = Gem::Requirement.new "~> 2.5.0"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = spec.homepage
spec.metadata["changelog_uri"] = spec.homepage
spec.add_development_dependency "rspec", "~> 3.2"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "bin"
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
end