commit
626e4b60b3
19 changed files with 1716 additions and 0 deletions
@ -0,0 +1,6 @@
|
||||
source 'https://rubygems.org' |
||||
gem 'dencli' |
||||
gem 'rest-client' |
||||
gem 'ipaddress' |
||||
gem 'activesupport' |
||||
gem 'pmap' |
@ -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 |
@ -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. |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
||||