[brightbox|compute] Helper to get default image from API

* First will look for a configuration value brightbox_default_image
* Second will query the API for latest Ubuntu (ideally LTS)
This commit is contained in:
Paul Thornthwaite 2012-08-15 12:27:09 +01:00
parent 977f6e3b8b
commit b221b97ba6
3 changed files with 61 additions and 1 deletions

View File

@ -101,7 +101,24 @@ module Fog
request :update_server_group
request :update_user
module Shared
# Returns an identifier for the default image for use
#
# Currently tries to find the latest version Ubuntu LTS (i686) widening
# up to the latest, official version of Ubuntu available.
#
# Highly recommended that you actually select the image you want to run
# on your servers yourself!
#
# @return [String, nil]
def default_image
return @default_image_id unless @default_image_id.nil?
@default_image_id = Fog.credentials[:brightbox_default_image] || select_default_image
end
end
class Mock
include Shared
def initialize(options)
@brightbox_client_id = options[:brightbox_client_id] || Fog.credentials[:brightbox_client_id]
@ -111,9 +128,15 @@ module Fog
def request(options)
raise "Not implemented"
end
private
def select_default_image
"img-mockd"
end
end
class Real
include Shared
def initialize(options)
# Currently authentication and api endpoints are the same but may change
@ -180,6 +203,34 @@ module Fog
options[:headers] = headers
@connection.request(options)
end
# Queries the API and tries to select the most suitable official Image
# to use if the user chooses not to select their own.
def select_default_image
return @default_image_id unless @default_image_id.nil?
all_images = Fog::Compute[:brightbox].list_images
official_images = all_images.select {|img| img["official"] == true}
ubuntu_lts_images = official_images.select {|img| img["name"] =~ /Ubuntu.*LTS/}
ubuntu_lts_i686_images = ubuntu_lts_images.select {|img| img["arch"] == "i686"}
if ubuntu_lts_i686_images.empty?
# Accept other architectures
if ubuntu_lts_images.empty?
# Accept non-LTS versions of Ubuntu
unsorted_images = official_images.select {|img| img["name"] =~ /Ubuntu/}
else
unsorted_images = ubuntu_lts_images
end
else
unsorted_images = ubuntu_lts_i686_images
end
# Get the latest and use it's ID for the default image
@default_image_id = unsorted_images.sort {|a,b| a["created_at"] <=> b["created_at"]}.first["id"]
rescue
nil
end
end
end

View File

@ -38,7 +38,7 @@ module Fog
attribute :server_type
def initialize(attributes={})
self.image_id ||= 'img-wwgbb' # Ubuntu Lucid 10.04 server (i686)
self.image_id ||= Fog::Compute[:brightbox].default_image
super
end

View File

@ -0,0 +1,9 @@
Shindo.tests('Fog::Compute::Brightbox::Real', ['brightbox']) do
@bb = Fog::Compute::Brightbox::Real.new({})
tests("#respond_to? :default_image").returns(true) do
@bb.respond_to?(:default_image)
end
end