pve/lib/pve/cli.rb

346 lines
9.7 KiB
Ruby

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'
require_relative 'cli/storage'
class UsageError <RuntimeError
end
class DenCli::Sub
def provide_help name: nil, aliases: nil, min: nil
base = self
name = :help if name.nil?
aliases = %w[-h --help] if aliases.nil?
min = 1 if min.nil?
#p name: name, aliases: aliases, min: min
cmd( name, '', aliases: aliases, min: min) {|*args| help *args }
end
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), permitted_classes: [],
permitted_symbols: [], aliases: false, filename: 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, 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] \e[33;1m%s\e[0m Still %s%s...\e[J", host.name, spinners[spin = (spin + 1) % 4], state, lock
end
STDERR.printf "\r\e[J"
exit 1 if interactive? and !r
end
def task_log task, logn, limit = 1024
log = task.log start: logn, limit: limit
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
logn
end
def wait task, secs: nil, text: nil, timeout: nil
secs ||= 0.1
spinners, spin, logn = "▖▘▝▗", 0, 0
STDERR.puts task.upid
host = task.host&.name
loop do
s = task.status
logn = self.task_log task, logn
if s.finished?
loop do
r = self.task_log task, logn
break if 0 == logn - r
logn = r
end
STDERR.printf "\r[%s] %s %s %s\e[J\n",
host || s.id,
s.successfull? ? "\e[32;1m✓\e[0m" : "\e[31;1m✗\e[0m",
text && "#{text}:",
s.stopped? ? :finished : s.status
return s
end
STDERR.printf "\r[%s] \e[33;1m%s\e[0m %s...\e[J",
host || s[:id],
spinners[spin = (spin + 1) % 4],
text || "Working"
sleep secs
end
end
def migrate host, node, timeout: nil, fire: nil, secs: nil, online: nil
timeout ||= 30
task = host.migrate Proxmox::Node.find_by_name!( node), online: online || false
wait task, text: "Migrating", timeout: timeout if fire
end
def start host, node: nil, timeout: nil, fire: nil, secs: nil
timeout ||= 60
if host.running?
STDERR.puts "Already running."
return
end
task = host.start
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
def stop host, timeout: nil, fire: nil, secs: nil
timeout ||= 30
if host.stopped?
STDERR.puts "Already stopped."
return
end
task = host.stop
t = Time.now
unless fire
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
def create klass, template, timeout: nil, fire: nil, start: nil, **options
options[:start] = fire && start
task = klass.create template, **options
return if fire
status = wait task, text: "Creating"
if status.successfull?
host = task.host.refresh!
start host, timeout: timeout, secs: secs if start
elsif not interactive?
exit 1
end
end
def destroy ct, timeout: nil, fire: nil, secs: nil
task = ct.destroy
unless fire
wait task, text: "Destroying"
end
end
def node_opt node = nil
node ? [Proxmox::Node.find_by_name!( node)] : Proxmox::Node.all
end
def target_opt target = nil, &exe
if target
target = /\A#{target}\z/
lambda {|n| exe.call n if n === target }
else
exe
end
end
def hosting_table target:, status:, sort:
connect
to = TablizedOutput.new %w[Status HA ID Name Host Uptime CPU/% Mem/MiB Mem/% Disk/MiB Disk/%], format: '<<<<<>>>>>>'
target &&= /\A#{target}\z/i
status =
case status
when /\Asta(r(t(ed?)?)?)?\z/i, /\Aon(l(i(ne?)?)?)?\z/i, /\Ar(u(n(n(i(ng?)?)?)?)?)?\z/i, '1'
%i[started online running]
when /\Asto(p(p(ed?)?)?)?\z/i, /\Aof(f(l(i(ne?)?)?)?)?\z/i, '0'
%i[stopped offline]
when nil, '', /\Aa(ll?)?\z/i then nil
else
raise DenKn::UsageError, "Unknown state #{status}"
end
push =
if target and status
lambda {|n| to.push tablized_virt( n) if n === target and status.include?( n.state) }
elsif target
lambda {|n| to.push tablized_virt( n) if n === target }
elsif status
lambda {|n| to.push tablized_virt( n) if status.include? n.state }
else
lambda {|n| to.push tablized_virt( n) }
end
yield push
to.print order: sort.each_char.map {|c| (2*c.ord[5]-1) * (' sainhucmd'.index( c.downcase)) }
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 complete_lxc f
Proxmox::LXC.all.
flat_map {|x| [x.name, x.vmid.to_s] }.
select {|x| f =~ x }
end
def complete_qemu f
Proxmox::Qemu.all.
flat_map {|x| [x.name, x.vmid.to_s] }.
select {|x| f =~ x }
end
def complete_node f
Proxmox::Qemu.all.
map {|x| x.name }.
select {|x| f =~ x }
end
def completion_helper *pre, arg, &exe
if pre.empty?
connect
xs = yield /\A#{Regexp.quote arg}/
STDOUT.print "\a" if xs.empty?
xs
else
STDOUT.print "\a"
[]
end
end
def prepare
cli_node
cli_ct
cli_qm
cli_task
cli_ha
cli_base
cli_storage
end
def call *argv
cli.call *argv
rescue RestClient::ExceptionWithResponse
STDERR.puts "#{$!.request}: #{$!.to_s} - #{$!.response} (#{$!.class})" #, $!.backtrace.map {|b|" #{b}"}
rescue UsageError, DenCli::UsageError
STDERR.puts $!
exit 1
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
system = applications = true if system.nil? and applications.nil?
node = node ? Proxmox::Node.find_by_name!( node) : Proxmox::Node.all.first
to = TablizedOutput.new %w<Section Package Version OS Template Description>, format: %w[> > > > > <]
node.aplinfo.
select {|a| 'system' == a.section ? system : applications}.
each do |apl|
to.push [
apl.section,
apl.package,
apl.version,
apl.os,
apl.template,
apl.description,
]
end
to.print order: [1,2]
end
COLORS = %w[black red green yellow blue magenta cyan white].each_with_index.to_h
def fgcolor color
color = color.to_s
if /\Abright[-_]?(.*)\z/ =~ color
c = COLORS[$1]
c.nil? ? nil : "1;3#{c}"
else
c = COLORS[color]
c.nil? ? nil : "3#{c}"
end
end
def tablized_virt v
ha = v.respond_to?( :ha) ? v.ha : nil
unknown = TablizedOutput::V.new 0, '-'
node = v.node.is_a?(String) ? v.node : v.node.node
if color = @cfg[:hosts]&.[](node.to_sym)&.[](:color)
node = ColoredString.new node, fgcolor( color)
end
[
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, node,
v.respond_to?(:uptime) ? TablizedOutput::V.new( v.uptime, Measured.seconds( v.uptime)) : unknown,
v.respond_to?(:cpu) ? TablizedOutput::Percentage.new( v.cpu) : unknown,
v.respond_to?(:mem) ? TablizedOutput::V.new( v.mem, Measured.bytes( v.mem)) : unknown,
v.respond_to?(:maxmem) ? TablizedOutput::Percentage.new( v.mem/v.maxmem.to_f) : unknown,
v.respond_to?(:disk) ? TablizedOutput::V.new( v.disk.to_i, Measured.bytes( v.disk.to_i)) : unknown,
if v.respond_to?(:maxdisk) and 0 < v.maxdisk.to_i
TablizedOutput::Percentage.new( v.disk.to_f/v.maxdisk.to_f)
else unknown end,
]
end
end