Merge pull request #84 from austb/print-debug-to-stderr

Print all non-success output to STDERR
This commit is contained in:
mattkirby 2020-08-12 11:34:11 -07:00 committed by GitHub
commit 3b91d6f582
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 77 additions and 60 deletions

View file

@ -13,6 +13,7 @@ require 'vmfloaty/conf'
require 'vmfloaty/utils' require 'vmfloaty/utils'
require 'vmfloaty/service' require 'vmfloaty/service'
require 'vmfloaty/ssh' require 'vmfloaty/ssh'
require 'vmfloaty/logger'
class Vmfloaty class Vmfloaty
include Commander::Methods include Commander::Methods
@ -45,7 +46,7 @@ class Vmfloaty
force = options.force force = options.force
if args.empty? if args.empty?
STDERR.puts 'No operating systems provided to obtain. See `floaty get --help` for more information on how to get VMs.' FloatyLogger.error 'No operating systems provided to obtain. See `floaty get --help` for more information on how to get VMs.'
exit 1 exit 1
end end
@ -54,13 +55,13 @@ class Vmfloaty
max_pool_request = 5 max_pool_request = 5
large_pool_requests = os_types.select { |_, v| v > max_pool_request } large_pool_requests = os_types.select { |_, v| v > max_pool_request }
if !large_pool_requests.empty? && !force if !large_pool_requests.empty? && !force
STDERR.puts "Requesting vms over #{max_pool_request} requires a --force flag." FloatyLogger.error "Requesting vms over #{max_pool_request} requires a --force flag."
STDERR.puts 'Try again with `floaty get --force`' FloatyLogger.error 'Try again with `floaty get --force`'
exit 1 exit 1
end end
if os_types.empty? if os_types.empty?
STDERR.puts 'No operating systems provided to obtain. See `floaty get --help` for more information on how to get VMs.' FloatyLogger.error 'No operating systems provided to obtain. See `floaty get --help` for more information on how to get VMs.'
exit 1 exit 1
end end
@ -151,7 +152,7 @@ class Vmfloaty
modify_all = options.all modify_all = options.all
if hostname.nil? && !modify_all if hostname.nil? && !modify_all
STDERR.puts 'ERROR: Provide a hostname or specify --all.' FloatyLogger.error 'ERROR: Provide a hostname or specify --all.'
exit 1 exit 1
end end
running_vms = modify_all ? service.list_active(verbose) : hostname.split(',') running_vms = modify_all ? service.list_active(verbose) : hostname.split(',')
@ -172,7 +173,7 @@ class Vmfloaty
begin begin
modified_hash[vm] = service.modify(verbose, vm, modify_hash) modified_hash[vm] = service.modify(verbose, vm, modify_hash)
rescue ModifyError => e rescue ModifyError => e
STDERR.puts e FloatyLogger.error e
ok = false ok = false
end end
end end
@ -214,11 +215,10 @@ class Vmfloaty
if delete_all if delete_all
running_vms = service.list_active(verbose) running_vms = service.list_active(verbose)
if running_vms.empty? if running_vms.empty?
STDERR.puts 'You have no running VMs.' puts 'You have no running VMs.'
else else
Utils.pretty_print_hosts(verbose, service, running_vms) Utils.pretty_print_hosts(verbose, service, running_vms, true)
# Confirm deletion # Confirm deletion
puts
confirmed = true confirmed = true
confirmed = agree('Delete all these VMs? [y/N]') unless force confirmed = agree('Delete all these VMs? [y/N]') unless force
if confirmed if confirmed
@ -243,20 +243,20 @@ class Vmfloaty
end end
end end
else else
STDERR.puts 'You did not provide any hosts to delete' FloatyLogger.info 'You did not provide any hosts to delete'
exit 1 exit 1
end end
unless failures.empty? unless failures.empty?
STDERR.puts 'Unable to delete the following VMs:' FloatyLogger.info 'Unable to delete the following VMs:'
failures.each do |hostname| failures.each do |hostname|
STDERR.puts "- #{hostname}" FloatyLogger.info "- #{hostname}"
end end
STDERR.puts 'Check `floaty list --active`; Do you need to specify a different service?' FloatyLogger.info 'Check `floaty list --active`; Do you need to specify a different service?'
end end
unless successes.empty? unless successes.empty?
puts unless failures.empty? FloatyLogger.info unless failures.empty?
puts 'Scheduled the following VMs for deletion:' puts 'Scheduled the following VMs for deletion:'
successes.each do |hostname| successes.each do |hostname|
puts "- #{hostname}" puts "- #{hostname}"
@ -284,7 +284,7 @@ class Vmfloaty
begin begin
snapshot_req = service.snapshot(verbose, hostname) snapshot_req = service.snapshot(verbose, hostname)
rescue TokenError, ModifyError => e rescue TokenError, ModifyError => e
STDERR.puts e FloatyLogger.error e
exit 1 exit 1
end end
@ -309,12 +309,12 @@ class Vmfloaty
hostname = args[0] hostname = args[0]
snapshot_sha = args[1] || options.snapshot snapshot_sha = args[1] || options.snapshot
STDERR.puts "Two snapshot arguments were given....using snapshot #{snapshot_sha}" if args[1] && options.snapshot FloatyLogger.info "Two snapshot arguments were given....using snapshot #{snapshot_sha}" if args[1] && options.snapshot
begin begin
revert_req = service.revert(verbose, hostname, snapshot_sha) revert_req = service.revert(verbose, hostname, snapshot_sha)
rescue TokenError, ModifyError => e rescue TokenError, ModifyError => e
STDERR.puts e FloatyLogger.error e
exit 1 exit 1
end end
@ -389,14 +389,14 @@ class Vmfloaty
status = service.token_status(verbose, token_value) status = service.token_status(verbose, token_value)
puts status puts status
when nil when nil
STDERR.puts 'No action provided' FloatyLogger.error 'No action provided'
exit 1 exit 1
else else
STDERR.puts "Unknown action: #{action}" FloatyLogger.error "Unknown action: #{action}"
exit 1 exit 1
end end
rescue TokenError => e rescue TokenError => e
STDERR.puts e FloatyLogger.error e
exit 1 exit 1
end end
exit 0 exit 0
@ -420,13 +420,13 @@ class Vmfloaty
use_token = !options.notoken use_token = !options.notoken
if args.empty? if args.empty?
STDERR.puts 'No operating systems provided to obtain. See `floaty ssh --help` for more information on how to get VMs.' FloatyLogger.error 'No operating systems provided to obtain. See `floaty ssh --help` for more information on how to get VMs.'
exit 1 exit 1
end end
host_os = args.first host_os = args.first
STDERR.puts "Can't ssh to multiple hosts; Using #{host_os} only..." if args.length > 1 FloatyLogger.info "Can't ssh to multiple hosts; Using #{host_os} only..." if args.length > 1
service.ssh(verbose, host_os, use_token) service.ssh(verbose, host_os, use_token)
exit 0 exit 0
@ -453,7 +453,7 @@ class Vmfloaty
puts completion_file puts completion_file
exit 0 exit 0
else else
STDERR.puts "Could not find completion file for '#{shell}': No such file #{completion_file}" FloatyLogger.error "Could not find completion file for '#{shell}': No such file #{completion_file}"
exit 1 exit 1
end end
end end

View file

@ -68,7 +68,7 @@ class ABS
ret_val.push(req_hash) ret_val.push(req_hash)
rescue NoMethodError rescue NoMethodError
puts "Warning: couldn't parse line returned from abs/status/queue: ".yellow FloatyLogger.warn "Warning: couldn't parse line returned from abs/status/queue: "
end end
end end
@ -85,7 +85,7 @@ class ABS
conn = Http.get_conn(verbose, url) conn = Http.get_conn(verbose, url)
conn.headers['X-AUTH-TOKEN'] = token if token conn.headers['X-AUTH-TOKEN'] = token if token
puts "Trying to delete hosts #{hosts}" if verbose FloatyLogger.info "Trying to delete hosts #{hosts}" if verbose
requests = get_active_requests(verbose, url, user) requests = get_active_requests(verbose, url, user)
jobs_to_delete = [] jobs_to_delete = []
@ -113,7 +113,7 @@ class ABS
} }
jobs_to_delete.push(req_hash) jobs_to_delete.push(req_hash)
else else
puts "When using ABS you must delete all vms that you requested at the same time: Can't delete #{req_hash['request']['job']['id']}: #{hosts} does not include all of #{req_hash['allocated_resources']}" FloatyLogger.info "When using ABS you must delete all vms that you requested at the same time: Can't delete #{req_hash['request']['job']['id']}: #{hosts} does not include all of #{req_hash['allocated_resources']}"
end end
end end
end end
@ -127,7 +127,7 @@ class ABS
'hosts' => job['allocated_resources'], 'hosts' => job['allocated_resources'],
} }
puts "Deleting #{req_obj}" if verbose FloatyLogger.info "Deleting #{req_obj}" if verbose
return_result = conn.post 'return', req_obj.to_json return_result = conn.post 'return', req_obj.to_json
req_obj['hosts'].each do |host| req_obj['hosts'].each do |host|
@ -220,11 +220,11 @@ class ABS
end end
end end
puts "Posting to ABS #{req_obj.to_json}" if verbose FloatyLogger.info "Posting to ABS #{req_obj.to_json}" if verbose
# os_string = os_type.map { |os, num| Array(os) * num }.flatten.join('+') # os_string = os_type.map { |os, num| Array(os) * num }.flatten.join('+')
# raise MissingParamError, 'No operating systems provided to obtain.' if os_string.empty? # raise MissingParamError, 'No operating systems provided to obtain.' if os_string.empty?
puts "Requesting VMs with job_id: #{saved_job_id}. Will retry for up to an hour." FloatyLogger.info "Requesting VMs with job_id: #{saved_job_id}. Will retry for up to an hour."
res = conn.post 'request', req_obj.to_json res = conn.post 'request', req_obj.to_json
retries = 360 retries = 360
@ -237,7 +237,7 @@ class ABS
sleep_seconds = 10 if i >= 10 sleep_seconds = 10 if i >= 10
sleep_seconds = i if i < 10 sleep_seconds = i if i < 10
puts "Waiting #{sleep_seconds} seconds to check if ABS request has been filled. Queue Position: #{queue_place}... (x#{i})" FloatyLogger.info "Waiting #{sleep_seconds} seconds to check if ABS request has been filled. Queue Position: #{queue_place}... (x#{i})"
sleep(sleep_seconds) sleep(sleep_seconds)
end end
@ -276,7 +276,7 @@ class ABS
end end
def self.snapshot(_verbose, _url, _hostname, _token) def self.snapshot(_verbose, _url, _hostname, _token)
puts "Can't snapshot with ABS, use '--service vmpooler' (even for vms checked out with ABS)" FloatyLogger.info "Can't snapshot with ABS, use '--service vmpooler' (even for vms checked out with ABS)"
end end
def self.status(verbose, url) def self.status(verbose, url)
@ -297,7 +297,7 @@ class ABS
def self.query(verbose, url, hostname) def self.query(verbose, url, hostname)
return @active_hostnames if @active_hostnames return @active_hostnames if @active_hostnames
puts "For vmpooler/snapshot information, use '--service vmpooler' (even for vms checked out with ABS)" FloatyLogger.info "For vmpooler/snapshot information, use '--service vmpooler' (even for vms checked out with ABS)"
conn = Http.get_conn(verbose, url) conn = Http.get_conn(verbose, url)
res = conn.get "host/#{hostname}" res = conn.get "host/#{hostname}"

View file

@ -8,7 +8,7 @@ class Conf
begin begin
conf = YAML.load_file("#{Dir.home}/.vmfloaty.yml") conf = YAML.load_file("#{Dir.home}/.vmfloaty.yml")
rescue StandardError rescue StandardError
STDERR.puts "WARNING: There was no config file at #{Dir.home}/.vmfloaty.yml" FloatyLogger.warn "WARNING: There was no config file at #{Dir.home}/.vmfloaty.yml"
end end
conf conf
end end

27
lib/vmfloaty/logger.rb Normal file
View file

@ -0,0 +1,27 @@
require 'logger'
class FloatyLogger < ::Logger
def self.logger
@@logger ||= FloatyLogger.new
end
def self.info(msg)
FloatyLogger.logger.info msg
end
def self.warn(msg)
FloatyLogger.logger.warn msg
end
def self.error(msg)
FloatyLogger.logger.error msg
end
def initialize
super(STDERR)
self.level = ::Logger::INFO
self.formatter = proc do |severity, datetime, progname, msg|
"#{msg}\n"
end
end
end

View file

@ -60,10 +60,10 @@ class Pooler
while check_ondemandvm(verbose, request_id, url) == false while check_ondemandvm(verbose, request_id, url) == false
return false if (Time.now - start_time).to_i > timeout return false if (Time.now - start_time).to_i > timeout
STDOUT.puts "waiting for request #{request_id} to be fulfilled" FloatyLogger.info "waiting for request #{request_id} to be fulfilled"
sleep 5 sleep 5
end end
STDOUT.puts "The request has been fulfilled" FloatyLogger.info "The request has been fulfilled"
check_ondemandvm(verbose, request_id, url) check_ondemandvm(verbose, request_id, url)
end end

View file

@ -36,7 +36,7 @@ class Service
def user def user
unless @config['user'] unless @config['user']
puts "Enter your #{@config['url']} service username:" FloatyLogger.info "Enter your #{@config['url']} service username:"
@config['user'] = STDIN.gets.chomp @config['user'] = STDIN.gets.chomp
end end
@config['user'] @config['user']
@ -44,7 +44,7 @@ class Service
def token def token
unless @config['token'] unless @config['token']
puts 'No token found. Retrieving a token...' FloatyLogger.info 'No token found. Retrieving a token...'
@config['token'] = get_new_token(nil) @config['token'] = get_new_token(nil)
end end
@config['token'] @config['token']
@ -76,7 +76,7 @@ class Service
end end
def retrieve(verbose, os_types, use_token = true, ondemand = nil) def retrieve(verbose, os_types, use_token = true, ondemand = nil)
puts 'Requesting a vm without a token...' unless use_token FloatyLogger.info 'Requesting a vm without a token...' unless use_token
token_value = use_token ? token : nil token_value = use_token ? token : nil
@service_object.retrieve verbose, os_types, token_value, url, user, @config, ondemand @service_object.retrieve verbose, os_types, token_value, url, user, @config, ondemand
end end
@ -91,22 +91,13 @@ class Service
begin begin
token_value = token || get_new_token(verbose) token_value = token || get_new_token(verbose)
rescue TokenError => e rescue TokenError => e
STDERR.puts e FloatyLogger.error e
STDERR.puts 'Could not get token... requesting vm without a token anyway...' FloatyLogger.info 'Could not get token... requesting vm without a token anyway...'
end end
end end
Ssh.ssh(verbose, self, host_os, token_value) Ssh.ssh(verbose, self, host_os, token_value)
end end
def pretty_print_running(verbose, hostnames = [])
if hostnames.empty?
puts 'You have no running VMs.'
else
puts 'Running VMs:'
@service_object.pretty_print_hosts(verbose, hostnames, url)
end
end
def query(verbose, hostname) def query(verbose, hostname)
@service_object.query verbose, url, hostname @service_object.query verbose, url, hostname
end end

View file

@ -45,7 +45,6 @@ class Utils
result = {} result = {}
STDOUT.puts "response body is #{response_body}"
filtered_response_body = response_body.reject { |key, _| key == 'request_id' || key == 'ready' } filtered_response_body = response_body.reject { |key, _| key == 'request_id' || key == 'ready' }
filtered_response_body.each do |os, value| filtered_response_body.each do |os, value|
hostnames = Array(value['hostname']) hostnames = Array(value['hostname'])
@ -79,7 +78,7 @@ class Utils
os_types os_types
end end
def self.pretty_print_hosts(verbose, service, hostnames = []) def self.pretty_print_hosts(verbose, service, hostnames = [], print_to_stderr = false)
hostnames = [hostnames] unless hostnames.is_a? Array hostnames = [hostnames] unless hostnames.is_a? Array
hostnames.each do |hostname| hostnames.each do |hostname|
begin begin
@ -110,8 +109,8 @@ class Utils
raise "Invalid service type #{service.type}" raise "Invalid service type #{service.type}"
end end
rescue StandardError => e rescue StandardError => e
STDERR.puts("Something went wrong while trying to gather information on #{hostname}:") FloatyLogger.error("Something went wrong while trying to gather information on #{hostname}:")
STDERR.puts(e) FloatyLogger.error(e)
end end
end end
end end
@ -135,7 +134,7 @@ class Utils
char = 'o' char = 'o'
puts "#{name.ljust(width)} #{(char * ready).green}#{(char * pending).yellow}#{(char * missing).red}" puts "#{name.ljust(width)} #{(char * ready).green}#{(char * pending).yellow}#{(char * missing).red}"
rescue StandardError => e rescue StandardError => e
puts "#{name.ljust(width)} #{e.red}" FloatyLogger.error "#{name.ljust(width)} #{e.red}"
end end
end end
puts message.colorize(status_response['status']['ok'] ? :default : :red) puts message.colorize(status_response['status']['ok'] ? :default : :red)
@ -154,11 +153,11 @@ class Utils
char = 'o' char = 'o'
puts "#{name.ljust(width)} #{(char * ready).green}#{(char * pending).yellow}#{(char * missing).red}" puts "#{name.ljust(width)} #{(char * ready).green}#{(char * pending).yellow}#{(char * missing).red}"
rescue StandardError => e rescue StandardError => e
puts "#{name.ljust(width)} #{e.red}" FloatyLogger.error "#{name.ljust(width)} #{e.red}"
end end
end end
when 'ABS' when 'ABS'
puts 'ABS Not OK'.red unless status_response FloatyLogger.error 'ABS Not OK' unless status_response
puts 'ABS is OK'.green if status_response puts 'ABS is OK'.green if status_response
else else
raise "Invalid service type #{service.type}" raise "Invalid service type #{service.type}"

View file

@ -169,7 +169,7 @@ describe Utils do
} } } }
output = '- mcpy42eqjxli9g2.delivery.mycompany.net (ubuntu-1604-x86_64, 9.66/12 hours)' output = '- mcpy42eqjxli9g2.delivery.mycompany.net (ubuntu-1604-x86_64, 9.66/12 hours)'
expect(Utils).to receive(:puts).with(output) expect(STDOUT).to receive(:puts).with(output)
service = Service.new(MockOptions.new, 'url' => url) service = Service.new(MockOptions.new, 'url' => url)
allow(service).to receive(:query) allow(service).to receive(:query)
@ -195,7 +195,7 @@ describe Utils do
} } } }
output = '- aiydvzpg23r415q.delivery.mycompany.net (redhat-7-x86_64, 7.67/48 hours, user: bob, role: agent)' output = '- aiydvzpg23r415q.delivery.mycompany.net (redhat-7-x86_64, 7.67/48 hours, user: bob, role: agent)'
expect(Utils).to receive(:puts).with(output) expect(STDOUT).to receive(:puts).with(output)
service = Service.new(MockOptions.new, 'url' => url) service = Service.new(MockOptions.new, 'url' => url)
allow(service).to receive(:query) allow(service).to receive(:query)
@ -216,7 +216,7 @@ describe Utils do
} } } }
output = '- sol11-9.delivery.mycompany.net (solaris-11-sparc, 35.89h remaining)' output = '- sol11-9.delivery.mycompany.net (solaris-11-sparc, 35.89h remaining)'
expect(Utils).to receive(:puts).with(output) expect(STDOUT).to receive(:puts).with(output)
service = Service.new(MockOptions.new, 'url' => url, 'type' => 'ns') service = Service.new(MockOptions.new, 'url' => url, 'type' => 'ns')
allow(service).to receive(:query) allow(service).to receive(:query)
@ -237,7 +237,7 @@ describe Utils do
} } } }
output = '- sol11-9.delivery.mycompany.net (solaris-11-sparc, 35.89h remaining, reason: testing)' output = '- sol11-9.delivery.mycompany.net (solaris-11-sparc, 35.89h remaining, reason: testing)'
expect(Utils).to receive(:puts).with(output) expect(STDOUT).to receive(:puts).with(output)
service = Service.new(MockOptions.new, 'url' => url, 'type' => 'ns') service = Service.new(MockOptions.new, 'url' => url, 'type' => 'ns')
allow(service).to receive(:query) allow(service).to receive(:query)