Merge pull request #135 from puppetlabs/rubocop_auto_fix

Run the rubocop auto_correct
This commit is contained in:
Gene Liverman 2021-07-12 10:04:35 -04:00 committed by GitHub
commit 302d52a45e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
21 changed files with 516 additions and 511 deletions

View file

@ -4,7 +4,7 @@ source 'https://rubygems.org'
gemspec gemspec
gem 'rake', :require => false gem 'rake', require: false
group :test do group :test do
gem 'coveralls', '~> 0.8.23' gem 'coveralls', '~> 0.8.23'

View file

@ -28,4 +28,4 @@ RuboCop::RakeTask.new(:rubocop) do |task|
end end
# Default task is to run the unit tests # Default task is to run the unit tests
task :default => :spec task default: :spec

View file

@ -20,7 +20,8 @@ class Vmfloaty
def run # rubocop:disable Metrics/AbcSize def run # rubocop:disable Metrics/AbcSize
program :version, Vmfloaty::VERSION program :version, Vmfloaty::VERSION
program :description, "A CLI helper tool for Puppet's vmpooler to help you stay afloat.\n\nConfiguration may be placed in a ~/.vmfloaty.yml file." program :description,
"A CLI helper tool for Puppet's vmpooler to help you stay afloat.\n\nConfiguration may be placed in a ~/.vmfloaty.yml file."
config = Conf.read_config config = Conf.read_config
@ -43,9 +44,7 @@ class Vmfloaty
c.option '--loglevel STRING', String, 'the log level to use (debug, info, error)' c.option '--loglevel STRING', String, 'the log level to use (debug, info, error)'
c.action do |args, options| c.action do |args, options|
verbose = options.verbose || config['verbose'] verbose = options.verbose || config['verbose']
if options.loglevel FloatyLogger.setlevel = options.loglevel if options.loglevel
FloatyLogger.setlevel = options.loglevel
end
service = Service.new(options, config) service = Service.new(options, config)
use_token = !options.notoken use_token = !options.notoken
force = options.force force = options.force
@ -100,21 +99,19 @@ class Vmfloaty
c.option '--loglevel STRING', String, 'the log level to use (debug, info, error)' c.option '--loglevel STRING', String, 'the log level to use (debug, info, error)'
c.action do |args, options| c.action do |args, options|
verbose = options.verbose || config['verbose'] verbose = options.verbose || config['verbose']
if options.loglevel FloatyLogger.setlevel = options.loglevel if options.loglevel
FloatyLogger.setlevel = options.loglevel
end
service = Service.new(options, config) service = Service.new(options, config)
filter = args[0] filter = args[0]
if options.active if options.active
# list active vms # list active vms
if service.type == "ABS" running_vms = if service.type == 'ABS'
# this is actually job_ids # this is actually job_ids
running_vms = service.list_active_job_ids(verbose, service.url, service.user) service.list_active_job_ids(verbose, service.url, service.user)
else else
running_vms = service.list_active(verbose) service.list_active(verbose)
end end
host = URI.parse(service.url).host host = URI.parse(service.url).host
if running_vms.empty? if running_vms.empty?
if options.json if options.json
@ -122,17 +119,15 @@ class Vmfloaty
else else
FloatyLogger.info "You have no running VMs on #{host}" FloatyLogger.info "You have no running VMs on #{host}"
end end
else elsif options.json
if options.json puts Utils.get_host_data(verbose, service, running_vms).to_json
puts Utils.get_host_data(verbose, service, running_vms).to_json elsif options.hostnameonly
elsif options.hostnameonly Utils.get_host_data(verbose, service, running_vms).each do |hostname, host_data|
Utils.get_host_data(verbose, service, running_vms).each do |hostname, host_data| Utils.print_fqdn_for_host(service, hostname, host_data)
Utils.print_fqdn_for_host(service, hostname, host_data)
end
else
puts "Your VMs on #{host}:"
Utils.pretty_print_hosts(verbose, service, running_vms)
end end
else
puts "Your VMs on #{host}:"
Utils.pretty_print_hosts(verbose, service, running_vms)
end end
else else
# list available vms from pooler # list available vms from pooler
@ -164,7 +159,8 @@ class Vmfloaty
c.syntax = 'floaty modify hostname [options]' c.syntax = 'floaty modify hostname [options]'
c.summary = 'Modify a VM\'s tags, time to live, disk space, or reservation reason' c.summary = 'Modify a VM\'s tags, time to live, disk space, or reservation reason'
c.description = 'This command makes modifications to the virtual machines state in the pooler service. You can either append tags to the vm, increase how long it stays active for, or increase the amount of disk space.' c.description = 'This command makes modifications to the virtual machines state in the pooler service. You can either append tags to the vm, increase how long it stays active for, or increase the amount of disk space.'
c.example 'Modifies myhost1 to have a TTL of 12 hours and adds a custom tag', 'floaty modify myhost1 --lifetime 12 --url https://myurl --token mytokenstring --tags \'{"tag":"myvalue"}\'' c.example 'Modifies myhost1 to have a TTL of 12 hours and adds a custom tag',
'floaty modify myhost1 --lifetime 12 --url https://myurl --token mytokenstring --tags \'{"tag":"myvalue"}\''
c.option '--verbose', 'Enables verbose output' c.option '--verbose', 'Enables verbose output'
c.option '--service STRING', String, 'Configured pooler service name' c.option '--service STRING', String, 'Configured pooler service name'
c.option '--url STRING', String, 'URL of pooler service' c.option '--url STRING', String, 'URL of pooler service'
@ -185,18 +181,18 @@ class Vmfloaty
exit 1 exit 1
end end
running_vms = running_vms =
if modify_all if modify_all
service.list_active(verbose) service.list_active(verbose)
else else
hostname.split(',') hostname.split(',')
end end
tags = options.tags ? JSON.parse(options.tags) : nil tags = options.tags ? JSON.parse(options.tags) : nil
modify_hash = { modify_hash = {
:lifetime => options.lifetime, lifetime: options.lifetime,
:disk => options.disk, disk: options.disk,
:tags => tags, tags: tags,
:reason => options.reason, reason: options.reason
} }
modify_hash.delete_if { |_, value| value.nil? } modify_hash.delete_if { |_, value| value.nil? }
@ -204,12 +200,10 @@ class Vmfloaty
ok = true ok = true
modified_hash = {} modified_hash = {}
running_vms.each do |vm| running_vms.each do |vm|
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 FloatyLogger.error e
FloatyLogger.error e ok = false
ok = false
end
end end
if ok if ok
if modify_all if modify_all
@ -241,9 +235,7 @@ class Vmfloaty
c.option '--loglevel STRING', String, 'the log level to use (debug, info, error)' c.option '--loglevel STRING', String, 'the log level to use (debug, info, error)'
c.action do |args, options| c.action do |args, options|
verbose = options.verbose || config['verbose'] verbose = options.verbose || config['verbose']
if options.loglevel FloatyLogger.setlevel = options.loglevel if options.loglevel
FloatyLogger.setlevel = options.loglevel
end
service = Service.new(options, config) service = Service.new(options, config)
hostnames = args[0] hostnames = args[0]
@ -254,17 +246,17 @@ class Vmfloaty
successes = [] successes = []
if delete_all if delete_all
if service.type == "ABS" running_vms = if service.type == 'ABS'
# this is actually job_ids # this is actually job_ids
running_vms = service.list_active_job_ids(verbose, service.url, service.user) service.list_active_job_ids(verbose, service.url, service.user)
else else
running_vms = service.list_active(verbose) service.list_active(verbose)
end end
if running_vms.empty? if running_vms.empty?
if options.json if options.json
puts {}.to_json puts {}.to_json
else else
FloatyLogger.info "You have no running VMs." FloatyLogger.info 'You have no running VMs.'
end end
else else
confirmed = true confirmed = true
@ -328,7 +320,8 @@ class Vmfloaty
c.syntax = 'floaty snapshot hostname [options]' c.syntax = 'floaty snapshot hostname [options]'
c.summary = 'Takes a snapshot of a given vm' c.summary = 'Takes a snapshot of a given vm'
c.description = 'Will request a snapshot be taken of the given hostname in the pooler service. This command is known to take a while depending on how much load is on the pooler service.' c.description = 'Will request a snapshot be taken of the given hostname in the pooler service. This command is known to take a while depending on how much load is on the pooler service.'
c.example 'Takes a snapshot for a given host', 'floaty snapshot myvm.example.com --url http://vmpooler.example.com --token a9znth9dn01t416hrguu56ze37t790bl' c.example 'Takes a snapshot for a given host',
'floaty snapshot myvm.example.com --url http://vmpooler.example.com --token a9znth9dn01t416hrguu56ze37t790bl'
c.option '--verbose', 'Enables verbose output' c.option '--verbose', 'Enables verbose output'
c.option '--service STRING', String, 'Configured pooler service name' c.option '--service STRING', String, 'Configured pooler service name'
c.option '--url STRING', String, 'URL of pooler service' c.option '--url STRING', String, 'URL of pooler service'
@ -354,7 +347,8 @@ class Vmfloaty
c.syntax = 'floaty revert hostname snapshot [options]' c.syntax = 'floaty revert hostname snapshot [options]'
c.summary = 'Reverts a vm to a specified snapshot' c.summary = 'Reverts a vm to a specified snapshot'
c.description = 'Given a snapshot SHA, vmfloaty will request a revert to the pooler service to go back to a previous snapshot.' c.description = 'Given a snapshot SHA, vmfloaty will request a revert to the pooler service to go back to a previous snapshot.'
c.example 'Reverts to a snapshot for a given host', 'floaty revert myvm.example.com n4eb4kdtp7rwv4x158366vd9jhac8btq --url http://vmpooler.example.com --token a9znth9dn01t416hrguu56ze37t790bl' c.example 'Reverts to a snapshot for a given host',
'floaty revert myvm.example.com n4eb4kdtp7rwv4x158366vd9jhac8btq --url http://vmpooler.example.com --token a9znth9dn01t416hrguu56ze37t790bl'
c.option '--verbose', 'Enables verbose output' c.option '--verbose', 'Enables verbose output'
c.option '--service STRING', String, 'Configured pooler service name' c.option '--service STRING', String, 'Configured pooler service name'
c.option '--url STRING', String, 'URL of pooler service' c.option '--url STRING', String, 'URL of pooler service'
@ -366,7 +360,9 @@ class Vmfloaty
hostname = args[0] hostname = args[0]
snapshot_sha = args[1] || options.snapshot snapshot_sha = args[1] || options.snapshot
FloatyLogger.info "Two snapshot arguments were given....using snapshot #{snapshot_sha}" if args[1] && options.snapshot if args[1] && options.snapshot
FloatyLogger.info "Two snapshot arguments were given....using snapshot #{snapshot_sha}"
end
begin begin
revert_req = service.revert(verbose, hostname, snapshot_sha) revert_req = service.revert(verbose, hostname, snapshot_sha)
@ -391,9 +387,7 @@ class Vmfloaty
c.option '--loglevel STRING', String, 'the log level to use (debug, info, error)' c.option '--loglevel STRING', String, 'the log level to use (debug, info, error)'
c.action do |_, options| c.action do |_, options|
verbose = options.verbose || config['verbose'] verbose = options.verbose || config['verbose']
if options.loglevel FloatyLogger.setlevel = options.loglevel if options.loglevel
FloatyLogger.setlevel = options.loglevel
end
service = Service.new(options, config) service = Service.new(options, config)
if options.json if options.json
pp service.status(verbose) pp service.status(verbose)
@ -527,7 +521,7 @@ class Vmfloaty
c.example 'Print a list of the valid service types', 'floaty service types' c.example 'Print a list of the valid service types', 'floaty service types'
c.example 'Print a sample config file with multiple services', 'floaty service examples' c.example 'Print a sample config file with multiple services', 'floaty service examples'
c.example 'list vms from the service named "nspooler-prod"', 'floaty list --service nspooler-prod' c.example 'list vms from the service named "nspooler-prod"', 'floaty list --service nspooler-prod'
c.action do |args, options| c.action do |args, _options|
action = args.first action = args.first
example_config = Utils.strip_heredoc(<<-CONFIG) example_config = Utils.strip_heredoc(<<-CONFIG)

View file

@ -53,10 +53,10 @@ class ABS
def self.list_active(verbose, url, _token, user) def self.list_active(verbose, url, _token, user)
hosts = [] hosts = []
get_active_requests(verbose, url, user).each do |req_hash| get_active_requests(verbose, url, user).each do |req_hash|
if req_hash.key?('allocated_resources') next unless req_hash.key?('allocated_resources')
req_hash['allocated_resources'].each do |onehost|
hosts.push(onehost['hostname']) req_hash['allocated_resources'].each do |onehost|
end hosts.push(onehost['hostname'])
end end
end end
@ -116,7 +116,7 @@ class ABS
ret_status = {} ret_status = {}
hosts.each do |host| hosts.each do |host|
ret_status[host] = { ret_status[host] = {
'ok' => false, 'ok' => false
} }
end end
@ -132,7 +132,7 @@ class ABS
if hosts.include? vm_name['hostname'] if hosts.include? vm_name['hostname']
if all_job_resources_accounted_for(req_hash['allocated_resources'], hosts) if all_job_resources_accounted_for(req_hash['allocated_resources'], hosts)
ret_status[vm_name['hostname']] = { ret_status[vm_name['hostname']] = {
'ok' => true, 'ok' => true
} }
jobs_to_delete.push(req_hash) jobs_to_delete.push(req_hash)
else else
@ -147,7 +147,7 @@ class ABS
jobs_to_delete.each do |job| jobs_to_delete.each do |job|
req_obj = { req_obj = {
'job_id' => job['request']['job']['id'], 'job_id' => job['request']['job']['id'],
'hosts' => job['allocated_resources'], 'hosts' => job['allocated_resources']
} }
FloatyLogger.info "Deleting #{req_obj}" if verbose FloatyLogger.info "Deleting #{req_obj}" if verbose
@ -172,11 +172,11 @@ class ABS
res_body = JSON.parse(res.body) res_body = JSON.parse(res.body)
if res_body.key?('vmpooler_platforms') if res_body.key?('vmpooler_platforms')
os_list << '*** VMPOOLER Pools ***' os_list << '*** VMPOOLER Pools ***'
if res_body['vmpooler_platforms'].is_a?(String) os_list += if res_body['vmpooler_platforms'].is_a?(String)
os_list += JSON.parse(res_body['vmpooler_platforms']) # legacy ABS had another JSON string always-be-scheduling/pull/306 JSON.parse(res_body['vmpooler_platforms']) # legacy ABS had another JSON string always-be-scheduling/pull/306
else else
os_list += res_body['vmpooler_platforms'] res_body['vmpooler_platforms']
end end
end end
end end
@ -200,11 +200,11 @@ class ABS
if res_body.key?('nspooler_platforms') if res_body.key?('nspooler_platforms')
os_list << '' os_list << ''
os_list << '*** NSPOOLER Pools ***' os_list << '*** NSPOOLER Pools ***'
if res_body['nspooler_platforms'].is_a?(String) os_list += if res_body['nspooler_platforms'].is_a?(String)
os_list += JSON.parse(res_body['nspooler_platforms']) # legacy ABS had another JSON string always-be-scheduling/pull/306 JSON.parse(res_body['nspooler_platforms']) # legacy ABS had another JSON string always-be-scheduling/pull/306
else else
os_list += res_body['nspooler_platforms'] res_body['nspooler_platforms']
end end
end end
end end
@ -214,11 +214,11 @@ class ABS
if res_body.key?('aws_platforms') if res_body.key?('aws_platforms')
os_list << '' os_list << ''
os_list << '*** AWS Pools ***' os_list << '*** AWS Pools ***'
if res_body['aws_platforms'].is_a?(String) os_list += if res_body['aws_platforms'].is_a?(String)
os_list += JSON.parse(res_body['aws_platforms']) # legacy ABS had another JSON string always-be-scheduling/pull/306 JSON.parse(res_body['aws_platforms']) # legacy ABS had another JSON string always-be-scheduling/pull/306
else else
os_list += res_body['aws_platforms'] res_body['aws_platforms']
end end
end end
end end
@ -248,20 +248,20 @@ class ABS
conn = Http.get_conn(verbose, supported_abs_url(url)) conn = Http.get_conn(verbose, supported_abs_url(url))
conn.headers['X-AUTH-TOKEN'] = token if token conn.headers['X-AUTH-TOKEN'] = token if token
if continue.nil? saved_job_id = if continue.nil?
saved_job_id = user + "-" + DateTime.now.strftime('%Q') "#{user}-#{DateTime.now.strftime('%Q')}"
else else
saved_job_id = continue continue
end end
req_obj = { req_obj = {
:resources => os_types, resources: os_types,
:job => { job: {
:id => saved_job_id, id: saved_job_id,
:tags => { tags: {
:user => user, user: user
}, }
}, }
} }
if config['vmpooler_fallback'] # optional and not available as cli flag if config['vmpooler_fallback'] # optional and not available as cli flag
@ -271,11 +271,12 @@ class ABS
end end
if config['priority'] if config['priority']
req_obj[:priority] = if config['priority'] == 'high' req_obj[:priority] = case config['priority']
when 'high'
1 1
elsif config['priority'] == 'medium' when 'medium'
2 2
elsif config['priority'] == 'low' when 'low'
3 3
else else
config['priority'].to_i config['priority'].to_i
@ -291,14 +292,12 @@ class ABS
retries = 360 retries = 360
status = validate_queue_status_response(res.status, res.body, "Initial request", verbose) status = validate_queue_status_response(res.status, res.body, 'Initial request', verbose)
begin begin
(1..retries).each do |i| (1..retries).each do |i|
res_body = check_queue(conn, saved_job_id, req_obj, verbose) res_body = check_queue(conn, saved_job_id, req_obj, verbose)
if res_body && res_body.is_a?(Array) # when we get a response with hostnames return translated(res_body, saved_job_id) if res_body.is_a?(Array) # when we get a response with hostnames
return translated(res_body, saved_job_id)
end
sleep_seconds = 10 if i >= 10 sleep_seconds = 10 if i >= 10
sleep_seconds = i if i < 10 sleep_seconds = i if i < 10
@ -317,10 +316,10 @@ class ABS
# We should fix the ABS API to be more like the vmpooler or nspooler api, but for now # We should fix the ABS API to be more like the vmpooler or nspooler api, but for now
# #
def self.translated(res_body, job_id) def self.translated(res_body, job_id)
vmpooler_formatted_body = {'job_id' => job_id} vmpooler_formatted_body = { 'job_id' => job_id }
res_body.each do |host| res_body.each do |host|
if vmpooler_formatted_body[host['type']] && vmpooler_formatted_body[host['type']]['hostname'].class == Array if vmpooler_formatted_body[host['type']] && vmpooler_formatted_body[host['type']]['hostname'].instance_of?(Array)
vmpooler_formatted_body[host['type']]['hostname'] << host['hostname'] vmpooler_formatted_body[host['type']]['hostname'] << host['hostname']
else else
vmpooler_formatted_body[host['type']] = { 'hostname' => [host['hostname']] } vmpooler_formatted_body[host['type']] = { 'hostname' => [host['hostname']] }
@ -331,9 +330,9 @@ class ABS
vmpooler_formatted_body vmpooler_formatted_body
end end
def self.check_queue(conn, job_id, req_obj, verbose) def self.check_queue(conn, _job_id, req_obj, verbose)
res = conn.post 'request', req_obj.to_json res = conn.post 'request', req_obj.to_json
status = validate_queue_status_response(res.status, res.body, "Check queue request", verbose) status = validate_queue_status_response(res.status, res.body, 'Check queue request', verbose)
unless res.body.empty? || !valid_json?(res.body) unless res.body.empty? || !valid_json?(res.body)
res_body = JSON.parse(res.body) res_body = JSON.parse(res.body)
return res_body return res_body
@ -353,7 +352,7 @@ class ABS
res.body == 'OK' res.body == 'OK'
end end
def self.summary(verbose, url) def self.summary(_verbose, _url)
raise NoMethodError, 'summary is not defined for ABS' raise NoMethodError, 'summary is not defined for ABS'
end end
@ -405,17 +404,17 @@ class ABS
def self.valid_json?(json) def self.valid_json?(json)
JSON.parse(json) JSON.parse(json)
return true true
rescue TypeError, JSON::ParserError => e rescue TypeError, JSON::ParserError => e
return false false
end end
# when missing, adds the required api/v2 in the url # when missing, adds the required api/v2 in the url
def self.supported_abs_url(url) def self.supported_abs_url(url)
expected_ending = "api/v2" expected_ending = 'api/v2'
if !url.include?(expected_ending) unless url.include?(expected_ending)
# add a slash if missing # add a slash if missing
expected_ending = "/#{expected_ending}" if url[-1] != "/" expected_ending = "/#{expected_ending}" if url[-1] != '/'
url = "#{url}#{expected_ending}" url = "#{url}#{expected_ending}"
end end
url url

View file

@ -21,13 +21,11 @@ class Http
url = "https://#{url}" unless url?(url) url = "https://#{url}" unless url?(url)
conn = Faraday.new(:url => url, :ssl => { :verify => false }) do |faraday| Faraday.new(url: url, ssl: { verify: false }) do |faraday|
faraday.request :url_encoded faraday.request :url_encoded
faraday.response :logger if verbose faraday.response :logger if verbose
faraday.adapter Faraday.default_adapter faraday.adapter Faraday.default_adapter
end end
conn
end end
def self.get_conn_with_auth(verbose, url, user, password) def self.get_conn_with_auth(verbose, url, user, password)
@ -37,13 +35,11 @@ class Http
url = "https://#{url}" unless url?(url) url = "https://#{url}" unless url?(url)
conn = Faraday.new(:url => url, :ssl => { :verify => false }) do |faraday| Faraday.new(url: url, ssl: { verify: false }) do |faraday|
faraday.request :url_encoded faraday.request :url_encoded
faraday.request :basic_auth, user, password faraday.request :basic_auth, user, password
faraday.response :logger if verbose faraday.response :logger if verbose
faraday.adapter Faraday.default_adapter faraday.adapter Faraday.default_adapter
end end
conn
end end
end end

View file

@ -1,3 +1,5 @@
# frozen_string_literal: true
require 'logger' require 'logger'
class FloatyLogger < ::Logger class FloatyLogger < ::Logger
@ -19,22 +21,23 @@ class FloatyLogger < ::Logger
def self.setlevel=(level) def self.setlevel=(level)
level = level.downcase level = level.downcase
if level == "debug" case level
self.logger.level = ::Logger::DEBUG when 'debug'
elsif level == "info" logger.level = ::Logger::DEBUG
self.logger.level = ::Logger::INFO when 'info'
elsif level == "error" logger.level = ::Logger::INFO
self.logger.level = ::Logger::ERROR when 'error'
logger.level = ::Logger::ERROR
else else
error("set loglevel to debug, info or error") error('set loglevel to debug, info or error')
end end
end end
def initialize def initialize
super(STDERR) super($stderr)
self.level = ::Logger::INFO self.level = ::Logger::INFO
self.formatter = proc do |severity, datetime, progname, msg| self.formatter = proc do |_severity, _datetime, _progname, msg|
"#{msg}\n" "#{msg}\n"
end end
end end
end end

View file

@ -22,7 +22,7 @@ class NonstandardPooler
status['reserved_hosts'] || [] status['reserved_hosts'] || []
end end
def self.retrieve(verbose, os_type, token, url, _user, _options, ondemand = nil, _continue = nil) def self.retrieve(verbose, os_type, token, url, _user, _options, _ondemand = nil, _continue = nil)
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
@ -46,7 +46,8 @@ class NonstandardPooler
raise TokenError, 'Token provided was nil; Request cannot be made to modify VM' if token.nil? raise TokenError, 'Token provided was nil; Request cannot be made to modify VM' if token.nil?
modify_hash.each do |key, _value| modify_hash.each do |key, _value|
raise ModifyError, "Configured service type does not support modification of #{key}" unless %i[reason reserved_for_reason].include? key raise ModifyError, "Configured service type does not support modification of #{key}" unless %i[reason
reserved_for_reason].include? key
end end
if modify_hash[:reason] if modify_hash[:reason]

View file

@ -12,13 +12,11 @@ class Pooler
response = conn.get 'vm' response = conn.get 'vm'
response_body = JSON.parse(response.body) response_body = JSON.parse(response.body)
hosts = if os_filter if os_filter
response_body.select { |i| i[/#{os_filter}/] } response_body.select { |i| i[/#{os_filter}/] }
else else
response_body response_body
end end
hosts
end end
def self.list_active(verbose, url, token, _user) def self.list_active(verbose, url, token, _user)
@ -50,7 +48,10 @@ class Pooler
elsif response.status == 403 elsif response.status == 403
raise "HTTP #{response.status}: Failed to obtain VMs from the pooler at #{url}/vm/#{os_string}. Request exceeds the configured per pool maximum. #{res_body}" raise "HTTP #{response.status}: Failed to obtain VMs from the pooler at #{url}/vm/#{os_string}. Request exceeds the configured per pool maximum. #{res_body}"
else else
raise "HTTP #{response.status}: Failed to obtain VMs from the pooler at #{url}/vm/#{os_string}. #{res_body}" unless ondemand unless ondemand
raise "HTTP #{response.status}: Failed to obtain VMs from the pooler at #{url}/vm/#{os_string}. #{res_body}"
end
raise "HTTP #{response.status}: Failed to obtain VMs from the pooler at #{url}/ondemandvm/#{os_string}. #{res_body}" raise "HTTP #{response.status}: Failed to obtain VMs from the pooler at #{url}/ondemandvm/#{os_string}. #{res_body}"
end end
end end
@ -63,7 +64,7 @@ class Pooler
FloatyLogger.info "waiting for request #{request_id} to be fulfilled" FloatyLogger.info "waiting for request #{request_id} to be fulfilled"
sleep 5 sleep 5
end end
FloatyLogger.info "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
@ -84,8 +85,9 @@ class Pooler
def self.modify(verbose, url, hostname, token, modify_hash) def self.modify(verbose, url, hostname, token, modify_hash)
raise TokenError, 'Token provided was nil. Request cannot be made to modify vm' if token.nil? raise TokenError, 'Token provided was nil. Request cannot be made to modify vm' if token.nil?
modify_hash.keys.each do |key| modify_hash.each_key do |key|
raise ModifyError, "Configured service type does not support modification of #{key}." unless %i[tags lifetime disk].include? key raise ModifyError, "Configured service type does not support modification of #{key}." unless %i[tags lifetime
disk].include? key
end end
conn = Http.get_conn(verbose, url) conn = Http.get_conn(verbose, url)
@ -120,8 +122,7 @@ class Pooler
response = conn.post "vm/#{hostname}/disk/#{disk}" response = conn.post "vm/#{hostname}/disk/#{disk}"
res_body = JSON.parse(response.body) JSON.parse(response.body)
res_body
end end
def self.delete(verbose, url, hosts, token, _user) def self.delete(verbose, url, hosts, token, _user)
@ -146,25 +147,21 @@ class Pooler
conn = Http.get_conn(verbose, url) conn = Http.get_conn(verbose, url)
response = conn.get '/status' response = conn.get '/status'
res_body = JSON.parse(response.body) JSON.parse(response.body)
res_body
end end
def self.summary(verbose, url) def self.summary(verbose, url)
conn = Http.get_conn(verbose, url) conn = Http.get_conn(verbose, url)
response = conn.get '/summary' response = conn.get '/summary'
res_body = JSON.parse(response.body) JSON.parse(response.body)
res_body
end end
def self.query(verbose, url, hostname) def self.query(verbose, url, hostname)
conn = Http.get_conn(verbose, url) conn = Http.get_conn(verbose, url)
response = conn.get "vm/#{hostname}" response = conn.get "vm/#{hostname}"
res_body = JSON.parse(response.body) JSON.parse(response.body)
res_body
end end
def self.snapshot(verbose, url, hostname, token) def self.snapshot(verbose, url, hostname, token)
@ -174,8 +171,7 @@ class Pooler
conn.headers['X-AUTH-TOKEN'] = token conn.headers['X-AUTH-TOKEN'] = token
response = conn.post "vm/#{hostname}/snapshot" response = conn.post "vm/#{hostname}/snapshot"
res_body = JSON.parse(response.body) JSON.parse(response.body)
res_body
end end
def self.revert(verbose, url, hostname, token, snapshot_sha) def self.revert(verbose, url, hostname, token, snapshot_sha)
@ -187,7 +183,6 @@ class Pooler
raise "Snapshot SHA provided was nil, could not revert #{hostname}" if snapshot_sha.nil? raise "Snapshot SHA provided was nil, could not revert #{hostname}" if snapshot_sha.nil?
response = conn.post "vm/#{hostname}/snapshot/#{snapshot_sha}" response = conn.post "vm/#{hostname}/snapshot/#{snapshot_sha}"
res_body = JSON.parse(response.body) JSON.parse(response.body)
res_body
end end
end end

View file

@ -39,7 +39,7 @@ class Service
def user def user
unless @config['user'] unless @config['user']
FloatyLogger.info "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']
end end
@ -140,8 +140,8 @@ class Service
# some methods do not exist for ABS, and if possible should target the Pooler service # some methods do not exist for ABS, and if possible should target the Pooler service
def maybe_use_vmpooler def maybe_use_vmpooler
if @service_object == ABS # this is not an instance if @service_object == ABS # this is not an instance
if !self.silent unless silent
FloatyLogger.info "The service in use is ABS, but the requested method should run against vmpooler directly, using fallback_vmpooler config from ~/.vmfloaty.yml" FloatyLogger.info 'The service in use is ABS, but the requested method should run against vmpooler directly, using fallback_vmpooler config from ~/.vmfloaty.yml'
self.silent = true self.silent = true
end end

View file

@ -39,7 +39,10 @@ class Utils
# "engine"=>"vmpooler" # "engine"=>"vmpooler"
# } # }
raise ArgumentError, "Bad GET response passed to format_hosts: #{response_body.to_json}" unless response_body.delete('ok') unless response_body.delete('ok')
raise ArgumentError,
"Bad GET response passed to format_hosts: #{response_body.to_json}"
end
# vmpooler reports the domain separately from the hostname # vmpooler reports the domain separately from the hostname
domain = response_body.delete('domain') domain = response_body.delete('domain')
@ -50,7 +53,7 @@ class Utils
abs_job_id = response_body.delete('job_id') abs_job_id = response_body.delete('job_id')
result['job_id'] = abs_job_id unless abs_job_id.nil? result['job_id'] = abs_job_id unless abs_job_id.nil?
filtered_response_body = response_body.reject { |key, _| key == 'request_id' || key == 'ready' } filtered_response_body = response_body.reject { |key, _| %w[request_id ready].include?(key) }
filtered_response_body.each do |os, value| filtered_response_body.each do |os, value|
hostnames = Array(value['hostname']) hostnames = Array(value['hostname'])
hostnames.map! { |host| "#{host}.#{domain}" } if domain hostnames.map! { |host| "#{host}.#{domain}" } if domain
@ -106,7 +109,7 @@ class Utils
def self.pretty_print_hosts(verbose, service, hostnames = [], print_to_stderr = false, indent = 0) def self.pretty_print_hosts(verbose, service, hostnames = [], print_to_stderr = false, indent = 0)
output_target = print_to_stderr ? $stderr : $stdout output_target = print_to_stderr ? $stderr : $stdout
fetched_data = self.get_host_data(verbose, service, hostnames) fetched_data = get_host_data(verbose, service, hostnames)
fetched_data.each do |hostname, host_data| fetched_data.each do |hostname, host_data|
case service.type case service.type
when 'ABS' when 'ABS'
@ -116,13 +119,14 @@ class Utils
output_target.puts "- [JobID:#{host_data['request']['job']['id']}] <#{host_data['state']}>" output_target.puts "- [JobID:#{host_data['request']['job']['id']}] <#{host_data['state']}>"
host_data['allocated_resources'].each do |allocated_resources, _i| host_data['allocated_resources'].each do |allocated_resources, _i|
if (allocated_resources['engine'] == "vmpooler" || allocated_resources['engine'] == 'ondemand') && service.config["vmpooler_fallback"] if (allocated_resources['engine'] == 'vmpooler' || allocated_resources['engine'] == 'ondemand') && service.config['vmpooler_fallback']
vmpooler_service = service.clone vmpooler_service = service.clone
vmpooler_service.silent = true vmpooler_service.silent = true
vmpooler_service.maybe_use_vmpooler vmpooler_service.maybe_use_vmpooler
self.pretty_print_hosts(verbose, vmpooler_service, allocated_resources['hostname'].split('.')[0], print_to_stderr, indent+2) pretty_print_hosts(verbose, vmpooler_service, allocated_resources['hostname'].split('.')[0],
print_to_stderr, indent + 2)
else else
#TODO we could add more specific metadata for the other services, nspooler and aws # TODO: we could add more specific metadata for the other services, nspooler and aws
output_target.puts " - #{allocated_resources['hostname']} (#{allocated_resources['type']})" output_target.puts " - #{allocated_resources['hostname']} (#{allocated_resources['type']})"
end end
end end
@ -132,7 +136,7 @@ class Utils
duration = "#{host_data['running']}/#{host_data['lifetime']} hours" duration = "#{host_data['running']}/#{host_data['lifetime']} hours"
metadata = [host_data['state'], host_data['template'], duration, *tag_pairs] metadata = [host_data['state'], host_data['template'], duration, *tag_pairs]
message = "- #{hostname}.#{host_data['domain']} (#{metadata.join(', ')})".gsub(/^/, ' ' * indent) message = "- #{hostname}.#{host_data['domain']} (#{metadata.join(', ')})".gsub(/^/, ' ' * indent)
if host_data['state'] && host_data['state'] == "destroyed" if host_data['state'] && host_data['state'] == 'destroyed'
output_target.puts message.colorize(:red) output_target.puts message.colorize(:red)
else else
output_target.puts message output_target.puts message
@ -153,30 +157,26 @@ class Utils
result = {} result = {}
hostnames = [hostnames] unless hostnames.is_a? Array hostnames = [hostnames] unless hostnames.is_a? Array
hostnames.each do |hostname| hostnames.each do |hostname|
begin response = service.query(verbose, hostname)
response = service.query(verbose, hostname) host_data = response[hostname]
host_data = response[hostname] if block_given?
if block_given? yield host_data result
yield host_data result else
case service.type
when 'ABS'
# For ABS, 'hostname' variable is the jobID
result[hostname] = host_data if host_data['state'] == 'allocated' || host_data['state'] == 'filled'
when 'Pooler'
result[hostname] = host_data
when 'NonstandardPooler'
result[hostname] = host_data
else else
case service.type raise "Invalid service type #{service.type}"
when 'ABS'
# For ABS, 'hostname' variable is the jobID
if host_data['state'] == 'allocated' || host_data['state'] == 'filled'
result[hostname] = host_data
end
when 'Pooler'
result[hostname] = host_data
when 'NonstandardPooler'
result[hostname] = host_data
else
raise "Invalid service type #{service.type}"
end
end end
rescue StandardError => e
FloatyLogger.error("Something went wrong while trying to gather information on #{hostname}:")
FloatyLogger.error(e)
end end
rescue StandardError => e
FloatyLogger.error("Something went wrong while trying to gather information on #{hostname}:")
FloatyLogger.error(e)
end end
result result
end end
@ -192,16 +192,14 @@ class Utils
width = pools.keys.map(&:length).max width = pools.keys.map(&:length).max
pools.each do |name, pool| pools.each do |name, pool|
begin max = pool['max']
max = pool['max'] ready = pool['ready']
ready = pool['ready'] pending = pool['pending']
pending = pool['pending'] missing = max - ready - pending
missing = max - ready - pending 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 FloatyLogger.error "#{name.ljust(width)} #{e.red}"
FloatyLogger.error "#{name.ljust(width)} #{e.red}"
end
end end
puts message.colorize(status_response['status']['ok'] ? :default : :red) puts message.colorize(status_response['status']['ok'] ? :default : :red)
when 'NonstandardPooler' when 'NonstandardPooler'
@ -211,16 +209,14 @@ class Utils
width = pools.keys.map(&:length).max width = pools.keys.map(&:length).max
pools.each do |name, pool| pools.each do |name, pool|
begin max = pool['total_hosts']
max = pool['total_hosts'] ready = pool['available_hosts']
ready = pool['available_hosts'] pending = pool['pending'] || 0 # not available for nspooler
pending = pool['pending'] || 0 # not available for nspooler missing = max - ready - pending
missing = max - ready - pending 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 FloatyLogger.error "#{name.ljust(width)} #{e.red}"
FloatyLogger.error "#{name.ljust(width)} #{e.red}"
end
end end
when 'ABS' when 'ABS'
FloatyLogger.error 'ABS Not OK' unless status_response FloatyLogger.error 'ABS Not OK' unless status_response
@ -256,11 +252,11 @@ class Utils
def self.get_service_config(config, options) def self.get_service_config(config, options)
# The top-level url, user, and token values in the config file are treated as defaults # The top-level url, user, and token values in the config file are treated as defaults
service_config = { service_config = {
'url' => config['url'], 'url' => config['url'],
'user' => config['user'], 'user' => config['user'],
'token' => config['token'], 'token' => config['token'],
'vmpooler_fallback' => config['vmpooler_fallback'], 'vmpooler_fallback' => config['vmpooler_fallback'],
'type' => config['type'] || 'vmpooler', 'type' => config['type'] || 'vmpooler'
} }
if config['services'] if config['services']
@ -271,7 +267,10 @@ class Utils
service_config.merge! values service_config.merge! values
else else
# If the user provided a service name at the command line, use that service if posible, or fail # If the user provided a service name at the command line, use that service if posible, or fail
raise ArgumentError, "Could not find a configured service named '#{options.service}' in ~/.vmfloaty.yml" unless config['services'][options.service] unless config['services'][options.service]
raise ArgumentError,
"Could not find a configured service named '#{options.service}' in ~/.vmfloaty.yml"
end
# If the service is configured but some values are missing, use the top-level defaults to fill them in # If the service is configured but some values are missing, use the top-level defaults to fill them in
service_config.merge! config['services'][options.service] service_config.merge! config['services'][options.service]
@ -295,22 +294,22 @@ class Utils
config = Conf.read_config config = Conf.read_config
# The top-level url, user, and token values in the config file are treated as defaults # The top-level url, user, and token values in the config file are treated as defaults
service_config = { service_config = {
'url' => config['url'], 'url' => config['url'],
'user' => config['user'], 'user' => config['user'],
'token' => config['token'], 'token' => config['token'],
'type' => 'vmpooler', 'type' => 'vmpooler'
} }
# at a minimum, the url needs to be configured # at a minimum, the url needs to be configured
if config['services'] && config['services'][vmpooler_fallback] && config['services'][vmpooler_fallback]['url'] if config['services'] && config['services'][vmpooler_fallback] && config['services'][vmpooler_fallback]['url']
# If the service is configured but some values are missing, use the top-level defaults to fill them in # If the service is configured but some values are missing, use the top-level defaults to fill them in
service_config.merge! config['services'][vmpooler_fallback] service_config.merge! config['services'][vmpooler_fallback]
elsif vmpooler_fallback.nil?
raise ArgumentError,
"The abs service should have a key named 'vmpooler_fallback' in ~/.vmfloaty.yml with a value that points to a vmpooler service name use this format:\nservices:\n myabs:\n url: 'http://abs.com'\n user: 'superman'\n token: 'kryptonite'\n vmpooler_fallback: 'myvmpooler'\n myvmpooler:\n url: 'http://vmpooler.com'\n user: 'superman'\n token: 'kryptonite'"
else else
if vmpooler_fallback.nil? raise ArgumentError,
raise ArgumentError, "The abs service should have a key named 'vmpooler_fallback' in ~/.vmfloaty.yml with a value that points to a vmpooler service name use this format:\nservices:\n myabs:\n url: 'http://abs.com'\n user: 'superman'\n token: 'kryptonite'\n vmpooler_fallback: 'myvmpooler'\n myvmpooler:\n url: 'http://vmpooler.com'\n user: 'superman'\n token: 'kryptonite'" "Could not find a configured service named '#{vmpooler_fallback}' in ~/.vmfloaty.yml use this format:\nservices:\n #{vmpooler_fallback}:\n url: 'http://vmpooler.com'\n user: 'superman'\n token: 'kryptonite'"
else
raise ArgumentError, "Could not find a configured service named '#{vmpooler_fallback}' in ~/.vmfloaty.yml use this format:\nservices:\n #{vmpooler_fallback}:\n url: 'http://vmpooler.com'\n user: 'superman'\n token: 'kryptonite'"
end
end end
service_config service_config

View file

@ -3,4 +3,3 @@
class Vmfloaty class Vmfloaty
VERSION = '1.3.0' VERSION = '1.3.0'
end end

View file

@ -4,9 +4,9 @@ require 'simplecov'
require 'coveralls' require 'coveralls'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([ SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([
SimpleCov::Formatter::HTMLFormatter, SimpleCov::Formatter::HTMLFormatter,
Coveralls::SimpleCov::Formatter Coveralls::SimpleCov::Formatter
]) ])
SimpleCov.start do SimpleCov.start do
add_filter %r{^/spec/} add_filter %r{^/spec/}
end end

View file

@ -16,7 +16,7 @@ describe Pooler do
it 'returns a token from abs' do it 'returns a token from abs' do
stub_request(:post, 'https://first.last:password@abs.example.com/api/v2/token') stub_request(:post, 'https://first.last:password@abs.example.com/api/v2/token')
.to_return(:status => 200, :body => @get_token_response, :headers => {}) .to_return(status: 200, body: @get_token_response, headers: {})
token = Auth.get_token(false, @abs_url, 'first.last', 'password') token = Auth.get_token(false, @abs_url, 'first.last', 'password')
expect(token).to eq @token expect(token).to eq @token
@ -24,7 +24,7 @@ describe Pooler do
it 'raises a token error if something goes wrong' do it 'raises a token error if something goes wrong' do
stub_request(:post, 'https://first.last:password@abs.example.com/api/v2/token') stub_request(:post, 'https://first.last:password@abs.example.com/api/v2/token')
.to_return(:status => 500, :body => '{"ok":false}', :headers => {}) .to_return(status: 500, body: '{"ok":false}', headers: {})
expect { Auth.get_token(false, @abs_url, 'first.last', 'password') }.to raise_error(TokenError) expect { Auth.get_token(false, @abs_url, 'first.last', 'password') }.to raise_error(TokenError)
end end
@ -38,14 +38,15 @@ describe Pooler do
it 'deletes the specified token' do it 'deletes the specified token' do
stub_request(:delete, 'https://first.last:password@abs.example.com/api/v2/token/utpg2i2xswor6h8ttjhu3d47z53yy47y') stub_request(:delete, 'https://first.last:password@abs.example.com/api/v2/token/utpg2i2xswor6h8ttjhu3d47z53yy47y')
.to_return(:status => 200, :body => @delete_token_response, :headers => {}) .to_return(status: 200, body: @delete_token_response, headers: {})
expect(Auth.delete_token(false, @abs_url, 'first.last', 'password', @token)).to eq JSON.parse(@delete_token_response) expect(Auth.delete_token(false, @abs_url, 'first.last', 'password',
@token)).to eq JSON.parse(@delete_token_response)
end end
it 'raises a token error if something goes wrong' do it 'raises a token error if something goes wrong' do
stub_request(:delete, 'https://first.last:password@abs.example.com/api/v2/token/utpg2i2xswor6h8ttjhu3d47z53yy47y') stub_request(:delete, 'https://first.last:password@abs.example.com/api/v2/token/utpg2i2xswor6h8ttjhu3d47z53yy47y')
.to_return(:status => 500, :body => '{"ok":false}', :headers => {}) .to_return(status: 500, body: '{"ok":false}', headers: {})
expect { Auth.delete_token(false, @abs_url, 'first.last', 'password', @token) }.to raise_error(TokenError) expect { Auth.delete_token(false, @abs_url, 'first.last', 'password', @token) }.to raise_error(TokenError)
end end
@ -63,16 +64,16 @@ describe Pooler do
it 'checks the status of a token' do it 'checks the status of a token' do
stub_request(:get, "#{@abs_url}/token/utpg2i2xswor6h8ttjhu3d47z53yy47y") stub_request(:get, "#{@abs_url}/token/utpg2i2xswor6h8ttjhu3d47z53yy47y")
.with(:headers => { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3' }) .with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3' })
.to_return(:status => 200, :body => @token_status_response, :headers => {}) .to_return(status: 200, body: @token_status_response, headers: {})
expect(Auth.token_status(false, @abs_url, @token)).to eq JSON.parse(@token_status_response) expect(Auth.token_status(false, @abs_url, @token)).to eq JSON.parse(@token_status_response)
end end
it 'raises a token error if something goes wrong' do it 'raises a token error if something goes wrong' do
stub_request(:get, "#{@abs_url}/token/utpg2i2xswor6h8ttjhu3d47z53yy47y") stub_request(:get, "#{@abs_url}/token/utpg2i2xswor6h8ttjhu3d47z53yy47y")
.with(:headers => { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3' }) .with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3' })
.to_return(:status => 500, :body => '{"ok":false}', :headers => {}) .to_return(status: 500, body: '{"ok":false}', headers: {})
expect { Auth.token_status(false, @abs_url, @token) }.to raise_error(TokenError) expect { Auth.token_status(false, @abs_url, @token) }.to raise_error(TokenError)
end end

View file

@ -11,12 +11,12 @@ describe ABS do
describe '#list' do describe '#list' do
it 'skips empty platforms and lists aws' do it 'skips empty platforms and lists aws' do
stub_request(:get, "http://foo/api/v2/status/platforms/vmpooler"). stub_request(:get, 'http://foo/api/v2/status/platforms/vmpooler')
to_return(:status => 200, :body => "", :headers => {}) .to_return(status: 200, body: '', headers: {})
stub_request(:get, "http://foo/api/v2/status/platforms/ondemand_vmpooler"). stub_request(:get, 'http://foo/api/v2/status/platforms/ondemand_vmpooler')
to_return(:status => 200, :body => "", :headers => {}) .to_return(status: 200, body: '', headers: {})
stub_request(:get, "http://foo/api/v2/status/platforms/nspooler"). stub_request(:get, 'http://foo/api/v2/status/platforms/nspooler')
to_return(:status => 200, :body => "", :headers => {}) .to_return(status: 200, body: '', headers: {})
body = '{ body = '{
"aws_platforms": [ "aws_platforms": [
"amazon-6-x86_64", "amazon-6-x86_64",
@ -26,50 +26,55 @@ describe ABS do
"redhat-8-arm64" "redhat-8-arm64"
] ]
}' }'
stub_request(:get, "http://foo/api/v2/status/platforms/aws"). stub_request(:get, 'http://foo/api/v2/status/platforms/aws')
to_return(:status => 200, :body => body, :headers => {}) .to_return(status: 200, body: body, headers: {})
results = ABS.list(false, 'http://foo')
results = ABS.list(false, "http://foo") expect(results).to include('amazon-6-x86_64', 'amazon-7-x86_64', 'amazon-7-arm64', 'centos-7-x86-64-west',
'redhat-8-arm64')
expect(results).to include("amazon-6-x86_64", "amazon-7-x86_64", "amazon-7-arm64", "centos-7-x86-64-west", "redhat-8-arm64")
end end
it 'legacy JSON string, prior to PR 306' do it 'legacy JSON string, prior to PR 306' do
stub_request(:get, "http://foo/api/v2/status/platforms/vmpooler"). stub_request(:get, 'http://foo/api/v2/status/platforms/vmpooler')
to_return(:status => 200, :body => "", :headers => {}) .to_return(status: 200, body: '', headers: {})
stub_request(:get, "http://foo/api/v2/status/platforms/ondemand_vmpooler"). stub_request(:get, 'http://foo/api/v2/status/platforms/ondemand_vmpooler')
to_return(:status => 200, :body => "", :headers => {}) .to_return(status: 200, body: '', headers: {})
stub_request(:get, "http://foo/api/v2/status/platforms/nspooler"). stub_request(:get, 'http://foo/api/v2/status/platforms/nspooler')
to_return(:status => 200, :body => "", :headers => {}) .to_return(status: 200, body: '', headers: {})
body = '{ body = '{
"aws_platforms": "[\"amazon-6-x86_64\",\"amazon-7-x86_64\",\"amazon-7-arm64\",\"centos-7-x86-64-west\",\"redhat-8-arm64\"]" "aws_platforms": "[\"amazon-6-x86_64\",\"amazon-7-x86_64\",\"amazon-7-arm64\",\"centos-7-x86-64-west\",\"redhat-8-arm64\"]"
}' }'
stub_request(:get, "http://foo/api/v2/status/platforms/aws"). stub_request(:get, 'http://foo/api/v2/status/platforms/aws')
to_return(:status => 200, :body => body, :headers => {}) .to_return(status: 200, body: body, headers: {})
results = ABS.list(false, "http://foo") results = ABS.list(false, 'http://foo')
expect(results).to include("amazon-6-x86_64", "amazon-7-x86_64", "amazon-7-arm64", "centos-7-x86-64-west", "redhat-8-arm64") expect(results).to include('amazon-6-x86_64', 'amazon-7-x86_64', 'amazon-7-arm64', 'centos-7-x86-64-west',
'redhat-8-arm64')
end end
end end
describe '#format' do describe '#format' do
it 'returns an hash formatted like a vmpooler return, plus the job_id' do it 'returns an hash formatted like a vmpooler return, plus the job_id' do
job_id = "generated_by_floaty_12345" job_id = 'generated_by_floaty_12345'
abs_formatted_response = [ abs_formatted_response = [
{ 'hostname' => 'aaaaaaaaaaaaaaa.delivery.puppetlabs.net', 'type' => 'centos-7.2-x86_64', 'engine' => 'vmpooler' }, { 'hostname' => 'aaaaaaaaaaaaaaa.delivery.puppetlabs.net', 'type' => 'centos-7.2-x86_64',
{ 'hostname' => 'aaaaaaaaaaaaaab.delivery.puppetlabs.net', 'type' => 'centos-7.2-x86_64', 'engine' => 'vmpooler' }, 'engine' => 'vmpooler' },
{ 'hostname' => 'aaaaaaaaaaaaaac.delivery.puppetlabs.net', 'type' => 'ubuntu-7.2-x86_64', 'engine' => 'vmpooler' }, { 'hostname' => 'aaaaaaaaaaaaaab.delivery.puppetlabs.net', 'type' => 'centos-7.2-x86_64',
'engine' => 'vmpooler' },
{ 'hostname' => 'aaaaaaaaaaaaaac.delivery.puppetlabs.net', 'type' => 'ubuntu-7.2-x86_64',
'engine' => 'vmpooler' }
] ]
vmpooler_formatted_response = ABS.translated(abs_formatted_response, job_id) vmpooler_formatted_response = ABS.translated(abs_formatted_response, job_id)
vmpooler_formatted_compare = { vmpooler_formatted_compare = {
'centos-7.2-x86_64' => {}, 'centos-7.2-x86_64' => {},
'ubuntu-7.2-x86_64' => {}, 'ubuntu-7.2-x86_64' => {}
} }
vmpooler_formatted_compare['centos-7.2-x86_64']['hostname'] = ['aaaaaaaaaaaaaaa.delivery.puppetlabs.net', 'aaaaaaaaaaaaaab.delivery.puppetlabs.net'] vmpooler_formatted_compare['centos-7.2-x86_64']['hostname'] =
['aaaaaaaaaaaaaaa.delivery.puppetlabs.net', 'aaaaaaaaaaaaaab.delivery.puppetlabs.net']
vmpooler_formatted_compare['ubuntu-7.2-x86_64']['hostname'] = ['aaaaaaaaaaaaaac.delivery.puppetlabs.net'] vmpooler_formatted_compare['ubuntu-7.2-x86_64']['hostname'] = ['aaaaaaaaaaaaaac.delivery.puppetlabs.net']
vmpooler_formatted_compare['ok'] = true vmpooler_formatted_compare['ok'] = true
@ -86,22 +91,22 @@ describe ABS do
hosts = ['host1'] hosts = ['host1']
allocated_resources = [ allocated_resources = [
{ {
'hostname' => 'host1', 'hostname' => 'host1'
}, },
{ {
'hostname' => 'host2', 'hostname' => 'host2'
}, }
] ]
expect(ABS.all_job_resources_accounted_for(allocated_resources, hosts)).to eq(false) expect(ABS.all_job_resources_accounted_for(allocated_resources, hosts)).to eq(false)
hosts = ['host1', 'host2'] hosts = %w[host1 host2]
allocated_resources = [ allocated_resources = [
{ {
'hostname' => 'host1', 'hostname' => 'host1'
}, },
{ {
'hostname' => 'host2', 'hostname' => 'host2'
}, }
] ]
expect(ABS.all_job_resources_accounted_for(allocated_resources, hosts)).to eq(true) expect(ABS.all_job_resources_accounted_for(allocated_resources, hosts)).to eq(true)
end end
@ -126,16 +131,16 @@ describe ABS do
it 'will skip a line with a null value returned from abs' do it 'will skip a line with a null value returned from abs' do
stub_request(:get, 'https://abs.example.com/api/v2/status/queue') stub_request(:get, 'https://abs.example.com/api/v2/status/queue')
.to_return(:status => 200, :body => @active_requests_response, :headers => {}) .to_return(status: 200, body: @active_requests_response, headers: {})
ret = ABS.get_active_requests(false, @abs_url, @test_user) ret = ABS.get_active_requests(false, @abs_url, @test_user)
expect(ret[0]).to include( expect(ret[0]).to include(
'allocated_resources' => [{ 'allocated_resources' => [{
'hostname' => 'take-this.delivery.puppetlabs.net', 'hostname' => 'take-this.delivery.puppetlabs.net',
'type' => 'win-2012r2-x86_64', 'type' => 'win-2012r2-x86_64',
'engine' => 'vmpooler', 'engine' => 'vmpooler'
}], }]
) )
end end
end end
@ -147,7 +152,7 @@ describe ABS do
[ [
{ "state":"allocated", "last_processed":"2020-01-17 22:29:13 +0000", "allocated_resources":[{"hostname":"craggy-chord.delivery.puppetlabs.net", "type":"centos-7-x86_64", "engine":"vmpooler"}, {"hostname":"visible-revival.delivery.puppetlabs.net", "type":"centos-7-x86_64", "engine":"vmpooler"}], "audit_log":{"2020-01-17 22:28:45 +0000":"Allocated craggy-chord.delivery.puppetlabs.net, visible-revival.delivery.puppetlabs.net for job 1579300120799"}, "request":{"resources":{"centos-7-x86_64":2}, "job":{"id":"1579300120799", "tags":{"user":"test-user"}, "user":"test-user", "time-received":1579300120}, "priority":3}} { "state":"allocated", "last_processed":"2020-01-17 22:29:13 +0000", "allocated_resources":[{"hostname":"craggy-chord.delivery.puppetlabs.net", "type":"centos-7-x86_64", "engine":"vmpooler"}, {"hostname":"visible-revival.delivery.puppetlabs.net", "type":"centos-7-x86_64", "engine":"vmpooler"}], "audit_log":{"2020-01-17 22:28:45 +0000":"Allocated craggy-chord.delivery.puppetlabs.net, visible-revival.delivery.puppetlabs.net for job 1579300120799"}, "request":{"resources":{"centos-7-x86_64":2}, "job":{"id":"1579300120799", "tags":{"user":"test-user"}, "user":"test-user", "time-received":1579300120}, "priority":3}}
]' ]'
@return_request = { '{"job_id":"1579300120799","hosts":{"hostname":"craggy-chord.delivery.puppetlabs.net","type":"centos-7-x86_64","engine":"vmpooler"},{"hostname":"visible-revival.delivery.puppetlabs.net","type":"centos-7-x86_64","engine":"vmpooler"}}'=>true } @return_request = { '{"job_id":"1579300120799","hosts":{"hostname":"craggy-chord.delivery.puppetlabs.net","type":"centos-7-x86_64","engine":"vmpooler"},{"hostname":"visible-revival.delivery.puppetlabs.net","type":"centos-7-x86_64","engine":"vmpooler"}}' => true }
# rubocop:enable Layout/LineLength # rubocop:enable Layout/LineLength
@token = 'utpg2i2xswor6h8ttjhu3d47z53yy47y' @token = 'utpg2i2xswor6h8ttjhu3d47z53yy47y'
@test_user = 'test-user' @test_user = 'test-user'
@ -157,15 +162,15 @@ describe ABS do
it 'will delete the whole job' do it 'will delete the whole job' do
stub_request(:get, 'https://abs.example.com/api/v2/status/queue') stub_request(:get, 'https://abs.example.com/api/v2/status/queue')
.to_return(:status => 200, :body => @active_requests_response, :headers => {}) .to_return(status: 200, body: @active_requests_response, headers: {})
stub_request(:post, 'https://abs.example.com/api/v2/return') stub_request(:post, 'https://abs.example.com/api/v2/return')
.with(:body => @return_request) .with(body: @return_request)
.to_return(:status => 200, :body => 'OK', :headers => {}) .to_return(status: 200, body: 'OK', headers: {})
ret = ABS.delete(false, @abs_url, @hosts, @token, @test_user) ret = ABS.delete(false, @abs_url, @hosts, @token, @test_user)
expect(ret).to include( expect(ret).to include(
'craggy-chord.delivery.puppetlabs.net' => { 'ok'=>true }, 'visible-revival.delivery.puppetlabs.net' => { 'ok'=>true }, 'craggy-chord.delivery.puppetlabs.net' => { 'ok' => true }, 'visible-revival.delivery.puppetlabs.net' => { 'ok' => true }
) )
end end
end end

View file

@ -16,7 +16,7 @@ describe Pooler do
it 'returns a token from vmpooler' do it 'returns a token from vmpooler' do
stub_request(:post, 'https://first.last:password@vmpooler.example.com/token') stub_request(:post, 'https://first.last:password@vmpooler.example.com/token')
.to_return(:status => 200, :body => @get_token_response, :headers => {}) .to_return(status: 200, body: @get_token_response, headers: {})
token = Auth.get_token(false, @vmpooler_url, 'first.last', 'password') token = Auth.get_token(false, @vmpooler_url, 'first.last', 'password')
expect(token).to eq @token expect(token).to eq @token
@ -24,7 +24,7 @@ describe Pooler do
it 'raises a token error if something goes wrong' do it 'raises a token error if something goes wrong' do
stub_request(:post, 'https://first.last:password@vmpooler.example.com/token') stub_request(:post, 'https://first.last:password@vmpooler.example.com/token')
.to_return(:status => 500, :body => '{"ok":false}', :headers => {}) .to_return(status: 500, body: '{"ok":false}', headers: {})
expect { Auth.get_token(false, @vmpooler_url, 'first.last', 'password') }.to raise_error(TokenError) expect { Auth.get_token(false, @vmpooler_url, 'first.last', 'password') }.to raise_error(TokenError)
end end
@ -38,14 +38,15 @@ describe Pooler do
it 'deletes the specified token' do it 'deletes the specified token' do
stub_request(:delete, 'https://first.last:password@vmpooler.example.com/token/utpg2i2xswor6h8ttjhu3d47z53yy47y') stub_request(:delete, 'https://first.last:password@vmpooler.example.com/token/utpg2i2xswor6h8ttjhu3d47z53yy47y')
.to_return(:status => 200, :body => @delete_token_response, :headers => {}) .to_return(status: 200, body: @delete_token_response, headers: {})
expect(Auth.delete_token(false, @vmpooler_url, 'first.last', 'password', @token)).to eq JSON.parse(@delete_token_response) expect(Auth.delete_token(false, @vmpooler_url, 'first.last', 'password',
@token)).to eq JSON.parse(@delete_token_response)
end end
it 'raises a token error if something goes wrong' do it 'raises a token error if something goes wrong' do
stub_request(:delete, 'https://first.last:password@vmpooler.example.com/token/utpg2i2xswor6h8ttjhu3d47z53yy47y') stub_request(:delete, 'https://first.last:password@vmpooler.example.com/token/utpg2i2xswor6h8ttjhu3d47z53yy47y')
.to_return(:status => 500, :body => '{"ok":false}', :headers => {}) .to_return(status: 500, body: '{"ok":false}', headers: {})
expect { Auth.delete_token(false, @vmpooler_url, 'first.last', 'password', @token) }.to raise_error(TokenError) expect { Auth.delete_token(false, @vmpooler_url, 'first.last', 'password', @token) }.to raise_error(TokenError)
end end
@ -63,14 +64,14 @@ describe Pooler do
it 'checks the status of a token' do it 'checks the status of a token' do
stub_request(:get, "#{@vmpooler_url}/token/utpg2i2xswor6h8ttjhu3d47z53yy47y") stub_request(:get, "#{@vmpooler_url}/token/utpg2i2xswor6h8ttjhu3d47z53yy47y")
.to_return(:status => 200, :body => @token_status_response, :headers => {}) .to_return(status: 200, body: @token_status_response, headers: {})
expect(Auth.token_status(false, @vmpooler_url, @token)).to eq JSON.parse(@token_status_response) expect(Auth.token_status(false, @vmpooler_url, @token)).to eq JSON.parse(@token_status_response)
end end
it 'raises a token error if something goes wrong' do it 'raises a token error if something goes wrong' do
stub_request(:get, "#{@vmpooler_url}/token/utpg2i2xswor6h8ttjhu3d47z53yy47y") stub_request(:get, "#{@vmpooler_url}/token/utpg2i2xswor6h8ttjhu3d47z53yy47y")
.to_return(:status => 500, :body => '{"ok":false}', :headers => {}) .to_return(status: 500, body: '{"ok":false}', headers: {})
expect { Auth.token_status(false, @vmpooler_url, @token) }.to raise_error(TokenError) expect { Auth.token_status(false, @vmpooler_url, @token) }.to raise_error(TokenError)
end end

View file

@ -9,7 +9,7 @@ describe NonstandardPooler do
before :each do before :each do
@nspooler_url = 'https://nspooler.example.com' @nspooler_url = 'https://nspooler.example.com'
@auth_token_headers = { @auth_token_headers = {
'X-Auth-Token' => 'token-value', 'X-Auth-Token' => 'token-value'
} }
end end
@ -36,7 +36,7 @@ describe NonstandardPooler do
it 'returns an array with operating systems from the pooler' do it 'returns an array with operating systems from the pooler' do
stub_request(:get, "#{@nspooler_url}/status") stub_request(:get, "#{@nspooler_url}/status")
.to_return(:status => 200, :body => @status_response_body, :headers => {}) .to_return(status: 200, body: @status_response_body, headers: {})
list = NonstandardPooler.list(false, @nspooler_url, nil) list = NonstandardPooler.list(false, @nspooler_url, nil)
expect(list).to be_an_instance_of Array expect(list).to be_an_instance_of Array
@ -44,7 +44,7 @@ describe NonstandardPooler do
it 'filters operating systems based on the filter param' do it 'filters operating systems based on the filter param' do
stub_request(:get, "#{@nspooler_url}/status") stub_request(:get, "#{@nspooler_url}/status")
.to_return(:status => 200, :body => @status_response_body, :headers => {}) .to_return(status: 200, body: @status_response_body, headers: {})
list = NonstandardPooler.list(false, @nspooler_url, 'aix') list = NonstandardPooler.list(false, @nspooler_url, 'aix')
expect(list).to be_an_instance_of Array expect(list).to be_an_instance_of Array
@ -53,7 +53,7 @@ describe NonstandardPooler do
it 'returns nothing if the filter does not match' do it 'returns nothing if the filter does not match' do
stub_request(:get, "#{@nspooler_url}/status") stub_request(:get, "#{@nspooler_url}/status")
.to_return(:status => 199, :body => @status_response_body, :headers => {}) .to_return(status: 199, body: @status_response_body, headers: {})
list = NonstandardPooler.list(false, @nspooler_url, 'windows') list = NonstandardPooler.list(false, @nspooler_url, 'windows')
expect(list).to be_an_instance_of Array expect(list).to be_an_instance_of Array
@ -89,7 +89,7 @@ describe NonstandardPooler do
.and_return(JSON.parse(@token_status_body_active)) .and_return(JSON.parse(@token_status_body_active))
list = NonstandardPooler.list_active(false, @nspooler_url, 'token-value', 'user') list = NonstandardPooler.list_active(false, @nspooler_url, 'token-value', 'user')
expect(list).to eql ['sol10-9', 'sol10-11'] expect(list).to eql %w[sol10-9 sol10-11]
end end
end end
@ -121,17 +121,19 @@ describe NonstandardPooler do
it 'raises an AuthError if the token is invalid' do it 'raises an AuthError if the token is invalid' do
stub_request(:post, "#{@nspooler_url}/host/solaris-11-sparc") stub_request(:post, "#{@nspooler_url}/host/solaris-11-sparc")
.with(:headers => @auth_token_headers) .with(headers: @auth_token_headers)
.to_return(:status => 401, :body => '{"ok":false,"reason": "token: token-value does not exist"}', :headers => {}) .to_return(status: 401, body: '{"ok":false,"reason": "token: token-value does not exist"}', headers: {})
vm_hash = { 'solaris-11-sparc' => 1 } vm_hash = { 'solaris-11-sparc' => 1 }
expect { NonstandardPooler.retrieve(false, vm_hash, 'token-value', @nspooler_url, 'first.last', {}) }.to raise_error(AuthError) expect do
NonstandardPooler.retrieve(false, vm_hash, 'token-value', @nspooler_url, 'first.last', {})
end.to raise_error(AuthError)
end end
it 'retrieves a single vm with a token' do it 'retrieves a single vm with a token' do
stub_request(:post, "#{@nspooler_url}/host/solaris-11-sparc") stub_request(:post, "#{@nspooler_url}/host/solaris-11-sparc")
.with(:headers => @auth_token_headers) .with(headers: @auth_token_headers)
.to_return(:status => 200, :body => @retrieve_response_body_single, :headers => {}) .to_return(status: 200, body: @retrieve_response_body_single, headers: {})
vm_hash = { 'solaris-11-sparc' => 1 } vm_hash = { 'solaris-11-sparc' => 1 }
vm_req = NonstandardPooler.retrieve(false, vm_hash, 'token-value', @nspooler_url, 'first.last', {}) vm_req = NonstandardPooler.retrieve(false, vm_hash, 'token-value', @nspooler_url, 'first.last', {})
@ -142,15 +144,16 @@ describe NonstandardPooler do
it 'retrieves a multiple vms with a token' do it 'retrieves a multiple vms with a token' do
stub_request(:post, "#{@nspooler_url}/host/aix-7.1-power+solaris-10-sparc+solaris-10-sparc") stub_request(:post, "#{@nspooler_url}/host/aix-7.1-power+solaris-10-sparc+solaris-10-sparc")
.with(:headers => @auth_token_headers) .with(headers: @auth_token_headers)
.to_return(:status => 200, :body => @retrieve_response_body_many, :headers => {}) .to_return(status: 200, body: @retrieve_response_body_many, headers: {})
vm_hash = { 'aix-7.1-power' => 1, 'solaris-10-sparc' => 2 } vm_hash = { 'aix-7.1-power' => 1, 'solaris-10-sparc' => 2 }
vm_req = NonstandardPooler.retrieve(false, vm_hash, 'token-value', @nspooler_url, 'first.last', {}) vm_req = NonstandardPooler.retrieve(false, vm_hash, 'token-value', @nspooler_url, 'first.last', {})
expect(vm_req).to be_an_instance_of Hash expect(vm_req).to be_an_instance_of Hash
expect(vm_req['ok']).to equal true expect(vm_req['ok']).to equal true
expect(vm_req['solaris-10-sparc']['hostname']).to be_an_instance_of Array expect(vm_req['solaris-10-sparc']['hostname']).to be_an_instance_of Array
expect(vm_req['solaris-10-sparc']['hostname']).to eq ['sol10-9.delivery.puppetlabs.net', 'sol10-10.delivery.puppetlabs.net'] expect(vm_req['solaris-10-sparc']['hostname']).to eq ['sol10-9.delivery.puppetlabs.net',
'sol10-10.delivery.puppetlabs.net']
expect(vm_req['aix-7.1-power']['hostname']).to eq 'pe-aix-71-ci-acceptance.delivery.puppetlabs.net' expect(vm_req['aix-7.1-power']['hostname']).to eq 'pe-aix-71-ci-acceptance.delivery.puppetlabs.net'
end end
end end
@ -162,10 +165,10 @@ describe NonstandardPooler do
it 'raises an error if the user tries to modify an unsupported attribute' do it 'raises an error if the user tries to modify an unsupported attribute' do
stub_request(:put, 'https://nspooler.example.com/host/myfakehost') stub_request(:put, 'https://nspooler.example.com/host/myfakehost')
.with(:body => { '{}' => true }, .with(body: { '{}' => true },
:headers => @auth_token_headers) headers: @auth_token_headers)
.to_return(:status => 200, :body => '', :headers => {}) .to_return(status: 200, body: '', headers: {})
details = { :lifetime => 12 } details = { lifetime: 12 }
expect { NonstandardPooler.modify(false, @nspooler_url, 'myfakehost', 'token-value', details) } expect { NonstandardPooler.modify(false, @nspooler_url, 'myfakehost', 'token-value', details) }
.to raise_error(ModifyError) .to raise_error(ModifyError)
end end
@ -173,11 +176,11 @@ describe NonstandardPooler do
it 'modifies the reason of a vm' do it 'modifies the reason of a vm' do
modify_request_body = { '{"reserved_for_reason":"testing"}' => true } modify_request_body = { '{"reserved_for_reason":"testing"}' => true }
stub_request(:put, "#{@nspooler_url}/host/myfakehost") stub_request(:put, "#{@nspooler_url}/host/myfakehost")
.with(:body => modify_request_body, .with(body: modify_request_body,
:headers => @auth_token_headers) headers: @auth_token_headers)
.to_return(:status => 200, :body => '{"ok": true}', :headers => {}) .to_return(status: 200, body: '{"ok": true}', headers: {})
modify_hash = { :reason => 'testing' } modify_hash = { reason: 'testing' }
modify_req = NonstandardPooler.modify(false, @nspooler_url, 'myfakehost', 'token-value', modify_hash) modify_req = NonstandardPooler.modify(false, @nspooler_url, 'myfakehost', 'token-value', modify_hash)
expect(modify_req['ok']).to be true expect(modify_req['ok']).to be true
end end
@ -208,7 +211,7 @@ describe NonstandardPooler do
it 'prints the status' do it 'prints the status' do
stub_request(:get, "#{@nspooler_url}/status") stub_request(:get, "#{@nspooler_url}/status")
.to_return(:status => 200, :body => @status_response_body, :headers => {}) .to_return(status: 200, body: @status_response_body, headers: {})
status = NonstandardPooler.status(false, @nspooler_url) status = NonstandardPooler.status(false, @nspooler_url)
expect(status).to be_an_instance_of Hash expect(status).to be_an_instance_of Hash
@ -231,7 +234,7 @@ describe NonstandardPooler do
it 'prints the summary' do it 'prints the summary' do
stub_request(:get, "#{@nspooler_url}/summary") stub_request(:get, "#{@nspooler_url}/summary")
.to_return(:status => 200, :body => @status_response_body, :headers => {}) .to_return(status: 200, body: @status_response_body, headers: {})
summary = NonstandardPooler.summary(false, @nspooler_url) summary = NonstandardPooler.summary(false, @nspooler_url)
expect(summary).to be_an_instance_of Hash expect(summary).to be_an_instance_of Hash
@ -256,7 +259,7 @@ describe NonstandardPooler do
it 'makes a query about a vm' do it 'makes a query about a vm' do
stub_request(:get, "#{@nspooler_url}/host/sol10-11") stub_request(:get, "#{@nspooler_url}/host/sol10-11")
.to_return(:status => 200, :body => @query_response_body, :headers => {}) .to_return(status: 200, body: @query_response_body, headers: {})
query_req = NonstandardPooler.query(false, @nspooler_url, 'sol10-11') query_req = NonstandardPooler.query(false, @nspooler_url, 'sol10-11')
expect(query_req).to be_an_instance_of Hash expect(query_req).to be_an_instance_of Hash
@ -271,8 +274,8 @@ describe NonstandardPooler do
it 'deletes a single existing vm' do it 'deletes a single existing vm' do
stub_request(:delete, "#{@nspooler_url}/host/sol11-7") stub_request(:delete, "#{@nspooler_url}/host/sol11-7")
.with(:headers => @auth_token_headers) .with(headers: @auth_token_headers)
.to_return(:status => 200, :body => @delete_response_success, :headers => {}) .to_return(status: 200, body: @delete_response_success, headers: {})
request = NonstandardPooler.delete(false, @nspooler_url, 'sol11-7', 'token-value', nil) request = NonstandardPooler.delete(false, @nspooler_url, 'sol11-7', 'token-value', nil)
expect(request['sol11-7']['ok']).to be true expect(request['sol11-7']['ok']).to be true
@ -280,8 +283,8 @@ describe NonstandardPooler do
it 'does not delete a nonexistant vm' do it 'does not delete a nonexistant vm' do
stub_request(:delete, "#{@nspooler_url}/host/fakehost") stub_request(:delete, "#{@nspooler_url}/host/fakehost")
.with(:headers => @auth_token_headers) .with(headers: @auth_token_headers)
.to_return(:status => 401, :body => @delete_response_failure, :headers => {}) .to_return(status: 401, body: @delete_response_failure, headers: {})
request = NonstandardPooler.delete(false, @nspooler_url, 'fakehost', 'token-value', nil) request = NonstandardPooler.delete(false, @nspooler_url, 'fakehost', 'token-value', nil)
expect(request['fakehost']['ok']).to be false expect(request['fakehost']['ok']).to be false

View file

@ -15,7 +15,7 @@ describe Pooler do
it 'returns a hash with operating systems from the pooler' do it 'returns a hash with operating systems from the pooler' do
stub_request(:get, "#{@vmpooler_url}/vm") stub_request(:get, "#{@vmpooler_url}/vm")
.to_return(:status => 200, :body => @list_response_body, :headers => {}) .to_return(status: 200, body: @list_response_body, headers: {})
list = Pooler.list(false, @vmpooler_url, nil) list = Pooler.list(false, @vmpooler_url, nil)
expect(list).to be_an_instance_of Array expect(list).to be_an_instance_of Array
@ -23,7 +23,7 @@ describe Pooler do
it 'filters operating systems based on the filter param' do it 'filters operating systems based on the filter param' do
stub_request(:get, "#{@vmpooler_url}/vm") stub_request(:get, "#{@vmpooler_url}/vm")
.to_return(:status => 200, :body => @list_response_body, :headers => {}) .to_return(status: 200, body: @list_response_body, headers: {})
list = Pooler.list(false, @vmpooler_url, 'deb') list = Pooler.list(false, @vmpooler_url, 'deb')
expect(list).to be_an_instance_of Array expect(list).to be_an_instance_of Array
@ -32,7 +32,7 @@ describe Pooler do
it 'returns nothing if the filter does not match' do it 'returns nothing if the filter does not match' do
stub_request(:get, "#{@vmpooler_url}/vm") stub_request(:get, "#{@vmpooler_url}/vm")
.to_return(:status => 200, :body => @list_response_body, :headers => {}) .to_return(status: 200, body: @list_response_body, headers: {})
list = Pooler.list(false, @vmpooler_url, 'windows') list = Pooler.list(false, @vmpooler_url, 'windows')
expect(list).to be_an_instance_of Array expect(list).to be_an_instance_of Array
@ -48,8 +48,8 @@ describe Pooler do
it 'raises an AuthError if the token is invalid' do it 'raises an AuthError if the token is invalid' do
stub_request(:post, "#{@vmpooler_url}/vm/debian-7-i386") stub_request(:post, "#{@vmpooler_url}/vm/debian-7-i386")
.with(:headers => { 'X-Auth-Token' => 'mytokenfile' }) .with(headers: { 'X-Auth-Token' => 'mytokenfile' })
.to_return(:status => 401, :body => '{"ok":false}', :headers => {}) .to_return(status: 401, body: '{"ok":false}', headers: {})
vm_hash = {} vm_hash = {}
vm_hash['debian-7-i386'] = 1 vm_hash['debian-7-i386'] = 1
@ -58,8 +58,8 @@ describe Pooler do
it 'retrieves a single vm with a token' do it 'retrieves a single vm with a token' do
stub_request(:post, "#{@vmpooler_url}/vm/debian-7-i386") stub_request(:post, "#{@vmpooler_url}/vm/debian-7-i386")
.with(:headers => { 'X-Auth-Token' => 'mytokenfile' }) .with(headers: { 'X-Auth-Token' => 'mytokenfile' })
.to_return(:status => 200, :body => @retrieve_response_body_single, :headers => {}) .to_return(status: 200, body: @retrieve_response_body_single, headers: {})
vm_hash = {} vm_hash = {}
vm_hash['debian-7-i386'] = 1 vm_hash['debian-7-i386'] = 1
@ -71,8 +71,8 @@ describe Pooler do
it 'retrieves a multiple vms with a token' do it 'retrieves a multiple vms with a token' do
stub_request(:post, "#{@vmpooler_url}/vm/debian-7-i386+debian-7-i386+centos-7-x86_64") stub_request(:post, "#{@vmpooler_url}/vm/debian-7-i386+debian-7-i386+centos-7-x86_64")
.with(:headers => { 'X-Auth-Token' => 'mytokenfile' }) .with(headers: { 'X-Auth-Token' => 'mytokenfile' })
.to_return(:status => 200, :body => @retrieve_response_body_double, :headers => {}) .to_return(status: 200, body: @retrieve_response_body_double, headers: {})
vm_hash = {} vm_hash = {}
vm_hash['debian-7-i386'] = 2 vm_hash['debian-7-i386'] = 2
@ -89,11 +89,11 @@ describe Pooler do
let(:ondemand_response) { '{"ok":true,"request_id":"1234"}' } let(:ondemand_response) { '{"ok":true,"request_id":"1234"}' }
it 'retreives the vm with a token' do it 'retreives the vm with a token' do
stub_request(:post, "#{@vmpooler_url}/ondemandvm/debian-7-i386") stub_request(:post, "#{@vmpooler_url}/ondemandvm/debian-7-i386")
.with(:headers => { 'X-Auth-Token' => 'mytokenfile' }) .with(headers: { 'X-Auth-Token' => 'mytokenfile' })
.to_return(:status => 200, :body => ondemand_response, :headers => {}) .to_return(status: 200, body: ondemand_response, headers: {})
stub_request(:get, "#{@vmpooler_url}/ondemandvm/1234") stub_request(:get, "#{@vmpooler_url}/ondemandvm/1234")
.to_return(:status => 200, :body => @retrieve_response_body_single, :headers => {}) .to_return(status: 200, body: @retrieve_response_body_single, headers: {})
vm_hash = {} vm_hash = {}
vm_hash['debian-7-i386'] = 1 vm_hash['debian-7-i386'] = 1
@ -117,11 +117,11 @@ describe Pooler do
end end
it 'modifies the TTL of a vm' do it 'modifies the TTL of a vm' do
modify_hash = { :lifetime => 12 } modify_hash = { lifetime: 12 }
stub_request(:put, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6") stub_request(:put, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6")
.with(:body => { '{"lifetime":12}' => true }, .with(body: { '{"lifetime":12}' => true },
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded', 'X-Auth-Token' => 'mytokenfile' }) headers: { 'Content-Type' => 'application/x-www-form-urlencoded', 'X-Auth-Token' => 'mytokenfile' })
.to_return(:status => 200, :body => @modify_response_body_success, :headers => {}) .to_return(status: 200, body: @modify_response_body_success, headers: {})
modify_req = Pooler.modify(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile', modify_hash) modify_req = Pooler.modify(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile', modify_hash)
expect(modify_req['ok']).to be true expect(modify_req['ok']).to be true
@ -136,8 +136,8 @@ describe Pooler do
it 'deletes a specified vm' do it 'deletes a specified vm' do
stub_request(:delete, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6") stub_request(:delete, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6")
.with(:headers => { 'X-Auth-Token' => 'mytokenfile' }) .with(headers: { 'X-Auth-Token' => 'mytokenfile' })
.to_return(:status => 200, :body => @delete_response_body_success, :headers => {}) .to_return(status: 200, body: @delete_response_body_success, headers: {})
expect(Pooler.delete(false, @vmpooler_url, ['fq6qlpjlsskycq6'], 'mytokenfile', nil)).to eq @delete_response expect(Pooler.delete(false, @vmpooler_url, ['fq6qlpjlsskycq6'], 'mytokenfile', nil)).to eq @delete_response
end end
@ -155,7 +155,7 @@ describe Pooler do
it 'prints the status' do it 'prints the status' do
stub_request(:get, "#{@vmpooler_url}/status") stub_request(:get, "#{@vmpooler_url}/status")
.to_return(:status => 200, :body => @status_response_body, :headers => {}) .to_return(status: 200, body: @status_response_body, headers: {})
status = Pooler.status(false, @vmpooler_url) status = Pooler.status(false, @vmpooler_url)
expect(status).to be_an_instance_of Hash expect(status).to be_an_instance_of Hash
@ -178,7 +178,7 @@ describe Pooler do
it 'makes a query about a vm' do it 'makes a query about a vm' do
stub_request(:get, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6") stub_request(:get, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6")
.to_return(:status => 200, :body => @query_response_body, :headers => {}) .to_return(status: 200, body: @query_response_body, headers: {})
query_req = Pooler.query(false, @vmpooler_url, 'fq6qlpjlsskycq6') query_req = Pooler.query(false, @vmpooler_url, 'fq6qlpjlsskycq6')
expect(query_req).to be_an_instance_of Hash expect(query_req).to be_an_instance_of Hash
@ -192,8 +192,8 @@ describe Pooler do
it 'makes a snapshot for a single vm' do it 'makes a snapshot for a single vm' do
stub_request(:post, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6/snapshot") stub_request(:post, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6/snapshot")
.with(:headers => { 'X-Auth-Token' => 'mytokenfile' }) .with(headers: { 'X-Auth-Token' => 'mytokenfile' })
.to_return(:status => 200, :body => @snapshot_response_body, :headers => {}) .to_return(status: 200, body: @snapshot_response_body, headers: {})
snapshot_req = Pooler.snapshot(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile') snapshot_req = Pooler.snapshot(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile')
expect(snapshot_req['ok']).to be true expect(snapshot_req['ok']).to be true
@ -207,15 +207,18 @@ describe Pooler do
it 'makes a request to revert a vm from a snapshot' do it 'makes a request to revert a vm from a snapshot' do
stub_request(:post, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6/snapshot/dAfewKNfaweLKNve") stub_request(:post, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6/snapshot/dAfewKNfaweLKNve")
.with(:headers => { 'X-Auth-Token' => 'mytokenfile' }) .with(headers: { 'X-Auth-Token' => 'mytokenfile' })
.to_return(:status => 200, :body => @revert_response_body, :headers => {}) .to_return(status: 200, body: @revert_response_body, headers: {})
revert_req = Pooler.revert(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile', 'dAfewKNfaweLKNve') revert_req = Pooler.revert(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile', 'dAfewKNfaweLKNve')
expect(revert_req['ok']).to be true expect(revert_req['ok']).to be true
end end
it "doesn't make a request to revert a vm if snapshot is not provided" do it "doesn't make a request to revert a vm if snapshot is not provided" do
expect { Pooler.revert(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile', nil) }.to raise_error(RuntimeError, 'Snapshot SHA provided was nil, could not revert fq6qlpjlsskycq6') expect do
Pooler.revert(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile',
nil)
end.to raise_error(RuntimeError, 'Snapshot SHA provided was nil, could not revert fq6qlpjlsskycq6')
end end
it 'raises a TokenError if no token was provided' do it 'raises a TokenError if no token was provided' do
@ -231,7 +234,7 @@ describe Pooler do
it 'makes a request to extend disk space of a vm' do it 'makes a request to extend disk space of a vm' do
stub_request(:post, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6/disk/12") stub_request(:post, "#{@vmpooler_url}/vm/fq6qlpjlsskycq6/disk/12")
.with(:headers => { 'X-Auth-Token' => 'mytokenfile' }). to_return(:status => 200, :body => @disk_response_body_success, :headers => {}) .with(headers: { 'X-Auth-Token' => 'mytokenfile' }).to_return(status: 200, body: @disk_response_body_success, headers: {})
disk_req = Pooler.disk(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile', 12) disk_req = Pooler.disk(false, @vmpooler_url, 'fq6qlpjlsskycq6', 'mytokenfile', 12)
expect(disk_req['ok']).to be true expect(disk_req['ok']).to be true

View file

@ -16,7 +16,7 @@ describe Service do
it 'prompts the user for their password and retrieves a token' do it 'prompts the user for their password and retrieves a token' do
config = { 'user' => 'first.last', 'url' => 'http://default.url' } config = { 'user' => 'first.last', 'url' => 'http://default.url' }
service = Service.new(MockOptions.new, config) service = Service.new(MockOptions.new, config)
allow(STDOUT).to receive(:puts).with('Enter your http://default.url service password:') allow($stdout).to receive(:puts).with('Enter your http://default.url service password:')
allow(Commander::UI).to(receive(:password) allow(Commander::UI).to(receive(:password)
.with('Enter your http://default.url service password:', '*') .with('Enter your http://default.url service password:', '*')
.and_return('hunter2')) .and_return('hunter2'))
@ -29,9 +29,9 @@ describe Service do
it 'prompts the user for their username and password if the username is unknown' do it 'prompts the user for their username and password if the username is unknown' do
config = { 'url' => 'http://default.url' } config = { 'url' => 'http://default.url' }
service = Service.new(MockOptions.new({}), config) service = Service.new(MockOptions.new({}), config)
allow(STDOUT).to receive(:puts).with 'Enter your http://default.url service username:' allow($stdout).to receive(:puts).with 'Enter your http://default.url service username:'
allow(STDOUT).to receive(:puts).with "\n" allow($stdout).to receive(:puts).with "\n"
allow(STDIN).to receive(:gets).and_return('first.last') allow($stdin).to receive(:gets).and_return('first.last')
allow(Commander::UI).to(receive(:password) allow(Commander::UI).to(receive(:password)
.with('Enter your http://default.url service password:', '*') .with('Enter your http://default.url service password:', '*')
.and_return('hunter2')) .and_return('hunter2'))
@ -59,16 +59,16 @@ describe Service do
it 'reports the status of a token' do it 'reports the status of a token' do
config = { config = {
'user' => 'first.last', 'user' => 'first.last',
'url' => 'http://default.url', 'url' => 'http://default.url'
} }
options = MockOptions.new('token' => 'token-value') options = MockOptions.new('token' => 'token-value')
service = Service.new(options, config) service = Service.new(options, config)
status = { status = {
'ok' => true, 'ok' => true,
'user' => config['user'], 'user' => config['user'],
'created' => '2017-09-22 02:04:18 +0000', 'created' => '2017-09-22 02:04:18 +0000',
'last_accessed' => '2017-09-22 02:04:28 +0000', 'last_accessed' => '2017-09-22 02:04:28 +0000',
'reserved_hosts' => [], 'reserved_hosts' => []
} }
allow(Auth).to(receive(:token_status) allow(Auth).to(receive(:token_status)
.with(nil, config['url'], 'token-value') .with(nil, config['url'], 'token-value')

View file

@ -8,14 +8,14 @@ class ServiceStub
if os_types.keys[0] == 'abs_host_string' if os_types.keys[0] == 'abs_host_string'
return { return {
os_types.keys[0] => { 'hostname' => ['abs-hostname.delivery.puppetlabs.net'] }, os_types.keys[0] => { 'hostname' => ['abs-hostname.delivery.puppetlabs.net'] },
'ok' => true, 'ok' => true
} }
end end
{ {
os_types.keys[0] => { 'hostname' => 'vmpooler-hostname' }, os_types.keys[0] => { 'hostname' => 'vmpooler-hostname' },
'domain' => 'delivery.puppetlabs.net', 'domain' => 'delivery.puppetlabs.net',
'ok' => true, 'ok' => true
} }
end end

View file

@ -36,13 +36,14 @@ describe Utils do
it 'formats a result from vmpooler into a hash of os to hostnames' do it 'formats a result from vmpooler into a hash of os to hostnames' do
result = Utils.standardize_hostnames(JSON.parse(@vmpooler_response_body)) result = Utils.standardize_hostnames(JSON.parse(@vmpooler_response_body))
expect(result).to eq('centos-7-x86_64' => ['dlgietfmgeegry2.delivery.mycompany.net'], expect(result).to eq('centos-7-x86_64' => ['dlgietfmgeegry2.delivery.mycompany.net'],
'ubuntu-1610-x86_64' => ['gdoy8q3nckuob0i.delivery.mycompany.net', 'ctnktsd0u11p9tm.delivery.mycompany.net']) 'ubuntu-1610-x86_64' => ['gdoy8q3nckuob0i.delivery.mycompany.net',
'ctnktsd0u11p9tm.delivery.mycompany.net'])
end end
it 'formats a result from the nonstandard pooler into a hash of os to hostnames' do it 'formats a result from the nonstandard pooler into a hash of os to hostnames' do
result = Utils.standardize_hostnames(JSON.parse(@nonstandard_response_body)) result = Utils.standardize_hostnames(JSON.parse(@nonstandard_response_body))
expect(result).to eq('solaris-10-sparc' => ['sol10-10.delivery.mycompany.net', 'sol10-11.delivery.mycompany.net'], expect(result).to eq('solaris-10-sparc' => ['sol10-10.delivery.mycompany.net', 'sol10-11.delivery.mycompany.net'],
'ubuntu-16.04-power8' => ['power8-ubuntu16.04-6.delivery.mycompany.net']) 'ubuntu-16.04-power8' => ['power8-ubuntu16.04-6.delivery.mycompany.net'])
end end
end end
@ -50,12 +51,12 @@ describe Utils do
describe '#format_host_output' do describe '#format_host_output' do
before :each do before :each do
@vmpooler_results = { @vmpooler_results = {
'centos-7-x86_64' => ['dlgietfmgeegry2.delivery.mycompany.net'], 'centos-7-x86_64' => ['dlgietfmgeegry2.delivery.mycompany.net'],
'ubuntu-1610-x86_64' => ['gdoy8q3nckuob0i.delivery.mycompany.net', 'ctnktsd0u11p9tm.delivery.mycompany.net'], 'ubuntu-1610-x86_64' => ['gdoy8q3nckuob0i.delivery.mycompany.net', 'ctnktsd0u11p9tm.delivery.mycompany.net']
} }
@nonstandard_results = { @nonstandard_results = {
'solaris-10-sparc' => ['sol10-10.delivery.mycompany.net', 'sol10-11.delivery.mycompany.net'], 'solaris-10-sparc' => ['sol10-10.delivery.mycompany.net', 'sol10-11.delivery.mycompany.net'],
'ubuntu-16.04-power8' => ['power8-ubuntu16.04-6.delivery.mycompany.net'], 'ubuntu-16.04-power8' => ['power8-ubuntu16.04-6.delivery.mycompany.net']
} }
@vmpooler_output = <<~OUT.chomp @vmpooler_output = <<~OUT.chomp
- dlgietfmgeegry2.delivery.mycompany.net (centos-7-x86_64) - dlgietfmgeegry2.delivery.mycompany.net (centos-7-x86_64)
@ -98,23 +99,23 @@ describe Utils do
describe '#get_service_config' do describe '#get_service_config' do
before :each do before :each do
@default_config = { @default_config = {
'url' => 'http://default.url', 'url' => 'http://default.url',
'user' => 'first.last.default', 'user' => 'first.last.default',
'token' => 'default-token', 'token' => 'default-token'
} }
@services_config = { @services_config = {
'services' => { 'services' => {
'vm' => { 'vm' => {
'url' => 'http://vmpooler.url', 'url' => 'http://vmpooler.url',
'user' => 'first.last.vmpooler', 'user' => 'first.last.vmpooler',
'token' => 'vmpooler-token', 'token' => 'vmpooler-token'
}, },
'ns' => { 'ns' => {
'url' => 'http://nspooler.url', 'url' => 'http://nspooler.url',
'user' => 'first.last.nspooler', 'user' => 'first.last.nspooler',
'token' => 'nspooler-token', 'token' => 'nspooler-token'
}, }
}, }
} }
end end
@ -126,26 +127,26 @@ describe Utils do
it 'allows selection by configured service key' do it 'allows selection by configured service key' do
config = @default_config.merge @services_config config = @default_config.merge @services_config
options = MockOptions.new(:service => 'ns') options = MockOptions.new(service: 'ns')
expect(Utils.get_service_config(config, options)).to include @services_config['services']['ns'] expect(Utils.get_service_config(config, options)).to include @services_config['services']['ns']
end end
it 'uses top-level service config values as defaults when configured service values are missing' do it 'uses top-level service config values as defaults when configured service values are missing' do
config = @default_config.merge @services_config config = @default_config.merge @services_config
config['services']['vm'].delete 'url' config['services']['vm'].delete 'url'
options = MockOptions.new(:service => 'vm') options = MockOptions.new(service: 'vm')
expect(Utils.get_service_config(config, options)['url']).to eq 'http://default.url' expect(Utils.get_service_config(config, options)['url']).to eq 'http://default.url'
end end
it "raises an error if passed a service name that hasn't been configured" do it "raises an error if passed a service name that hasn't been configured" do
config = @default_config.merge @services_config config = @default_config.merge @services_config
options = MockOptions.new(:service => 'none') options = MockOptions.new(service: 'none')
expect { Utils.get_service_config(config, options) }.to raise_error ArgumentError expect { Utils.get_service_config(config, options) }.to raise_error ArgumentError
end end
it 'prioritizes values passed as command line options over configuration options' do it 'prioritizes values passed as command line options over configuration options' do
config = @default_config config = @default_config
options = MockOptions.new(:url => 'http://alternate.url', :token => 'alternate-token') options = MockOptions.new(url: 'http://alternate.url', token: 'alternate-token')
expected = config.merge('url' => 'http://alternate.url', 'token' => 'alternate-token') expected = config.merge('url' => 'http://alternate.url', 'token' => 'alternate-token')
expect(Utils.get_service_config(config, options)).to include expected expect(Utils.get_service_config(config, options)).to include expected
end end
@ -182,15 +183,15 @@ describe Utils do
{ {
'template' => 'ubuntu-1604-x86_64', 'template' => 'ubuntu-1604-x86_64',
'lifetime' => 12, 'lifetime' => 12,
'running' => 9.66, 'running' => 9.66,
'state' => 'running', 'state' => 'running',
'ip' => '127.0.0.1', 'ip' => '127.0.0.1',
'domain' => domain, 'domain' => domain
} }
end end
it 'outputs fqdn for host' do it 'outputs fqdn for host' do
expect(STDOUT).to receive(:puts).with(fqdn) expect($stdout).to receive(:puts).with(fqdn)
subject subject
end end
@ -201,17 +202,17 @@ describe Utils do
let(:hostname) { 'sol11-9.delivery.mycompany.net' } let(:hostname) { 'sol11-9.delivery.mycompany.net' }
let(:host_data) do let(:host_data) do
{ {
'fqdn' => hostname, 'fqdn' => hostname,
'os_triple' => 'solaris-11-sparc', 'os_triple' => 'solaris-11-sparc',
'reserved_by_user' => 'first.last', 'reserved_by_user' => 'first.last',
'reserved_for_reason' => '', 'reserved_for_reason' => '',
'hours_left_on_reservation' => 35.89, 'hours_left_on_reservation' => 35.89
} }
end end
let(:fqdn) { hostname } # for nspooler these are the same let(:fqdn) { hostname } # for nspooler these are the same
it 'outputs fqdn for host' do it 'outputs fqdn for host' do
expect(STDOUT).to receive(:puts).with(fqdn) expect($stdout).to receive(:puts).with(fqdn)
subject subject
end end
@ -231,19 +232,19 @@ describe Utils do
{ {
'hostname' => fqdn, 'hostname' => fqdn,
'type' => template, 'type' => template,
'enging' => 'vmpooler', 'enging' => 'vmpooler'
}, }
], ],
'request' => { 'request' => {
'job' => { 'job' => {
'id' => hostname, 'id' => hostname
} }
}, }
} }
end end
it 'outputs fqdn for host' do it 'outputs fqdn for host' do
expect(STDOUT).to receive(:puts).with(fqdn) expect($stdout).to receive(:puts).with(fqdn)
subject subject
end end
@ -275,10 +276,10 @@ describe Utils do
hostname => { hostname => {
'template' => 'ubuntu-1604-x86_64', 'template' => 'ubuntu-1604-x86_64',
'lifetime' => 12, 'lifetime' => 12,
'running' => 9.66, 'running' => 9.66,
'state' => 'running', 'state' => 'running',
'ip' => '127.0.0.1', 'ip' => '127.0.0.1',
'domain' => domain, 'domain' => domain
} }
} }
end end
@ -286,7 +287,7 @@ describe Utils do
let(:default_output) { "- #{fqdn} (running, ubuntu-1604-x86_64, 9.66/12 hours)" } let(:default_output) { "- #{fqdn} (running, ubuntu-1604-x86_64, 9.66/12 hours)" }
it 'prints output with host fqdn, template and duration info' do it 'prints output with host fqdn, template and duration info' do
expect(STDOUT).to receive(:puts).with(default_output) expect($stdout).to receive(:puts).with(default_output)
subject subject
end end
@ -298,14 +299,14 @@ describe Utils do
hostname => { hostname => {
'template' => 'redhat-7-x86_64', 'template' => 'redhat-7-x86_64',
'lifetime' => 48, 'lifetime' => 48,
'running' => 7.67, 'running' => 7.67,
'state' => 'running', 'state' => 'running',
'tags' => { 'tags' => {
'user' => 'bob', 'user' => 'bob',
'role' => 'agent', 'role' => 'agent'
}, },
'ip' => '127.0.0.1', 'ip' => '127.0.0.1',
'domain' => domain, 'domain' => domain
} }
} }
end end
@ -313,7 +314,7 @@ describe Utils do
it 'prints output with host fqdn, template, duration info, and tags' do it 'prints output with host fqdn, template, duration info, and tags' do
output = "- #{fqdn} (running, redhat-7-x86_64, 7.67/48 hours, user: bob, role: agent)" output = "- #{fqdn} (running, redhat-7-x86_64, 7.67/48 hours, user: bob, role: agent)"
expect(STDOUT).to receive(:puts).with(output) expect($stdout).to receive(:puts).with(output)
subject subject
end end
@ -323,7 +324,7 @@ describe Utils do
let(:print_to_stderr) { true } let(:print_to_stderr) { true }
it 'outputs to stderr instead of stdout' do it 'outputs to stderr instead of stdout' do
expect(STDERR).to receive(:puts).with(default_output) expect($stderr).to receive(:puts).with(default_output)
subject subject
end end
@ -337,11 +338,11 @@ describe Utils do
let(:response_body) do let(:response_body) do
{ {
hostname => { hostname => {
'fqdn' => hostname, 'fqdn' => hostname,
'os_triple' => 'solaris-11-sparc', 'os_triple' => 'solaris-11-sparc',
'reserved_by_user' => 'first.last', 'reserved_by_user' => 'first.last',
'reserved_for_reason' => '', 'reserved_for_reason' => '',
'hours_left_on_reservation' => 35.89, 'hours_left_on_reservation' => 35.89
} }
} }
end end
@ -349,7 +350,7 @@ describe Utils do
let(:default_output) { "- #{hostname} (solaris-11-sparc, 35.89h remaining)" } let(:default_output) { "- #{hostname} (solaris-11-sparc, 35.89h remaining)" }
it 'prints output with host, template, and time remaining' do it 'prints output with host, template, and time remaining' do
expect(STDOUT).to receive(:puts).with(default_output) expect($stdout).to receive(:puts).with(default_output)
subject subject
end end
@ -358,11 +359,11 @@ describe Utils do
let(:response_body) do let(:response_body) do
{ {
hostname => { hostname => {
'fqdn' => hostname, 'fqdn' => hostname,
'os_triple' => 'solaris-11-sparc', 'os_triple' => 'solaris-11-sparc',
'reserved_by_user' => 'first.last', 'reserved_by_user' => 'first.last',
'reserved_for_reason' => 'testing', 'reserved_for_reason' => 'testing',
'hours_left_on_reservation' => 35.89, 'hours_left_on_reservation' => 35.89
} }
} }
end end
@ -370,7 +371,7 @@ describe Utils do
it 'prints output with host, template, time remaining, and reason' do it 'prints output with host, template, time remaining, and reason' 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(STDOUT).to receive(:puts).with(output) expect($stdout).to receive(:puts).with(output)
subject subject
end end
@ -380,7 +381,7 @@ describe Utils do
let(:print_to_stderr) { true } let(:print_to_stderr) { true }
it 'outputs to stderr instead of stdout' do it 'outputs to stderr instead of stdout' do
expect(STDERR).to receive(:puts).with(default_output) expect($stderr).to receive(:puts).with(default_output)
subject subject
end end
@ -392,7 +393,7 @@ describe Utils do
let(:hostname) { '1597952189390' } let(:hostname) { '1597952189390' }
let(:fqdn) { 'example-noun.delivery.mycompany.net' } let(:fqdn) { 'example-noun.delivery.mycompany.net' }
let(:fqdn_hostname) {'example-noun'} let(:fqdn_hostname) { 'example-noun' }
let(:template) { 'ubuntu-1604-x86_64' } let(:template) { 'ubuntu-1604-x86_64' }
# This seems to be the miminal stub response from ABS for the current output # This seems to be the miminal stub response from ABS for the current output
@ -404,14 +405,14 @@ describe Utils do
{ {
'hostname' => fqdn, 'hostname' => fqdn,
'type' => template, 'type' => template,
'engine' => 'vmpooler', 'engine' => 'vmpooler'
}, }
], ],
'request' => { 'request' => {
'job' => { 'job' => {
'id' => hostname, 'id' => hostname
} }
}, }
} }
} }
end end
@ -420,58 +421,58 @@ describe Utils do
let(:domain) { 'delivery.mycompany.net' } let(:domain) { 'delivery.mycompany.net' }
let(:response_body_vmpooler) do let(:response_body_vmpooler) do
{ {
fqdn_hostname => { fqdn_hostname => {
'template' => template, 'template' => template,
'lifetime' => 48, 'lifetime' => 48,
'running' => 7.67, 'running' => 7.67,
'state' => 'running', 'state' => 'running',
'tags' => { 'tags' => {
'user' => 'bob', 'user' => 'bob',
'role' => 'agent', 'role' => 'agent'
}, },
'ip' => '127.0.0.1', 'ip' => '127.0.0.1',
'domain' => domain, 'domain' => domain
} }
} }
end end
before(:each) do before(:each) do
allow(Utils).to receive(:get_vmpooler_service_config).and_return({ allow(Utils).to receive(:get_vmpooler_service_config).and_return({
'url' => 'http://vmpooler.example.com', 'url' => 'http://vmpooler.example.com',
'token' => 'krypto-knight' 'token' => 'krypto-knight'
}) })
allow(service).to receive(:query) allow(service).to receive(:query)
.with(anything, fqdn_hostname) .with(anything, fqdn_hostname)
.and_return(response_body_vmpooler) .and_return(response_body_vmpooler)
end end
let(:default_output_first_line) { "- [JobID:#{hostname}] <allocated>" } let(:default_output_first_line) { "- [JobID:#{hostname}] <allocated>" }
let(:default_output_second_line) { " - #{fqdn} (#{template})" } let(:default_output_second_line) { " - #{fqdn} (#{template})" }
it 'prints output with job id, host, and template' do it 'prints output with job id, host, and template' do
expect(STDOUT).to receive(:puts).with(default_output_first_line) expect($stdout).to receive(:puts).with(default_output_first_line)
expect(STDOUT).to receive(:puts).with(default_output_second_line) expect($stdout).to receive(:puts).with(default_output_second_line)
subject subject
end end
it 'prints more information when vmpooler_fallback is set output with job id, host, template, lifetime, user and role' do it 'prints more information when vmpooler_fallback is set output with job id, host, template, lifetime, user and role' do
fallback = {'vmpooler_fallback' => 'vmpooler'} fallback = { 'vmpooler_fallback' => 'vmpooler' }
service.config.merge! fallback service.config.merge! fallback
default_output_second_line=" - #{fqdn} (running, #{template}, 7.67/48 hours, user: bob, role: agent)" default_output_second_line = " - #{fqdn} (running, #{template}, 7.67/48 hours, user: bob, role: agent)"
expect(STDOUT).to receive(:puts).with(default_output_first_line) expect($stdout).to receive(:puts).with(default_output_first_line)
expect(STDOUT).to receive(:puts).with(default_output_second_line) expect($stdout).to receive(:puts).with(default_output_second_line)
subject subject
end end
it 'prints in red when destroyed' do it 'prints in red when destroyed' do
fallback = {'vmpooler_fallback' => 'vmpooler'} fallback = { 'vmpooler_fallback' => 'vmpooler' }
service.config.merge! fallback service.config.merge! fallback
response_body_vmpooler[fqdn_hostname]['state'] = "destroyed" response_body_vmpooler[fqdn_hostname]['state'] = 'destroyed'
default_output_second_line_red=" - #{fqdn} (destroyed, #{template}, 7.67/48 hours, user: bob, role: agent)".red default_output_second_line_red = " - #{fqdn} (destroyed, #{template}, 7.67/48 hours, user: bob, role: agent)".red
expect(STDOUT).to receive(:puts).with(default_output_first_line) expect($stdout).to receive(:puts).with(default_output_first_line)
expect(STDOUT).to receive(:puts).with(default_output_second_line_red) expect($stdout).to receive(:puts).with(default_output_second_line_red)
subject subject
end end
@ -480,8 +481,8 @@ describe Utils do
let(:print_to_stderr) { true } let(:print_to_stderr) { true }
it 'outputs to stderr instead of stdout' do it 'outputs to stderr instead of stdout' do
expect(STDERR).to receive(:puts).with(default_output_first_line) expect($stderr).to receive(:puts).with(default_output_first_line)
expect(STDERR).to receive(:puts).with(default_output_second_line) expect($stderr).to receive(:puts).with(default_output_second_line)
subject subject
end end
@ -494,34 +495,34 @@ describe Utils do
let(:hostname) { '1597952189390' } let(:hostname) { '1597952189390' }
let(:fqdn) { 'this-noun.delivery.mycompany.net' } let(:fqdn) { 'this-noun.delivery.mycompany.net' }
let(:fqdn_ns) { 'that-noun.delivery.mycompany.net' } let(:fqdn_ns) { 'that-noun.delivery.mycompany.net' }
let(:fqdn_hostname) {'this-noun'} let(:fqdn_hostname) { 'this-noun' }
let(:fqdn_ns_hostname) {'that-noun'} let(:fqdn_ns_hostname) { 'that-noun' }
let(:template) { 'ubuntu-1604-x86_64' } let(:template) { 'ubuntu-1604-x86_64' }
let(:template_ns) { 'solaris-10-sparc' } let(:template_ns) { 'solaris-10-sparc' }
# This seems to be the miminal stub response from ABS for the current output # This seems to be the miminal stub response from ABS for the current output
let(:response_body) do let(:response_body) do
{ {
hostname => { hostname => {
'state' => 'allocated', 'state' => 'allocated',
'allocated_resources' => [ 'allocated_resources' => [
{ {
'hostname' => fqdn, 'hostname' => fqdn,
'type' => template, 'type' => template,
'engine' => 'vmpooler', 'engine' => 'vmpooler'
}, },
{ {
'hostname' => fqdn_ns, 'hostname' => fqdn_ns,
'type' => template_ns, 'type' => template_ns,
'engine' => 'nspooler', 'engine' => 'nspooler'
}, }
], ],
'request' => { 'request' => {
'job' => { 'job' => {
'id' => hostname, 'id' => hostname
} }
},
} }
}
} }
end end
@ -529,29 +530,29 @@ describe Utils do
let(:domain) { 'delivery.mycompany.net' } let(:domain) { 'delivery.mycompany.net' }
let(:response_body_vmpooler) do let(:response_body_vmpooler) do
{ {
fqdn_hostname => { fqdn_hostname => {
'template' => template, 'template' => template,
'lifetime' => 48, 'lifetime' => 48,
'running' => 7.67, 'running' => 7.67,
'state' => 'running', 'state' => 'running',
'tags' => { 'tags' => {
'user' => 'bob', 'user' => 'bob',
'role' => 'agent', 'role' => 'agent'
}, },
'ip' => '127.0.0.1', 'ip' => '127.0.0.1',
'domain' => domain, 'domain' => domain
} }
} }
end end
before(:each) do before(:each) do
allow(Utils).to receive(:get_vmpooler_service_config).and_return({ allow(Utils).to receive(:get_vmpooler_service_config).and_return({
'url' => 'http://vmpooler.example.com', 'url' => 'http://vmpooler.example.com',
'token' => 'krypto-knight' 'token' => 'krypto-knight'
}) })
allow(service).to receive(:query) allow(service).to receive(:query)
.with(anything, fqdn_hostname) .with(anything, fqdn_hostname)
.and_return(response_body_vmpooler) .and_return(response_body_vmpooler)
end end
let(:default_output_first_line) { "- [JobID:#{hostname}] <allocated>" } let(:default_output_first_line) { "- [JobID:#{hostname}] <allocated>" }
@ -559,9 +560,9 @@ describe Utils do
let(:default_output_third_line) { " - #{fqdn_ns} (#{template_ns})" } let(:default_output_third_line) { " - #{fqdn_ns} (#{template_ns})" }
it 'prints output with job id, host, and template' do it 'prints output with job id, host, and template' do
expect(STDOUT).to receive(:puts).with(default_output_first_line) expect($stdout).to receive(:puts).with(default_output_first_line)
expect(STDOUT).to receive(:puts).with(default_output_second_line) expect($stdout).to receive(:puts).with(default_output_second_line)
expect(STDOUT).to receive(:puts).with(default_output_third_line) expect($stdout).to receive(:puts).with(default_output_third_line)
subject subject
end end
@ -570,9 +571,9 @@ describe Utils do
let(:print_to_stderr) { true } let(:print_to_stderr) { true }
it 'outputs to stderr instead of stdout' do it 'outputs to stderr instead of stdout' do
expect(STDERR).to receive(:puts).with(default_output_first_line) expect($stderr).to receive(:puts).with(default_output_first_line)
expect(STDERR).to receive(:puts).with(default_output_second_line) expect($stderr).to receive(:puts).with(default_output_second_line)
expect(STDERR).to receive(:puts).with(default_output_third_line) expect($stderr).to receive(:puts).with(default_output_third_line)
subject subject
end end
@ -586,54 +587,59 @@ describe Utils do
config = { config = {
'user' => 'foo', 'user' => 'foo',
'services' => { 'services' => {
'myabs' => { 'myabs' => {
'url' => 'http://abs.com', 'url' => 'http://abs.com',
'token' => 'krypto-night', 'token' => 'krypto-night',
'type' => 'abs' 'type' => 'abs'
} }
} }
} }
allow(Conf).to receive(:read_config).and_return(config) allow(Conf).to receive(:read_config).and_return(config)
expect{Utils.get_vmpooler_service_config(config['services']['myabs']['vmpooler_fallback'])}.to raise_error(ArgumentError) expect do
Utils.get_vmpooler_service_config(config['services']['myabs']['vmpooler_fallback'])
end.to raise_error(ArgumentError)
end end
it 'returns an error if the vmpooler_fallback is setup but cannot be found' do it 'returns an error if the vmpooler_fallback is setup but cannot be found' do
config = { config = {
'user' => 'foo', 'user' => 'foo',
'services' => { 'services' => {
'myabs' => { 'myabs' => {
'url' => 'http://abs.com', 'url' => 'http://abs.com',
'token' => 'krypto-night', 'token' => 'krypto-night',
'type' => 'abs', 'type' => 'abs',
'vmpooler_fallback' => 'myvmpooler' 'vmpooler_fallback' => 'myvmpooler'
} }
} }
} }
allow(Conf).to receive(:read_config).and_return(config) allow(Conf).to receive(:read_config).and_return(config)
expect{Utils.get_vmpooler_service_config(config['services']['myabs']['vmpooler_fallback'])}.to raise_error(ArgumentError, /myvmpooler/) expect do
Utils.get_vmpooler_service_config(config['services']['myabs']['vmpooler_fallback'])
end.to raise_error(ArgumentError,
/myvmpooler/)
end end
it 'returns the vmpooler_fallback config' do it 'returns the vmpooler_fallback config' do
config = { config = {
'user' => 'foo', 'user' => 'foo',
'services' => { 'services' => {
'myabs' => { 'myabs' => {
'url' => 'http://abs.com', 'url' => 'http://abs.com',
'token' => 'krypto-night', 'token' => 'krypto-night',
'type' => 'abs', 'type' => 'abs',
'vmpooler_fallback' => 'myvmpooler' 'vmpooler_fallback' => 'myvmpooler'
}, },
'myvmpooler' => { 'myvmpooler' => {
'url' => 'http://vmpooler.com', 'url' => 'http://vmpooler.com',
'token' => 'krypto-knight' 'token' => 'krypto-knight'
} }
} }
} }
allow(Conf).to receive(:read_config).and_return(config) allow(Conf).to receive(:read_config).and_return(config)
expect(Utils.get_vmpooler_service_config(config['services']['myabs']['vmpooler_fallback'])).to include({ expect(Utils.get_vmpooler_service_config(config['services']['myabs']['vmpooler_fallback'])).to include({
'url' => 'http://vmpooler.com', 'url' => 'http://vmpooler.com',
'token' => 'krypto-knight', 'token' => 'krypto-knight',
'user' => 'foo', 'user' => 'foo',
'type' => 'vmpooler' 'type' => 'vmpooler'
}) })
end end
end end
end end

View file

@ -8,11 +8,11 @@ Gem::Specification.new do |s|
s.version = Vmfloaty::VERSION s.version = Vmfloaty::VERSION
s.authors = [ s.authors = [
'Brian Cain', 'Brian Cain',
'Puppet', 'Puppet'
] ]
s.email = [ s.email = [
'brianccain@gmail.com', 'brianccain@gmail.com',
'dio-gems@puppet.com', 'dio-gems@puppet.com'
] ]
s.license = 'Apache-2.0' s.license = 'Apache-2.0'
s.homepage = 'https://github.com/puppetlabs/vmfloaty' s.homepage = 'https://github.com/puppetlabs/vmfloaty'