From 05e9d5a0cccfc4b4639b9a08e2578f3a256a8572 Mon Sep 17 00:00:00 2001 From: Brian Cain Date: Sat, 24 Sep 2016 10:22:48 -0700 Subject: [PATCH] (#32) Handle vmpooler responses when token is invalid This commit adds an errors class to handle when pooler tokens are invalid. The retrieve method in Pooler will raise an AuthError if it gets an HTTP 401 from the vmpooler. --- lib/vmfloaty/errors.rb | 5 +++++ lib/vmfloaty/pooler.rb | 6 +++++- spec/vmfloaty/pooler_spec.rb | 10 ++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 lib/vmfloaty/errors.rb diff --git a/lib/vmfloaty/errors.rb b/lib/vmfloaty/errors.rb new file mode 100644 index 0000000..b92211d --- /dev/null +++ b/lib/vmfloaty/errors.rb @@ -0,0 +1,5 @@ +class AuthError < StandardError + def initialize(msg="Could not authenticate to pooler") + super + end +end diff --git a/lib/vmfloaty/pooler.rb b/lib/vmfloaty/pooler.rb index c515d65..f633846 100644 --- a/lib/vmfloaty/pooler.rb +++ b/lib/vmfloaty/pooler.rb @@ -1,6 +1,7 @@ require 'faraday' require 'vmfloaty/http' require 'json' +require 'vmfloaty/errors' class Pooler def self.list(verbose, url, os_filter=nil) @@ -40,10 +41,13 @@ class Pooler response = conn.post "vm/#{os_string}" res_body = JSON.parse(response.body) + if res_body["ok"] res_body + elsif response.status == 401 + raise AuthError, "HTTP #{response.status}: The token provided could not authenticate to the pooler.\n#{res_body}" else - raise "Failed to obtain VMs from the pooler at #{url}/vm/#{os_string}. #{res_body}" + raise "HTTP #{response.status}: Failed to obtain VMs from the pooler at #{url}/vm/#{os_string}. #{res_body}" end end diff --git a/spec/vmfloaty/pooler_spec.rb b/spec/vmfloaty/pooler_spec.rb index 881e883..697149e 100644 --- a/spec/vmfloaty/pooler_spec.rb +++ b/spec/vmfloaty/pooler_spec.rb @@ -44,6 +44,16 @@ describe Pooler do @retrieve_response_body_double = "{\"ok\":true,\"debian-7-i386\":{\"hostname\":[\"sc0o4xqtodlul5w\",\"4m4dkhqiufnjmxy\"]},\"centos-7-x86_64\":{\"hostname\":\"zb91y9qbrbf6d3q\"}}" end + it "raises an AuthError if the token is invalid" do + stub_request(:post, "#{@vmpooler_url}/vm/debian-7-i386"). + with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Length'=>'0', 'User-Agent'=>'Faraday v0.9.2', 'X-Auth-Token'=>'mytokenfile'}). + to_return(:status => 401, :body => "{\"ok\":false}", :headers => {}) + + vm_hash = {} + vm_hash['debian-7-i386'] = 1 + expect{ Pooler.retrieve(false, vm_hash, 'mytokenfile', @vmpooler_url) }.to raise_error(AuthError) + end + it "retrieves a single vm with a token" do stub_request(:post, "#{@vmpooler_url}/vm/debian-7-i386"). with(:headers => {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Length'=>'0', 'User-Agent'=>'Faraday v0.9.2', 'X-Auth-Token'=>'mytokenfile'}).