Skip to content

Commit f6b4dab

Browse files
barriserlothaustb
authored andcommitted
Use Logger for non-result output
This adds the Logger class for log output, all of which goes to STDERR, and uses puts to send only the command result to STDOUT.
1 parent 4755343 commit f6b4dab

File tree

7 files changed

+81
-67
lines changed

7 files changed

+81
-67
lines changed

lib/vmfloaty.rb

+41-37
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,15 @@
1313
require 'vmfloaty/utils'
1414
require 'vmfloaty/service'
1515
require 'vmfloaty/ssh'
16+
require 'vmfloaty/logger'
1617

1718
class Vmfloaty
1819
include Commander::Methods
1920

21+
def self.logger
22+
@logger ||= FloatyLogger.new
23+
end
24+
2025
def run # rubocop:disable Metrics/AbcSize
2126
program :version, Vmfloaty::VERSION
2227
program :description, "A CLI helper tool for Puppet's vmpooler to help you stay afloat"
@@ -45,7 +50,7 @@ def run # rubocop:disable Metrics/AbcSize
4550
force = options.force
4651

4752
if args.empty?
48-
STDERR.puts 'No operating systems provided to obtain. See `floaty get --help` for more information on how to get VMs.'
53+
logger.error 'No operating systems provided to obtain. See `floaty get --help` for more information on how to get VMs.'
4954
exit 1
5055
end
5156

@@ -54,13 +59,13 @@ def run # rubocop:disable Metrics/AbcSize
5459
max_pool_request = 5
5560
large_pool_requests = os_types.select { |_, v| v > max_pool_request }
5661
if !large_pool_requests.empty? && !force
57-
STDERR.puts "Requesting vms over #{max_pool_request} requires a --force flag."
58-
STDERR.puts 'Try again with `floaty get --force`'
62+
logger.error "Requesting vms over #{max_pool_request} requires a --force flag."
63+
logger.error 'Try again with `floaty get --force`'
5964
exit 1
6065
end
6166

6267
if os_types.empty?
63-
STDERR.puts 'No operating systems provided to obtain. See `floaty get --help` for more information on how to get VMs.'
68+
logger.error 'No operating systems provided to obtain. See `floaty get --help` for more information on how to get VMs.'
6469
exit 1
6570
end
6671

@@ -71,9 +76,9 @@ def run # rubocop:disable Metrics/AbcSize
7176
hosts = Utils.standardize_hostnames(response)
7277

7378
if options.json || options.ondemand
74-
STDOUT.puts JSON.pretty_generate(hosts)
79+
puts JSON.pretty_generate(hosts)
7580
else
76-
STDOUT.puts Utils.format_host_output(hosts)
81+
puts Utils.format_host_output(hosts)
7782
end
7883
end
7984
end
@@ -99,15 +104,15 @@ def run # rubocop:disable Metrics/AbcSize
99104
running_vms = service.list_active(verbose)
100105
host = URI.parse(service.url).host
101106
if running_vms.empty?
102-
STDOUT.puts "You have no running VMs on #{host}"
107+
puts "You have no running VMs on #{host}"
103108
else
104-
STDOUT.puts "Your VMs on #{host}:"
109+
puts "Your VMs on #{host}:"
105110
Utils.pretty_print_hosts(verbose, service, running_vms)
106111
end
107112
else
108113
# list available vms from pooler
109114
os_list = service.list(verbose, filter)
110-
STDOUT.puts os_list
115+
puts os_list
111116
end
112117
end
113118
end
@@ -151,7 +156,7 @@ def run # rubocop:disable Metrics/AbcSize
151156
modify_all = options.all
152157

153158
if hostname.nil? && !modify_all
154-
STDERR.puts 'ERROR: Provide a hostname or specify --all.'
159+
logger.error 'ERROR: Provide a hostname or specify --all.'
155160
exit 1
156161
end
157162
running_vms = modify_all ? service.list_active(verbose) : hostname.split(',')
@@ -172,17 +177,17 @@ def run # rubocop:disable Metrics/AbcSize
172177
begin
173178
modified_hash[vm] = service.modify(verbose, vm, modify_hash)
174179
rescue ModifyError => e
175-
STDERR.puts e
180+
logger.error e
176181
ok = false
177182
end
178183
end
179184
if ok
180185
if modify_all
181-
STDOUT.puts 'Successfully modified all VMs.'
186+
puts 'Successfully modified all VMs.'
182187
else
183-
STDOUT.puts "Successfully modified VM #{hostname}."
188+
puts "Successfully modified VM #{hostname}."
184189
end
185-
STDOUT.puts 'Use `floaty list --active` to see the results.'
190+
puts 'Use `floaty list --active` to see the results.'
186191
end
187192
end
188193
end
@@ -214,11 +219,10 @@ def run # rubocop:disable Metrics/AbcSize
214219
if delete_all
215220
running_vms = service.list_active(verbose)
216221
if running_vms.empty?
217-
STDOUT.puts 'You have no running VMs.'
222+
puts 'You have no running VMs.'
218223
else
219224
Utils.pretty_print_hosts(verbose, service, running_vms, true)
220225
# Confirm deletion
221-
STDERR.puts
222226
confirmed = true
223227
confirmed = agree('Delete all these VMs? [y/N]') unless force
224228
if confirmed
@@ -243,23 +247,23 @@ def run # rubocop:disable Metrics/AbcSize
243247
end
244248
end
245249
else
246-
STDERR.puts 'You did not provide any hosts to delete'
250+
logger.info 'You did not provide any hosts to delete'
247251
exit 1
248252
end
249253

250254
unless failures.empty?
251-
STDERR.puts 'Unable to delete the following VMs:'
255+
logger.info 'Unable to delete the following VMs:'
252256
failures.each do |hostname|
253-
STDERR.puts "- #{hostname}"
257+
logger.info "- #{hostname}"
254258
end
255-
STDERR.puts 'Check `floaty list --active`; Do you need to specify a different service?'
259+
logger.info 'Check `floaty list --active`; Do you need to specify a different service?'
256260
end
257261

258262
unless successes.empty?
259-
STDERR.puts unless failures.empty?
260-
STDOUT.puts 'Scheduled the following VMs for deletion:'
263+
logger.info unless failures.empty?
264+
puts 'Scheduled the following VMs for deletion:'
261265
successes.each do |hostname|
262-
STDOUT.puts "- #{hostname}"
266+
puts "- #{hostname}"
263267
end
264268
end
265269

@@ -284,11 +288,11 @@ def run # rubocop:disable Metrics/AbcSize
284288
begin
285289
snapshot_req = service.snapshot(verbose, hostname)
286290
rescue TokenError, ModifyError => e
287-
STDERR.puts e
291+
logger.error e
288292
exit 1
289293
end
290294

291-
STDOUT.puts "Snapshot pending. Use `floaty query #{hostname}` to determine when snapshot is valid."
295+
puts "Snapshot pending. Use `floaty query #{hostname}` to determine when snapshot is valid."
292296
pp snapshot_req
293297
end
294298
end
@@ -309,12 +313,12 @@ def run # rubocop:disable Metrics/AbcSize
309313
hostname = args[0]
310314
snapshot_sha = args[1] || options.snapshot
311315

312-
STDERR.puts "Two snapshot arguments were given....using snapshot #{snapshot_sha}" if args[1] && options.snapshot
316+
logger.info "Two snapshot arguments were given....using snapshot #{snapshot_sha}" if args[1] && options.snapshot
313317

314318
begin
315319
revert_req = service.revert(verbose, hostname, snapshot_sha)
316320
rescue TokenError, ModifyError => e
317-
STDERR.puts e
321+
logger.error e
318322
exit 1
319323
end
320324

@@ -379,24 +383,24 @@ def run # rubocop:disable Metrics/AbcSize
379383
case action
380384
when 'get'
381385
token = service.get_new_token(verbose)
382-
STDOUT.puts token
386+
puts token
383387
when 'delete'
384388
result = service.delete_token(verbose, options.token)
385-
STDOUT.puts result
389+
puts result
386390
when 'status'
387391
token_value = options.token
388392
token_value = args[1] if token_value.nil?
389393
status = service.token_status(verbose, token_value)
390-
STDOUT.puts status
394+
puts status
391395
when nil
392-
STDERR.puts 'No action provided'
396+
logger.error 'No action provided'
393397
exit 1
394398
else
395-
STDERR.puts "Unknown action: #{action}"
399+
logger.error "Unknown action: #{action}"
396400
exit 1
397401
end
398402
rescue TokenError => e
399-
STDERR.puts e
403+
logger.error e
400404
exit 1
401405
end
402406
exit 0
@@ -420,13 +424,13 @@ def run # rubocop:disable Metrics/AbcSize
420424
use_token = !options.notoken
421425

422426
if args.empty?
423-
STDERR.puts 'No operating systems provided to obtain. See `floaty ssh --help` for more information on how to get VMs.'
427+
logger.error 'No operating systems provided to obtain. See `floaty ssh --help` for more information on how to get VMs.'
424428
exit 1
425429
end
426430

427431
host_os = args.first
428432

429-
STDERR.puts "Can't ssh to multiple hosts; Using #{host_os} only..." if args.length > 1
433+
logger.info "Can't ssh to multiple hosts; Using #{host_os} only..." if args.length > 1
430434

431435
service.ssh(verbose, host_os, use_token)
432436
exit 0
@@ -450,10 +454,10 @@ def run # rubocop:disable Metrics/AbcSize
450454
completion_file = File.expand_path(File.join('..', '..', 'extras', 'completions', "floaty.#{shell}"), __FILE__)
451455

452456
if File.exist?(completion_file)
453-
STDOUT.puts completion_file
457+
puts completion_file
454458
exit 0
455459
else
456-
STDERR.puts "Could not find completion file for '#{shell}': No such file #{completion_file}"
460+
logger.error "Could not find completion file for '#{shell}': No such file #{completion_file}"
457461
exit 1
458462
end
459463
end

lib/vmfloaty/abs.rb

+9-9
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def self.get_active_requests(verbose, url, user)
6868

6969
ret_val.push(req_hash)
7070
rescue NoMethodError
71-
STDERR.puts "Warning: couldn't parse line returned from abs/status/queue: ".yellow
71+
"Warning: couldn't parse line returned from abs/status/queue: ".yellow
7272
end
7373
end
7474

@@ -85,7 +85,7 @@ def self.delete(verbose, url, hosts, token, user)
8585
conn = Http.get_conn(verbose, url)
8686
conn.headers['X-AUTH-TOKEN'] = token if token
8787

88-
STDERR.puts "Trying to delete hosts #{hosts}" if verbose
88+
Vmfloaty.logger.info "Trying to delete hosts #{hosts}" if verbose
8989
requests = get_active_requests(verbose, url, user)
9090

9191
jobs_to_delete = []
@@ -113,7 +113,7 @@ def self.delete(verbose, url, hosts, token, user)
113113
}
114114
jobs_to_delete.push(req_hash)
115115
else
116-
STDERR.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']}"
116+
Vmfloaty.logger.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']}"
117117
end
118118
end
119119
end
@@ -127,7 +127,7 @@ def self.delete(verbose, url, hosts, token, user)
127127
'hosts' => job['allocated_resources'],
128128
}
129129

130-
STDERR.puts "Deleting #{req_obj}" if verbose
130+
Vmfloaty.logger.info "Deleting #{req_obj}" if verbose
131131

132132
return_result = conn.post 'return', req_obj.to_json
133133
req_obj['hosts'].each do |host|
@@ -220,11 +220,11 @@ def self.retrieve(verbose, os_types, token, url, user, options, _ondemand = nil)
220220
end
221221
end
222222

223-
STDERR.puts "Posting to ABS #{req_obj.to_json}" if verbose
223+
Vmfloaty.logger.info "Posting to ABS #{req_obj.to_json}" if verbose
224224

225225
# os_string = os_type.map { |os, num| Array(os) * num }.flatten.join('+')
226226
# raise MissingParamError, 'No operating systems provided to obtain.' if os_string.empty?
227-
STDERR.puts "Requesting VMs with job_id: #{saved_job_id}. Will retry for up to an hour."
227+
Vmfloaty.logger.info "Requesting VMs with job_id: #{saved_job_id}. Will retry for up to an hour."
228228
res = conn.post 'request', req_obj.to_json
229229

230230
retries = 360
@@ -237,7 +237,7 @@ def self.retrieve(verbose, os_types, token, url, user, options, _ondemand = nil)
237237

238238
sleep_seconds = 10 if i >= 10
239239
sleep_seconds = i if i < 10
240-
STDERR.puts "Waiting #{sleep_seconds} seconds to check if ABS request has been filled. Queue Position: #{queue_place}... (x#{i})"
240+
Vmfloaty.logger.info "Waiting #{sleep_seconds} seconds to check if ABS request has been filled. Queue Position: #{queue_place}... (x#{i})"
241241

242242
sleep(sleep_seconds)
243243
end
@@ -276,7 +276,7 @@ def self.check_queue(conn, job_id, req_obj)
276276
end
277277

278278
def self.snapshot(_verbose, _url, _hostname, _token)
279-
STDERR.puts "Can't snapshot with ABS, use '--service vmpooler' (even for vms checked out with ABS)"
279+
Vmfloaty.logger.info "Can't snapshot with ABS, use '--service vmpooler' (even for vms checked out with ABS)"
280280
end
281281

282282
def self.status(verbose, url)
@@ -297,7 +297,7 @@ def self.summary(verbose, url)
297297
def self.query(verbose, url, hostname)
298298
return @active_hostnames if @active_hostnames
299299

300-
STDERR.puts "For vmpooler/snapshot information, use '--service vmpooler' (even for vms checked out with ABS)"
300+
Vmfloaty.logger.info "For vmpooler/snapshot information, use '--service vmpooler' (even for vms checked out with ABS)"
301301
conn = Http.get_conn(verbose, url)
302302

303303
res = conn.get "host/#{hostname}"

lib/vmfloaty/conf.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def self.read_config
88
begin
99
conf = YAML.load_file("#{Dir.home}/.vmfloaty.yml")
1010
rescue StandardError
11-
STDERR.puts "WARNING: There was no config file at #{Dir.home}/.vmfloaty.yml"
11+
Vmfloaty.logger.warn "WARNING: There was no config file at #{Dir.home}/.vmfloaty.yml"
1212
end
1313
conf
1414
end

lib/vmfloaty/logger.rb

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
require 'logger'
2+
3+
class FloatyLogger < ::Logger
4+
def initialize
5+
super(STDERR)
6+
self.level = ::Logger::INFO
7+
self.formatter = proc do |severity, datetime, progname, msg|
8+
"#{msg}\n"
9+
end
10+
end
11+
end

lib/vmfloaty/pooler.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,10 @@ def self.wait_for_request(verbose, request_id, url, timeout = 300)
6060
while check_ondemandvm(verbose, request_id, url) == false
6161
return false if (Time.now - start_time).to_i > timeout
6262

63-
STDOUT.puts "waiting for request #{request_id} to be fulfilled"
63+
Vmfloaty.logger.info "waiting for request #{request_id} to be fulfilled"
6464
sleep 5
6565
end
66-
STDOUT.puts "The request has been fulfilled"
66+
Vmfloaty.logger.info "The request has been fulfilled"
6767
check_ondemandvm(verbose, request_id, url)
6868
end
6969

lib/vmfloaty/service.rb

+5-5
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,15 @@ def type
3636

3737
def user
3838
unless @config['user']
39-
STDERR.puts "Enter your #{@config['url']} service username:"
39+
Vmfloaty.logger.info "Enter your #{@config['url']} service username:"
4040
@config['user'] = STDIN.gets.chomp
4141
end
4242
@config['user']
4343
end
4444

4545
def token
4646
unless @config['token']
47-
STDERR.puts 'No token found. Retrieving a token...'
47+
Vmfloaty.logger.info 'No token found. Retrieving a token...'
4848
@config['token'] = get_new_token(nil)
4949
end
5050
@config['token']
@@ -76,7 +76,7 @@ def list_active(verbose)
7676
end
7777

7878
def retrieve(verbose, os_types, use_token = true, ondemand = nil)
79-
STDERR.puts 'Requesting a vm without a token...' unless use_token
79+
Vmfloaty.logger.info 'Requesting a vm without a token...' unless use_token
8080
token_value = use_token ? token : nil
8181
@service_object.retrieve verbose, os_types, token_value, url, user, @config, ondemand
8282
end
@@ -91,8 +91,8 @@ def ssh(verbose, host_os, use_token = true)
9191
begin
9292
token_value = token || get_new_token(verbose)
9393
rescue TokenError => e
94-
STDERR.puts e
95-
STDERR.puts 'Could not get token... requesting vm without a token anyway...'
94+
Vmfloaty.logger.error e
95+
Vmfloaty.logger.info 'Could not get token... requesting vm without a token anyway...'
9696
end
9797
end
9898
Ssh.ssh(verbose, self, host_os, token_value)

0 commit comments

Comments
 (0)