v0.3.0: >=ruby2.7. PVE-6 not supported anymore. small fixes. more comfort. commands on more than one machine at once.

This commit is contained in:
Denis Knauf 2022-10-05 12:55:03 +02:00
parent 93889f9dab
commit d558af77b6
10 changed files with 302 additions and 93 deletions

View file

@ -39,8 +39,9 @@ class PVE::Cli
def initialize config_file = nil def initialize config_file = nil
config_file ||= '/etc/pve/pvecli.yml' config_file ||= '/etc/pve/pvecli.yml'
@cfg = @cfg =
YAML.safe_load File.read( config_file), [], [], false, YAML.safe_load File.read( config_file), permitted_classes: [],
config_file, symbolize_names: true permitted_symbols: [], aliases: false, filename: config_file,
symbolize_names: true
@cli = DenCli.new File.basename($0), "PVE CLI" @cli = DenCli.new File.basename($0), "PVE CLI"
@interactive = false @interactive = false
prepare prepare
@ -56,15 +57,14 @@ class PVE::Cli
end end
def wait_state host, state, timeout: nil, lock: nil def wait_state host, state, timeout: nil, lock: nil
spinners = %w[- / | \\] spinners, spin = "▖▘▝▗", 0
spin = 0
r = r =
host.wait state, lock: lock, timeout: timeout, secs: 0.2 do |state, lock| host.wait state, lock: lock, timeout: timeout, secs: 0.2 do |state, lock|
lock = " (locked: #{lock})" if 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 STDERR.printf "\r[%s] \e[33;1m%s\e[0m Still %s%s...\e[J", host.name, spinners[spin = (spin + 1) % 4], state, lock
end end
STDERR.printf "\r\e[J" STDERR.printf "\r\e[J"
exit 1 unless interactive? and r exit 1 if interactive? and !r
end end
def task_log task, logn, limit = 1024 def task_log task, logn, limit = 1024
@ -78,7 +78,7 @@ class PVE::Cli
logn logn
end end
def wait task, secs: nil, text: nil def wait task, secs: nil, text: nil, timeout: nil
secs ||= 0.1 secs ||= 0.1
spinners, spin, logn = "▖▘▝▗", 0, 0 spinners, spin, logn = "▖▘▝▗", 0, 0
STDERR.puts task.upid STDERR.puts task.upid
@ -107,18 +107,24 @@ class PVE::Cli
end end
end end
def start host, node: nil, timeout: nil, fire: nil, secs: nil def migrate host, node, timeout: nil, fire: nil, secs: nil, online: nil
timeout ||= 30 timeout ||= 30
if node task = host.migrate Proxmox::Node.find_by_name!( node), online: online || false
task = host.migrate Proxmox::Node.find_by_name!( node) wait task, text: "Migrating", timeout: timeout if fire
wait task, text: "Migrating"
end end
def start host, node: nil, timeout: nil, fire: nil, secs: nil
timeout ||= 60
if host.running? if host.running?
STDERR.puts "Already running." STDERR.puts "Already running."
return return
end end
task = host.start task = host.start
wait task, text: "Starting" unless fire t = Time.now
unless fire
wait task, text: "Starting", timeout: timeout
wait_state host, :running, timeout: timeout-(Time.now-t) if host.ha.exist? and not host.running?
end
end end
def stop host, timeout: nil, fire: nil, secs: nil def stop host, timeout: nil, fire: nil, secs: nil
@ -128,12 +134,14 @@ class PVE::Cli
return return
end end
task = host.stop task = host.stop
t = Time.now
unless fire unless fire
wait task, text: "Stopping" wait task, text: "Stopping", timeout: timeout
wait_state host, :stopped, timeout: timeout-(Time.now-t) if host.ha.exist? and not host.stopped?
end end
end end
def create klass, template, timeout: nil, fire: nil, secs: nil, start: nil, **options def create klass, template, timeout: nil, fire: nil, start: nil, **options
options[:start] = fire && start options[:start] = fire && start
task = klass.create template, **options task = klass.create template, **options
return if fire return if fire
@ -154,8 +162,7 @@ class PVE::Cli
end end
def node_opt node = nil def node_opt node = nil
node &&= /\A#{node}\z/ node ? [Proxmox::Node.find_by_name!( node)] : Proxmox::Node.all
node ? Proxmox::Node.find_by_name( name) : Proxmox::Node.all
end end
def target_opt target = nil, &exe def target_opt target = nil, &exe
@ -250,12 +257,29 @@ class PVE::Cli
def call *argv def call *argv
cli.call *argv cli.call *argv
rescue RestClient::ExceptionWithResponse rescue RestClient::ExceptionWithResponse
STDERR.puts "#$! - #{$!.response} (#{$!.class})" #, $!.backtrace.map {|b|" #{b}"} STDERR.puts "#{$!.request}: #{$!.to_s} - #{$!.response} (#{$!.class})" #, $!.backtrace.map {|b|" #{b}"}
rescue UsageError, DenCli::UsageError rescue UsageError, DenCli::UsageError
STDERR.puts $! STDERR.puts $!
exit 1 exit 1
end end
def per_argument arguments, print: nil, &exe
arguments.each do |argument|
STDERR.printf print, argument if print
begin
yield argument
rescue RestClient::ExceptionWithResponse
STDERR.puts "#{$!.request}: #{$!.to_s} - #{JSON.parse( $!.response.body)}"
rescue UsageError, DenCli::UsageError
STDERR.puts $!
rescue RestClient::BadRequest
STDERR.puts $!.message.inspect
rescue SystemExit
STDERR.puts "Failed with exit code: #{$!.status}" if 0 < $!.status
end
end
end
def appliances node, regexp, system, applications def appliances node, regexp, system, applications
system = applications = true if system.nil? and applications.nil? system = applications = true if system.nil? and applications.nil?
node = node ? Proxmox::Node.find_by_name!( node) : Proxmox::Node.all.first node = node ? Proxmox::Node.find_by_name!( node) : Proxmox::Node.all.first
@ -277,6 +301,7 @@ class PVE::Cli
COLORS = %w[black red green yellow blue magenta cyan white].each_with_index.to_h COLORS = %w[black red green yellow blue magenta cyan white].each_with_index.to_h
def fgcolor color def fgcolor color
color = color.to_s
if /\Abright[-_]?(.*)\z/ =~ color if /\Abright[-_]?(.*)\z/ =~ color
c = COLORS[$1] c = COLORS[$1]
c.nil? ? nil : "1;3#{c}" c.nil? ? nil : "1;3#{c}"

View file

@ -27,6 +27,14 @@ def cli_base
opt( :node, '-n', '--node=NODE', "List only hosted by this NODE"). opt( :node, '-n', '--node=NODE', "List only hosted by this NODE").
opt( :status, '-S', '--status=STATUS', "Filter for status (running, stopped, ...) (default: no filter)") opt( :status, '-S', '--status=STATUS', "Filter for status (running, stopped, ...) (default: no filter)")
def val2str v
case v
when true then 1
when false then 0
else v
end
end
def prepare_show_config cnf def prepare_show_config cnf
r = {} r = {}
cnf.each do |k,v| cnf.each do |k,v|
@ -37,18 +45,15 @@ def cli_base
net. net.
reject {|k, v| :card == k }. reject {|k, v| :card == k }.
sort_by {|k, v| :name == k ? :AAAAAAAAA : 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}=#{val2str v}" }
map {|k, v| "#{k}=#{v}" } r[net[:card].to_sym] = s.join ','
r[net[:card].to_sym] = s.join(",")
end end
when :sshkeys when :sshkeys
r[k] = CGI.unescape(v).gsub( /^/, " "*14).gsub /\A {14}|\n\z/, '' r[k] = CGI.unescape( v).gsub( /^/, " "*14).gsub /\A {14}|\n\z/, ''
when :features
r[k] = v.map {|k, v| "#{k}=#{val2str v}" }.join ','
else else
case v r[k] = val2str( v).to_s.gsub( /$^/, " "*14).gsub /\n\z/, ''
when true then v = 1
when false then v = 0
end
r[k] = v.to_s.gsub( /$^/, " "*14).gsub /\n\z/, ''
end end
end end
r r
@ -56,20 +61,21 @@ def cli_base
def show_config cnf, old = nil def show_config cnf, old = nil
cnf = prepare_show_config cnf cnf = prepare_show_config cnf
l = cnf.keys.map( &:length).max
if old if old
old = prepare_show_config old old = prepare_show_config old
(cnf.keys+old.keys).uniq.sort.each do |k| (cnf.keys+old.keys).uniq.sort.each do |k|
v, o = cnf[k], old[k] v, o = cnf[k], old[k]
if v == o if v == o
puts "#{k}:#{' ' * (12-k.length)} #{v}" puts "#{k}:#{' ' * (l-k.length)} #{v}"
else else
puts "\e[31m#{k}:#{' ' * (12-k.length)} #{o}\e[0m" unless o.nil? puts "\e[31m#{k}:#{' ' * (l-k.length)} #{o}\e[0m" unless o.nil?
puts "\e[32m#{k}:#{' ' * (12-k.length)} #{v}\e[0m" unless v.nil? puts "\e[32m#{k}:#{' ' * (l-k.length)} #{v}\e[0m" unless v.nil?
end end
end end
else else
cnf.sort_by{|k,v|k}.each do |k,v| cnf.sort_by {|k,_| k }.each do |k,v|
puts "#{k}:#{' ' * (12-k.length)} #{v}" puts "#{k}:#{' ' * (l-k.length)} #{v}"
end end
end end
end end
@ -86,17 +92,26 @@ def cli_base
opts = {} opts = {}
until args.empty? until args.empty?
case arg = args.shift case arg = args.shift
when /\A--no-(\w+)\z/
opts[$1.to_sym] = false
when /\A--(\w+)=(.*)\z/ when /\A--(\w+)=(.*)\z/
opts[$1.to_sym] = $2 opts[$1.to_sym] = $2
when /\A--(\w+)!\z/, /\A--del-(\w+)\z/
opts[$1.to_sym] = nil
when /\A--(\w+)\z/ when /\A--(\w+)\z/
opts[$1.to_sym] = args.shift n = $1.to_sym
opts[n] =
if args.empty? or /\A--/ == args.first
true
else opts[n] = args.shift
end
else else
raise UsageError, "Expection option to set. What do you mean with: #{arg}" raise UsageError, "Expection option to set. What do you mean with: #{arg}"
end end
end end
opts.each do |k, v| opts.each do |k, v|
opts[k] = opts[k] =
case v = opts[k] case v
when '' then nil when '' then nil
else v else v
end end
@ -121,14 +136,15 @@ def cli_base
next unless opts.has_key? k next unless opts.has_key? k
opts[k] = opts[k] =
case v = opts[k] case v = opts[k]
when *%w[1 T TRUE t true True Y YES y yes Yes] then true when true, *%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 false, *%w[0 F FALSE f false False N NO n no No] then false
when '', 'nil', nil then nil when '', 'nil', nil then nil
else raise UsageError, "Boolean expected, given: #{v.inspect}" else raise UsageError, "Boolean expected, given: #{v.inspect}"
end end
end end
connect connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id) 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
old = th.config old = th.config
opts[:digest] ||= old[:digest] opts[:digest] ||= old[:digest]
th.cnfset opts th.cnfset opts
@ -138,6 +154,7 @@ def cli_base
ccli.cmd :show, "Show Config of CT/VM", &lambda {|name_or_id| ccli.cmd :show, "Show Config of CT/VM", &lambda {|name_or_id|
connect connect
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id) 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
show_config th.config show_config th.config
} }
end end
@ -154,11 +171,14 @@ def cli_base
end end
end end
cli.cmd( :run, "Starts CT/VM", aliases: %w[start star], &lambda {|name_or_id| cli.cmd( :run, "Starts CT/VM", aliases: %w[start star], &lambda {|*names_or_ids|
connect connect
raise UsageError, "Nothing to start?" if names_or_ids.empty?
per_argument names_or_ids, print: "\e[34;1mRunning CT/VM\e[0m %s:\n" do |name_or_id|
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id) 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 raise UsageError, "Container or Node not found: #{name_or_id}" unless th
start th start th
end
}). }).
completion do |*pre, arg| completion do |*pre, arg|
completion_helper *pre, arg do |f| completion_helper *pre, arg do |f|
@ -166,6 +186,21 @@ def cli_base
end end
end end
cli.cmd( :migrate, "Migrates (halted) CTs/VMs to an other host", min: 2, &lambda {|target, *names_or_ids, fire:, timeout:, secs:|
connect
node = Proxmox::Node.find_by_name! target
per_argument names_or_ids, print: "\e[1;34mCT/VM(s)\e[0m %s:\n" do |name_or_id|
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
raise UsageError, "CT/VM not found: #{name_or_id}" unless th
unless th.stopped?
raise UsageError, "VM #{name_or_id} is running. Shutdown or for VM-online-migration see `help qm migrate`" if Proxmox::Qemu === th
raise UsageError, "CT #{name_or_id} is running. You have to shutdown it."
end
task = th.migrate node
wait task, text: "Migrating", timeout: timeout unless fire
end
}).tap {|c| opts_wait c }
#cli.cmd :reboot, "Reboot CT/VM (not implemented, yet)", min: 6, &lambda {|name_or_id| #cli.cmd :reboot, "Reboot CT/VM (not implemented, yet)", min: 6, &lambda {|name_or_id|
# connect # connect
# th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id) # th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id)
@ -173,11 +208,13 @@ def cli_base
# reboot th # reboot th
#} #}
cli.cmd( :stop, "Stops CT/VM", min: 4, &lambda {|name_or_id| cli.cmd( :stop, "Stops CT/VM", min: 4, &lambda {|*names_or_ids|
connect connect
per_argument names_or_ids, print: "\e[34;1mStopping CT/VM\e[0m %s:\n" do |name_or_id|
th = Proxmox::LXC.find( name_or_id) || Proxmox::Qemu.find_by_name( name_or_id) 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 raise UsageError, "Container or Node not found: #{name_or_id}" unless th
stop th stop th
end
}). }).
completion do |*pre, arg| completion do |*pre, arg|
completion_helper *pre, arg do |f| completion_helper *pre, arg do |f|

View file

@ -31,18 +31,30 @@ def cli_ct
STDERR.puts "! #{$?.exitstatus}" unless Proxmox::LXC.find!( name_or_id).exec *command STDERR.puts "! #{$?.exitstatus}" unless Proxmox::LXC.find!( name_or_id).exec *command
} }
ct_cli.cmd( :start, "Starts CT", min: 4, &lambda {|name_or_id, node: nil, fire:, timeout:, secs:| ct_cli.cmd( :migrate, "Migrates halted CT(s) to an other host", min: 2, &lambda {|target, *names_or_ids, fire:, timeout:, secs:|
connect connect
node = Proxmox::Node.find_by_name! target
per_argument names_or_ids, print: "\e[1;34mMigrate CT %s:\e[0m" do |name_or_id|
ct = Proxmox::LXC.find! name_or_id
task = ct.migrate node
wait task, text: "Migrating", timeout: timeout unless fire
end
}).tap {|c| opts_wait c }
ct_cli.cmd( :start, "Starts CT(s)", min: 4, &lambda {|*names_or_ids, node: nil, fire:, timeout:, secs:|
connect
per_argument names_or_ids, print: "\e[1;34mStart CT %s:\e[0m" do |name_or_id|
ct = Proxmox::LXC.find! name_or_id ct = Proxmox::LXC.find! name_or_id
start ct, node: node, fire: fire, timeout: timeout, secs: secs start ct, node: node, fire: fire, timeout: timeout, secs: secs
}). end
opt( :node, "-nNODE", "--node=NODE", "On NODE (default, as is, so without migration)"). }).tap {|c| opts_wait c }
tap {|c| opts_wait c }
ct_cli.cmd( :stop, "Stops CT", min: 3, &lambda {|name_or_id, fire: nil, timeout:, secs:| ct_cli.cmd( :stop, "Stops CT(s)", min: 3, &lambda {|*names_or_ids, fire: nil, timeout:, secs:|
connect connect
per_argument names_or_ids, print: "\e[1;34mStart CT %s:\e[0m" do |name_or_id|
ct = Proxmox::LXC.find! name_or_id ct = Proxmox::LXC.find! name_or_id
stop ct, fire: fire, timeout: timeout, secs: secs stop ct, fire: fire, timeout: timeout, secs: secs
end
}).tap {|c| opts_wait c } }).tap {|c| opts_wait c }
ct_cli.cmd( :wait, "Wait till CT is in state", &lambda {|name_or_id, state, timeout: nil, secs: nil| ct_cli.cmd( :wait, "Wait till CT is in state", &lambda {|name_or_id, state, timeout: nil, secs: nil|

View file

@ -1,7 +1,7 @@
class PVE::Cli class PVE::Cli
def cli_qm def cli_qm
cli.sub :qm, "Virtual Machines", aliases: %w[v vm qemu], &lambda {|qm| cli.sub :qm, "Virtual Machines", aliases: %w[v vm qemu], &lambda {|qm_cli|
qm.cmd :list, "List VM-IDs", aliases: ['ls'], &lambda {|node=nil| qm_cli.cmd :list, "List VM-IDs", aliases: ['ls'], &lambda {|node=nil|
connect connect
nodes = Proxmox::Node.all nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node nodes = nodes.select {|n| node == n.name } if node
@ -10,11 +10,52 @@ def cli_qm
end.sort.each {|c| puts c } end.sort.each {|c| puts c }
} }
qm.cmd( :status, "Lists CTs with status", aliases: [nil], &lambda {|target=nil, sort: nil, node: nil, status: nil| qm_cli.cmd( :migrate, "Migrates VM(s) to an other host", min: 2, &lambda {|target, *names_or_ids, fire:, timeout:, secs:|#, online:, restart:|
#if online and restart
# raise UsageError, "You have to decide for one migration-mode: --restart or --online."
#end
#online = !restart or online
connect
node = Proxmox::Node.find_by_name! target
per_argument names_or_ids, print: "\e[1;34mVM\e[0m %s:\n" do |name_or_id|
qm = Proxmox::Qemu.find! name_or_id
task = qm.migrate node #, online: online
wait task, text: "Migrating", timeout: timeout unless fire
end
}).
#opt( :online, '-o', '--online', "Online-migration: Does not shutdown or interrupt running VM. Opposite of --online, Default", default: nil).
#opt( :restart, '-r', '--restart', "Restart-migration: Does shutdown or interrupt running VM. Opposite of --restart", default: nil).
tap {|c| opts_wait c }
qm_cli.cmd( :start, "Starts VM(s)", min: 4, &lambda {|*names_or_ids, node: nil, fire:, timeout:, secs:|
connect
per_argument names_or_ids, print: "\e[1;34mStart VM %s:\e[0m" do |name_or_id|
qm = Proxmox::Qemu.find! name_or_id
start qm, node: node, fire: fire, timeout: timeout, secs: secs
end
}).tap {|c| opts_wait c }
qm_cli.cmd( :stop, "Stops VM(s)", min: 3, &lambda {|*names_or_ids, fire: nil, timeout:, secs:|
connect
per_argument names_or_ids, print: "\e[1;34mStart VM %s:\e[0m" do |name_or_id|
qm = Proxmox::Qemu.find! name_or_id
stop qm, fire: fire, timeout: timeout, secs: secs
end
}).tap {|c| opts_wait c }
qm_cli.cmd( :wait, "Wait till VM is in state", &lambda {|name_or_id, state, timeout: nil, secs: nil|
connect
qm = Proxmox::Qemu.find! name_or_id
wait qm, 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)
qm_cli.cmd( :status, "Lists VMs with status", aliases: [nil], &lambda {|target=nil, sort: nil, node: nil, status: nil|
hosting_table target: target, state: state, sort: sort do |push| hosting_table target: target, state: state, sort: sort do |push|
node_opt( node). node_opt( node).
each( &push).lazy. each( &push).lazy.
flat_map {|n| [ Thread.new( n, &:lxc), Thread.new( n, &:qemu) ] }. flat_map {|n| [ Thread.new( n, &:qemu) ] }.
each {|n| n.value.each &push } each {|n| n.value.each &push }
end end
}). }).
@ -22,19 +63,19 @@ def cli_qm
opt( :node, '-n', '--node=NODE', "List only hosted by this NODE"). opt( :node, '-n', '--node=NODE', "List only hosted by this NODE").
opt( :status, '-S', '--status=STATUS', "Filter for status (running, stopped, ...) (default: no filter)") opt( :status, '-S', '--status=STATUS', "Filter for status (running, stopped, ...) (default: no filter)")
qm.cmd :exec, "Executes Command in VM via qemu-guest-agent", min: 4, &lambda {|name_or_id, *command| qm_cli.cmd :exec, "Executes Command in VM via qemu-guest-agent", min: 4, &lambda {|name_or_id, *command|
connect connect
STDERR.puts "! #{$?.exitstatus}" unless Proxmox::Qemu.find!( name_or_id).exec *command STDERR.puts "! #{$?.exitstatus}" unless Proxmox::Qemu.find!( name_or_id).exec *command
} }
qm.cmd( :resize, 'Resize a disk', &lambda {|name_or_id, disk, size| qm_cli.cmd( :resize, 'Resize a disk', &lambda {|name_or_id, disk, size|
connect connect
qm = Proxmox::Qemu.find! name_or_id qm = Proxmox::Qemu.find! name_or_id
task = qm.resize disk, size task = qm.resize disk, size
wait task, text: "Resizing #{qm.sid} #{disk} to #{size}" wait task, text: "Resizing #{qm.sid} #{disk} to #{size}"
}) })
qm.cmd 'help', '', aliases: ['-h', '--help'], &lambda {|*args| help qm, *args } qm_cli.cmd 'help', '', aliases: ['-h', '--help'], &lambda {|*args| help qm_cli, *args }
} }
end end
end end

View file

@ -40,7 +40,7 @@ def cli_storage
storage = node.storage.select {|sm| storage == sm.storage }.first storage = node.storage.select {|sm| storage == sm.storage }.first
storage.content.each {|c| puts c.to_s } storage.content.each {|c| puts c.to_s }
} }
cli_cnt.cmd( :help, '', aliases: ['-h', '--help']) {|*args| help cli_cnt, *args } cli_cnt.cmd( :help, '', aliases: ['-h', '--help', nil]) {|*args| help cli_cnt, *args }
end end
cli_sm.cmd( :help, '', aliases: ['-h', '--help']) {|*args| help cli_sm, *args } cli_sm.cmd( :help, '', aliases: ['-h', '--help']) {|*args| help cli_sm, *args }

View file

@ -21,6 +21,22 @@ def cli_task
end end
end end
} }
tcli.cmd :status, "Shows tasks states", &lambda {|upid|
}
tcli.cmd :monitor, "Monitors running tasks", &lambda {|node: nil|
connect
nodes = Proxmox::Node.all
nodes = nodes.select {|n| node == n.name } if node
tasks = {}
loop do
nodes.flat_map do |n|
n.tasks.map &:upid
end.sort.each do |upid|
end
end
}
end end
end end
end end

View file

@ -5,6 +5,13 @@ require 'ipaddress'
require 'shellwords' require 'shellwords'
require 'active_support/all' require 'active_support/all'
class RestClient::Exception
attr_reader :request
def to_s
"#{request|"?"}: #{message}: #{response}"
end
end
module Proxmox module Proxmox
class Exception < ::Exception class Exception < ::Exception
end end
@ -13,6 +20,30 @@ module Proxmox
class AlreadyExists < Exception class AlreadyExists < Exception
end end
def self.cnfstr2hash str
str.
split( ',').
map do |o|
k, v = o.split( '=', 2)
[k.to_sym, v]
end.
to_h
end
def self.hash2cnfstr **opts
opts.
map do |k, v|
v =
case v
when true then 1
when false then 0
else v.to_s
end
"#{k}=#{v}"
end.
join( ',')
end
def self.connect username, password, realm: nil, verify_tls: nil, uri: nil def self.connect username, password, realm: nil, verify_tls: nil, uri: nil
uri ||= 'https://localhost:8006/api2/json' uri ||= 'https://localhost:8006/api2/json'
cred = cred =
@ -95,19 +126,37 @@ module Proxmox
def rest_get path, **data, &exe def rest_get path, **data, &exe
data = data.delete_if {|k,v|v.nil?} 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? path += "#{path.include?( ??) ? ?& : ??}#{data.map{|k,v|"#{CGI.escape k.to_s}=#{CGI.escape v.to_s}"}.join '&'}" unless data.empty?
STDERR.puts "GET #{path} <= #{data}" if $DEBUG
__response__ Proxmox.connection[path].get( __headers__( :'Content-Type' => 'application/json')) __response__ Proxmox.connection[path].get( __headers__( :'Content-Type' => 'application/json'))
rescue RestClient::Exception
$!.instance_variable_set :@request, "GET #{path}"
raise
end end
def rest_put path, **data, &exe def rest_put path, **data, &exe
__response__ Proxmox.connection[path].put( __data__( data), __headers__( :'Content-Type' => 'application/json')) data = __data__( data)
STDERR.puts "PUT #{path} <= #{data}" if $DEBUG
__response__ Proxmox.connection[path].put( data, __headers__( :'Content-Type' => 'application/json'))
rescue RestClient::Exception
$!.instance_variable_set :@request, "PUT #{path}"
raise
end end
def rest_del path, &exe def rest_del path, &exe
STDERR.puts "DELETE #{path}" if $DEBUG
__response__ Proxmox.connection[path].delete( __headers__( :'Content-Type' => 'application/json')) __response__ Proxmox.connection[path].delete( __headers__( :'Content-Type' => 'application/json'))
rescue RestClient::Exception
$!.instance_variable_set :@request, "DELETE #{path}"
raise
end end
def rest_post path, **data, &exe def rest_post path, **data, &exe
__response__ Proxmox.connection[path].post( __data__( data), __headers__( :'Content-Type' => 'application/json')) data = __data__( data)
STDERR.puts "POST #{path} <= #{data}" if $DEBUG
__response__ Proxmox.connection[path].post( data, __headers__( :'Content-Type' => 'application/json'))
rescue RestClient::Exception
$!.instance_variable_set :@request, "POST #{path}"
raise
end end
end end
@ -295,15 +344,6 @@ module Proxmox
@name =~ t or @vmid.to_s =~ t or @sid =~ t @name =~ t or @vmid.to_s =~ t or @sid =~ t
end 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 def start
Task.send :__new__, node: @node, host: self, upid: rest_post( "#{@rest_prefix}/status/start") Task.send :__new__, node: @node, host: self, upid: rest_post( "#{@rest_prefix}/status/start")
end end
@ -350,13 +390,8 @@ module Proxmox
map( &:to_s). map( &:to_s).
grep( /\Anet\d+\z/). grep( /\Anet\d+\z/).
map do |k| map do |k|
nc = {card: k} nc = Proxmox::cnfstr2hash cnf.delete( k.to_sym)
cnf.delete( k.to_sym). nc[:card] = k
split( ',').
each do |f|
k, v = f.split( '=', 2)
nc[k.to_sym] = v
end
nc[:ip] &&= IPAddress::IPv4.new nc[:ip] nc[:ip] &&= IPAddress::IPv4.new nc[:ip]
nc[:gw] &&= IPAddress::IPv4.new nc[:gw] nc[:gw] &&= IPAddress::IPv4.new nc[:gw]
nc[:mtu] &&= nc[:mtu].to_i nc[:mtu] &&= nc[:mtu].to_i
@ -364,9 +399,13 @@ module Proxmox
nc[:firewall] &&= 1 == nc[:firewall].to_i nc[:firewall] &&= 1 == nc[:firewall].to_i
nc nc
end end
cnf[:features] &&=
Proxmox::cnfstr2hash( cnf[:features]).
tap {|f| f[:nesting] &&= '1' == f[:nesting] }
cnf[:unprivileged] &&= 1 == cnf[:unprivileged] cnf[:unprivileged] &&= 1 == cnf[:unprivileged]
cnf[:memory] &&= cnf[:memory].to_i cnf[:memory] &&= cnf[:memory].to_i
cnf[:cores] &&= cnf[:cores].to_i cnf[:cores] &&= cnf[:cores].to_i
cnf.update cnf.delete( :lxc).map{|k,v|[k.to_sym,v]}.to_h if cnf[:lxc]
cnf cnf
end end
@ -381,6 +420,7 @@ module Proxmox
end end
end end
r.delete :delete if r[:delete].empty? r.delete :delete if r[:delete].empty?
STDERR.puts r.inspect
rest_put "#{@rest_prefix}/config", r rest_put "#{@rest_prefix}/config", r
end end
@ -461,6 +501,15 @@ module Proxmox
upid = rest_put "#{@rest_prefix}/resize", disk: disk, size: size upid = rest_put "#{@rest_prefix}/resize", disk: disk, size: size
Task.send :__new__, node: @node, host: self, upid: upid Task.send :__new__, node: @node, host: self, upid: upid
end end
def migrate target, online: nil
target =
case target
when Node then target
else Node.find!( target.to_s)
end
Task.send :__new__, node: @node, host: self, upid: rest_post( "#{@rest_prefix}/migrate", target: target.node, online: ! !online)
end
end end
class LXC < Hosted class LXC < Hosted
@ -551,6 +600,7 @@ module Proxmox
#}.map {|k,v| "#{k}=#{v}" }.join( ','), #}.map {|k,v| "#{k}=#{v}" }.join( ','),
swap: tmplt.swap, swap: tmplt.swap,
unprivileged: tmplt.unprivileged, unprivileged: tmplt.unprivileged,
features: tmplt.features ? Proxmox::hash2cnfstr( tmplt.features) : nil,
}.delete_if {|k,v| v.nil? } }.delete_if {|k,v| v.nil? }
temp = LXC.send :__new__, node: node, vmid: options[:vmid], name: name, hostname: options[:hostname] temp = LXC.send :__new__, node: node, vmid: options[:vmid], name: name, hostname: options[:hostname]
@ -579,6 +629,15 @@ module Proxmox
def enter def enter
node.enter 'pct', 'enter', vmid node.enter 'pct', 'enter', vmid
end end
def migrate target
target =
case target
when Node then target
else Node.find!( target.to_s)
end
Task.send :__new__, node: @node, host: self, upid: rest_post( "#{@rest_prefix}/migrate", target: target.node)
end
end end
class HA < Base class HA < Base
@ -628,7 +687,8 @@ module Proxmox
end end
def state= state def state= state
rest_put "#{@rest_prefix}", state: state.to_s r = rest_put "#{@rest_prefix}", state: state.to_s
pp r: r
refresh! refresh!
end end
@ -651,6 +711,7 @@ module Proxmox
def stopped?() 'stopped' == self.state end def stopped?() 'stopped' == self.state end
def error?() 'error' == self.state end def error?() 'error' == self.state end
def active?() ! ! digest end def active?() ! ! digest end
def exist?() ! ! digest end
end end
class Storage < Base class Storage < Base

View file

@ -20,7 +20,18 @@ module PVE::CTTemplate
def hostname() options.hostname || name end def hostname() options.hostname || name end
def memory() options.memory || 1024 end def memory() options.memory || 1024 end
def swap() options.swap || 0 end def swap() options.swap || 0 end
def unprivileged() options.unprivileged() || 1 end def unprivileged() options.unprivileged || 1 end
def features
r =
if options.features
Proxmox::cnfstr2hash( options.features).
tap {|f| f[:nesting] &&= 1 == f[:nesting] }
else {}
end
r[:nesting] = options.nesting.nil? ? true : options.nesting
r
end
def ssh_public_keys def ssh_public_keys
options[:'ssh-public-keys'] || options[:'ssh-public-keys'] ||
@ -82,6 +93,8 @@ module PVE::CTTemplate
ipv6: [:string, false, "IPv6-Address with net-size or auto."], ipv6: [:string, false, "IPv6-Address with net-size or auto."],
gateway6: [:string, false, "IPv6-Address of gateway."], gateway6: [:string, false, "IPv6-Address of gateway."],
storage: [:string, false, "Device will be create on this Storage (default: local"], storage: [:string, false, "Device will be create on this Storage (default: local"],
features: [:string, false, "Features"],
nesting: [:boolean, false, "Support nested containers (->Features)"],
} }
end end
end end
@ -122,6 +135,8 @@ module PVE::CTTemplate
gateway6: [:string, false, "IPv6-Address of gateway."], gateway6: [:string, false, "IPv6-Address of gateway."],
storage: [:string, false, "Device will be create on this Storage (default: root)"], storage: [:string, false, "Device will be create on this Storage (default: root)"],
ostemplate: [:string, false, "OS-Template eg. local:vztmpl/superlinux-1.2-amd64.tar.xz"], ostemplate: [:string, false, "OS-Template eg. local:vztmpl/superlinux-1.2-amd64.tar.xz"],
features: [:string, false, "Features"],
nesting: [:boolean, false, "Support nested containers (->Features)"],
} }
end end

View file

@ -1,3 +1,3 @@
module PVE module PVE
VERSION = '0.2.4' VERSION = '0.3.0'
end end

View file

@ -12,8 +12,10 @@ Gem::Specification.new do |spec|
spec.homepage = "https://git.denkn.at/deac/pve" spec.homepage = "https://git.denkn.at/deac/pve"
# Ruby3 interpret **opts in another way than before. # Ruby3 interpret **opts in another way than before.
# 2.7.0 should work with both(?) behaviours. # 2.7.0 should work with both(?) behaviours.
# PVE based on debian, so ruby 2.5 is default. # PVE-7 based on debian-11, so ruby 2.7 is default.
spec.required_ruby_version = Gem::Requirement.new "~> 2.5.0" # No support for ruby 2.5 anymore (PVE-6 based on debian-10)
# Old behaviour will be droped.
spec.required_ruby_version = Gem::Requirement.new "~> 2.7"
spec.metadata["homepage_uri"] = spec.homepage spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = spec.homepage spec.metadata["source_code_uri"] = spec.homepage