fog-rackspace-0.1.6/0000755000004100000410000000000013411315054014250 5ustar www-datawww-datafog-rackspace-0.1.6/.travis.yml0000644000004100000410000000115113411315054016357 0ustar www-datawww-datalanguage: ruby sudo: false script: bundle exec rake test matrix: fast_finish: true include: - rvm: 1.8.7 gemfile: gemfiles/Gemfile-ruby-1.8.7 - rvm: 1.9.3 gemfile: Gemfile - rvm: 2.0.0 gemfile: Gemfile - rvm: 2.1.0 gemfile: Gemfile - rvm: 2.1.1 gemfile: Gemfile - rvm: 2.1.1 gemfile: gemfiles/Gemfile-edge - rvm: 2.2.0 gemfile: Gemfile - rvm: 2.2.0 gemfile: gemfiles/Gemfile-edge - rvm: jruby-18mode gemfile: gemfiles/Gemfile-ruby-1.8.7 - rvm: jruby-19mode gemfile: Gemfile - rvm: jruby-head gemfile: Gemfile allow_failures: - rvm: jruby-head fog-rackspace-0.1.6/.rspec0000644000004100000410000000003713411315054015365 0ustar www-datawww-data--format documentation --color fog-rackspace-0.1.6/README.md0000644000004100000410000000075613411315054015537 0ustar www-datawww-data# Fog::Rackspace [![Circle CI](https://circleci.com/gh/fog/fog-rackspace.svg?style=svg)](https://circleci.com/gh/fog/fog-rackspace) [![Build Status](https://travis-ci.org/fog/fog-rackspace.svg?branch=master)](https://travis-ci.org/fog/fog-rackspace) ## Installation Add this line to your application's Gemfile: ```ruby gem 'fog-rackspace' ``` And then execute: $ bundle Or install it yourself as: $ gem install fog-rackspace ## Usage See https://github.com/fog/fog for usage. fog-rackspace-0.1.6/tests/0000755000004100000410000000000013411315054015412 5ustar www-datawww-datafog-rackspace-0.1.6/tests/helper.rb0000644000004100000410000000143513411315054017221 0ustar www-datawww-databegin require "codeclimate-test-reporter" CodeClimate::TestReporter.start rescue LoadError => e $stderr.puts "not recording test coverage: #{e.inspect}" end require File.expand_path('../../lib/fog/rackspace', __FILE__) Bundler.require(:test) Excon.defaults.merge!(:debug_request => true, :debug_response => true) require File.expand_path(File.join(File.dirname(__FILE__), 'helpers', 'mock_helper')) # This overrides the default 600 seconds timeout during live test runs unless Fog.mocking? Fog.timeout = ENV['FOG_TEST_TIMEOUT'] || 2_000 Fog::Logger.warning "Setting default fog timeout to #{Fog.timeout} seconds" end def lorem_file File.open(File.dirname(__FILE__) + '/lorem.txt', 'r') end def array_differences(array_a, array_b) (array_a - array_b) | (array_b - array_a) end fog-rackspace-0.1.6/tests/helpers/0000755000004100000410000000000013411315054017054 5ustar www-datawww-datafog-rackspace-0.1.6/tests/helpers/collection_helper.rb0000644000004100000410000000502713411315054023077 0ustar www-datawww-datadef collection_tests(collection, params = {}, mocks_implemented = true) tests('success') do tests("#new(#{params.inspect})").succeeds do pending if Fog.mocking? && !mocks_implemented collection.new(params) end tests("#create(#{params.inspect})").succeeds do pending if Fog.mocking? && !mocks_implemented @instance = collection.create(params) end # FIXME: work around for timing issue on AWS describe_instances mocks if Fog.mocking? && @instance.respond_to?(:ready?) @instance.wait_for { ready? } end tests("#all").succeeds do pending if Fog.mocking? && !mocks_implemented collection.all end if !Fog.mocking? || mocks_implemented @identity = @instance.identity end tests("#get(#{@identity})").succeeds do pending if Fog.mocking? && !mocks_implemented collection.get(@identity) end tests('Enumerable') do pending if Fog.mocking? && !mocks_implemented methods = [ 'all?', 'any?', 'find', 'detect', 'collect', 'map', 'find_index', 'flat_map', 'collect_concat', 'group_by', 'none?', 'one?' ] # JRuby 1.7.5+ issue causes a SystemStackError: stack level too deep # https://github.com/jruby/jruby/issues/1265 if RUBY_PLATFORM == "java" and JRUBY_VERSION =~ /1\.7\.[5-8]/ methods.delete('all?') end methods.each do |enum_method| if collection.respond_to?(enum_method) tests("##{enum_method}").succeeds do block_called = false collection.send(enum_method) {|x| block_called = true } block_called end end end [ 'max_by','min_by' ].each do |enum_method| if collection.respond_to?(enum_method) tests("##{enum_method}").succeeds do block_called = false collection.send(enum_method) {|x| block_called = true; 0 } block_called end end end end if block_given? yield(@instance) end if !Fog.mocking? || mocks_implemented @instance.destroy end end tests('failure') do if !Fog.mocking? || mocks_implemented @identity = @identity.to_s @identity = @identity.gsub(/[a-zA-Z]/) { Fog::Mock.random_letters(1) } @identity = @identity.gsub(/\d/) { Fog::Mock.random_numbers(1) } @identity end tests("#get('#{@identity}')").returns(nil) do pending if Fog.mocking? && !mocks_implemented collection.get(@identity) end end end fog-rackspace-0.1.6/tests/helpers/formats_helper_tests.rb0000644000004100000410000000702013411315054023634 0ustar www-datawww-dataShindo.tests('test_helper', 'meta') do tests('comparing welcome data against schema') do data = {:welcome => "Hello" } data_matches_schema(:welcome => String) { data } end tests('#data_matches_schema') do tests('when value matches schema expectation') do data_matches_schema({"key" => String}) { {"key" => "Value"} } end tests('when values within an array all match schema expectation') do data_matches_schema({"key" => [Integer]}) { {"key" => [1, 2]} } end tests('when nested values match schema expectation') do data_matches_schema({"key" => {:nested_key => String}}) { {"key" => {:nested_key => "Value"}} } end tests('when collection of values all match schema expectation') do data_matches_schema([{"key" => String}]) { [{"key" => "Value"}, {"key" => "Value"}] } end tests('when collection is empty although schema covers optional members') do data_matches_schema([{"key" => String}], {:allow_optional_rules => true}) { [] } end tests('when additional keys are passed and not strict') do data_matches_schema({"key" => String}, {:allow_extra_keys => true}) { {"key" => "Value", :extra => "Bonus"} } end tests('when value is nil and schema expects NilClass') do data_matches_schema({"key" => NilClass}) { {"key" => nil} } end tests('when value and schema match as hashes') do data_matches_schema({}) { {} } end tests('when value and schema match as arrays') do data_matches_schema([]) { [] } end tests('when value is a Time') do data_matches_schema({"time" => Time}) { {"time" => Time.now} } end tests('when key is missing but value should be NilClass (#1477)') do data_matches_schema({"key" => NilClass}, {:allow_optional_rules => true}) { {} } end tests('when key is missing but value is nullable (#1477)') do data_matches_schema({"key" => Fog::Nullable::String}, {:allow_optional_rules => true}) { {} } end end tests('#formats backwards compatible changes') do tests('when value matches schema expectation') do formats({"key" => String}) { {"key" => "Value"} } end tests('when values within an array all match schema expectation') do formats({"key" => [Integer]}) { {"key" => [1, 2]} } end tests('when nested values match schema expectation') do formats({"key" => {:nested_key => String}}) { {"key" => {:nested_key => "Value"}} } end tests('when collection of values all match schema expectation') do formats([{"key" => String}]) { [{"key" => "Value"}, {"key" => "Value"}] } end tests('when collection is empty although schema covers optional members') do formats([{"key" => String}]) { [] } end tests('when additional keys are passed and not strict') do formats({"key" => String}, false) { {"key" => "Value", :extra => "Bonus"} } end tests('when value is nil and schema expects NilClass') do formats({"key" => NilClass}) { {"key" => nil} } end tests('when value and schema match as hashes') do formats({}) { {} } end tests('when value and schema match as arrays') do formats([]) { [] } end tests('when value is a Time') do formats({"time" => Time}) { {"time" => Time.now} } end tests('when key is missing but value should be NilClass (#1477)') do formats({"key" => NilClass}) { {} } end tests('when key is missing but value is nullable (#1477)') do formats({"key" => Fog::Nullable::String}) { {} } end end end fog-rackspace-0.1.6/tests/helpers/mock_helper.rb0000644000004100000410000000064513411315054021676 0ustar www-datawww-data# Use so you can run in mock mode from the command line # # FOG_MOCK=true fog if ENV["FOG_MOCK"] == "true" Fog.mock! end # if in mocked mode, fill in some fake credentials for us if Fog.mock? Fog.credentials = { :rackspace_api_key => 'rackspace_api_key', :rackspace_region => 'dfw', :rackspace_username => 'rackspace_username' }.merge(Fog.credentials) end fog-rackspace-0.1.6/tests/helpers/model_helper.rb0000644000004100000410000000141413411315054022040 0ustar www-datawww-datadef model_tests(collection, params = {}, mocks_implemented = true) tests('success') do @instance = collection.new(params) tests("#save").succeeds do pending if Fog.mocking? && !mocks_implemented @instance.save end if block_given? yield(@instance) end tests("#destroy").succeeds do pending if Fog.mocking? && !mocks_implemented @instance.destroy end end end # Generates a unique identifier with a random differentiator. # Useful when rapidly re-running tests, so we don't have to wait # serveral minutes for deleted objects to disappear from the API # E.g. 'fog-test-1234' def uniq_id(base_name = 'fog-test') # random_differentiator suffix = rand(65536).to_s(16).rjust(4, '0') [base_name, suffix] * '-' end fog-rackspace-0.1.6/tests/helpers/formats_helper.rb0000644000004100000410000000705613411315054022423 0ustar www-datawww-datarequire "fog/schema/data_validator" # format related hackery # allows both true.is_a?(Fog::Boolean) and false.is_a?(Fog::Boolean) # allows both nil.is_a?(Fog::Nullable::String) and ''.is_a?(Fog::Nullable::String) module Fog module Boolean; end module Nullable module Boolean; end module Integer; end module String; end module Time; end module Float; end module Hash; end module Array; end end end [FalseClass, TrueClass].each {|klass| klass.send(:include, Fog::Boolean)} [FalseClass, TrueClass, NilClass, Fog::Boolean].each {|klass| klass.send(:include, Fog::Nullable::Boolean)} [NilClass, String].each {|klass| klass.send(:include, Fog::Nullable::String)} [NilClass, Time].each {|klass| klass.send(:include, Fog::Nullable::Time)} [Integer, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Integer)} [Float, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Float)} [Hash, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Hash)} [Array, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Array)} module Shindo class Tests # Generates a Shindo test that compares a hash schema to the result # of the passed in block returning true if they match. # # The schema that is passed in is a Hash or Array of hashes that # have Classes in place of values. When checking the schema the # value should match the Class. # # Strict mode will fail if the data has additional keys. Setting # +strict+ to +false+ will allow additional keys to appear. # # @param [Hash] schema A Hash schema # @param [Hash] options Options to change validation rules # @option options [Boolean] :allow_extra_keys # If +true+ does not fail when keys are in the data that are # not specified in the schema. This allows new values to # appear in API output without breaking the check. # @option options [Boolean] :allow_optional_rules # If +true+ does not fail if extra keys are in the schema # that do not match the data. Not recommended! # @yield Data to check with schema # # @example Using in a test # Shindo.tests("comparing welcome data against schema") do # data = {:welcome => "Hello" } # data_matches_schema(:welcome => String) { data } # end # # comparing welcome data against schema # + data matches schema # # @example Example schema # { # "id" => String, # "ram" => Integer, # "disks" => [ # { # "size" => Float # } # ], # "dns_name" => Fog::Nullable::String, # "active" => Fog::Boolean, # "created" => DateTime # } # # @return [Boolean] def data_matches_schema(schema, options = {}) test('data matches schema') do validator = Fog::Schema::DataValidator.new valid = validator.validate(yield, schema, options) @message = validator.message unless valid valid end end # @deprecated #formats is deprecated. Use #data_matches_schema instead def formats(format, strict = true) test('has proper format') do if strict options = {:allow_extra_keys => false, :allow_optional_rules => true} else options = {:allow_extra_keys => true, :allow_optional_rules => true} end validator = Fog::Schema::DataValidator.new valid = validator.validate(yield, format, options) @message = validator.message unless valid valid end end end end fog-rackspace-0.1.6/tests/helpers/compute/0000755000004100000410000000000013411315054020530 5ustar www-datawww-datafog-rackspace-0.1.6/tests/helpers/compute/flavors_helper.rb0000644000004100000410000000146313411315054024074 0ustar www-datawww-datadef flavors_tests(connection, params = {}, mocks_implemented = true) tests('success') do tests("#all").succeeds do pending if Fog.mocking? && !mocks_implemented connection.flavors.all end if !Fog.mocking? || mocks_implemented @identity = connection.flavors.first.identity end tests("#get('#{@identity}')").succeeds do pending if Fog.mocking? && !mocks_implemented connection.flavors.get(@identity) end end tests('failure') do if !Fog.mocking? || mocks_implemented invalid_flavor_identity = connection.flavors.first.identity.to_s.gsub(/\w/, '0') end tests("#get('#{invalid_flavor_identity}')").returns(nil) do pending if Fog.mocking? && !mocks_implemented connection.flavors.get(invalid_flavor_identity) end end end fog-rackspace-0.1.6/tests/helpers/compute/servers_helper.rb0000644000004100000410000000041013411315054024100 0ustar www-datawww-datadef servers_tests(connection, params = {}, mocks_implemented = true) collection_tests(connection.servers, params, mocks_implemented) do if !Fog.mocking? || mocks_implemented @instance.wait_for { ready? } yield if block_given? end end end fog-rackspace-0.1.6/tests/helpers/compute/server_helper.rb0000644000004100000410000000124613411315054023725 0ustar www-datawww-datadef server_tests(connection, params = {}, mocks_implemented = true) model_tests(connection.servers, params, mocks_implemented) do tests('#reload').returns(true) do pending if Fog.mocking? && !mocks_implemented @instance.wait_for { ready? } identity = @instance.identity !identity.nil? && identity == @instance.reload.identity end responds_to([:ready?, :state]) yield if block_given? tests('#reboot').succeeds do pending if Fog.mocking? && !mocks_implemented @instance.wait_for { ready? } @instance.reboot end if !Fog.mocking? || mocks_implemented @instance.wait_for { ready? } end end end fog-rackspace-0.1.6/tests/helpers/succeeds_helper.rb0000644000004100000410000000020613411315054022534 0ustar www-datawww-datamodule Shindo class Tests def succeeds test('succeeds') do !!instance_eval(&Proc.new) end end end end fog-rackspace-0.1.6/tests/helpers/responds_to_helper.rb0000644000004100000410000000037413411315054023303 0ustar www-datawww-datamodule Shindo class Tests def responds_to(method_names) for method_name in [*method_names] tests("#respond_to?(:#{method_name})").returns(true) do @instance.respond_to?(method_name) end end end end end fog-rackspace-0.1.6/tests/helpers/schema_validator_tests.rb0000644000004100000410000000723113411315054024133 0ustar www-datawww-dataShindo.tests('Fog::Schema::DataValidator', 'meta') do validator = Fog::Schema::DataValidator.new tests('#validate') do tests('returns true') do returns(true, 'when value matches schema expectation') do validator.validate({"key" => "Value"}, {"key" => String}) end returns(true, 'when values within an array all match schema expectation') do validator.validate({"key" => [1, 2]}, {"key" => [Integer]}) end returns(true, 'when nested values match schema expectation') do validator.validate({"key" => {:nested_key => "Value"}}, {"key" => {:nested_key => String}}) end returns(true, 'when collection of values all match schema expectation') do validator.validate([{"key" => "Value"}, {"key" => "Value"}], [{"key" => String}]) end returns(true, 'when collection is empty although schema covers optional members') do validator.validate([], [{"key" => String}]) end returns(true, 'when additional keys are passed and not strict') do validator.validate({"key" => "Value", :extra => "Bonus"}, {"key" => String}, {:allow_extra_keys => true}) end returns(true, 'when value is nil and schema expects NilClass') do validator.validate({"key" => nil}, {"key" => NilClass}) end returns(true, 'when value and schema match as hashes') do validator.validate({}, {}) end returns(true, 'when value and schema match as arrays') do validator.validate([], []) end returns(true, 'when value is a Time') do validator.validate({"time" => Time.now}, {"time" => Time}) end returns(true, 'when key is missing but value should be NilClass (#1477)') do validator.validate({}, {"key" => NilClass}, {:allow_optional_rules => true}) end returns(true, 'when key is missing but value is nullable (#1477)') do validator.validate({}, {"key" => Fog::Nullable::String}, {:allow_optional_rules => true}) end end tests('returns false') do returns(false, 'when value does not match schema expectation') do validator.validate({"key" => nil}, {"key" => String}) end returns(false, 'when key formats do not match') do validator.validate({"key" => "Value"}, {:key => String}) end returns(false, 'when additional keys are passed and strict') do validator.validate({"key" => "Missing"}, {}) end returns(false, 'when some keys do not appear') do validator.validate({}, {"key" => String}) end returns(false, 'when collection contains a member that does not match schema') do validator.validate([{"key" => "Value"}, {"key" => 5}], [{"key" => String}]) end returns(false, 'when collection has multiple schema patterns') do validator.validate([{"key" => "Value"}], [{"key" => Integer}, {"key" => String}]) end returns(false, 'when hash and array are compared') do validator.validate({}, []) end returns(false, 'when array and hash are compared') do validator.validate([], {}) end returns(false, 'when a hash is expected but another data type is found') do validator.validate({"key" => {:nested_key => []}}, {"key" => {:nested_key => {}}}) end returns(false, 'when key is missing but value should be NilClass (#1477)') do validator.validate({}, {"key" => NilClass}, {:allow_optional_rules => false}) end returns(false, 'when key is missing but value is nullable (#1477)') do validator.validate({}, {"key" => Fog::Nullable::String}, {:allow_optional_rules => false}) end end end end fog-rackspace-0.1.6/tests/rackspace/0000755000004100000410000000000013411315054017346 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/0000755000004100000410000000000013411315054021221 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/identity/0000755000004100000410000000000013411315054023052 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/identity/token_tests.rb0000644000004100000410000000347313411315054025750 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity | tokens', ['rackspace']) do ROLE_FORMAT = { 'id' => String, 'name' => String, 'description' => String } ENDPOINT_FORMAT = { 'tenantId' => String, 'publicURL' => Fog::Nullable::String, 'internalURL' => Fog::Nullable::String, 'region' => Fog::Nullable::String, 'versionId' => Fog::Nullable::String, 'versionInfo' => Fog::Nullable::String, 'versionList' => Fog::Nullable::String } SERVICE_FORMAT = { 'name' => String, 'type' => String, 'endpoints' => [ENDPOINT_FORMAT] } ACCESS_FORMAT = { 'access' => { 'token' => { 'id' => String, 'expires' => String, 'tenant' => { 'id' => String, 'name' => String } }, 'user' => { 'id' => String, 'name' => String, 'roles' => [ROLE_FORMAT] }, 'serviceCatalog' => [SERVICE_FORMAT] } } service = Fog::Rackspace::Identity.new tests('success') do credentials = Fog.credentials username = credentials[:rackspace_username] api_key = credentials[:rackspace_api_key] tests('#create_token').formats(ACCESS_FORMAT) do service.create_token(username, api_key).body end tests('uses connection options').returns(true) do pending if Fog.mocking? identity_service = Fog::Rackspace::Identity.new(:connection_options => { :ssl_verify_peer => true }) connection = identity_service.instance_variable_get("@connection") excon = connection.instance_variable_get("@excon") data = excon.instance_variable_get("@data") data.key?(:ssl_verify_peer) end end tests('failure') do tests('#create_token(invalidname, invalidkey').raises(Excon::Errors::HTTPStatusError) do service.create_token('baduser', 'badkey') end end end fog-rackspace-0.1.6/tests/rackspace/requests/identity/tenants_tests.rb0000644000004100000410000000070513411315054026277 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity | tenants', ['rackspace']) do pending if Fog.mock? TENANTS_FORMATS = { 'tenants' => [{ 'id' => String, 'name' => String, 'description' => Fog::Nullable::String, 'enabled' => Fog::Nullable::Boolean }] } service = Fog::Rackspace::Identity.new tests('success') do tests('#list_tenants').formats(TENANTS_FORMATS) do service.list_tenants().body end end end fog-rackspace-0.1.6/tests/rackspace/requests/identity/user_tests.rb0000644000004100000410000000526313411315054025605 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity | users', ['rackspace']) do pending if Fog.mock? USER_INFO = { 'id' => String, 'username' => String, 'email' => Fog::Nullable::String, 'enabled' => Fog::Boolean, 'OS-KSADM:password' => Fog::Nullable::String, 'created' => Fog::Nullable::String, 'updated' => Fog::Nullable::String } USER_FORMAT = { 'user' => USER_INFO } USERS_FORMAT = { 'users' => [USER_INFO] } CREDENTIAL_FORMAT = { 'RAX-KSKEY:apiKeyCredentials' => { 'username' => String, 'apiKey' => String } } CREDENTIALS_FORMAT = { 'credentials' => [CREDENTIAL_FORMAT] } ROLES_FORMAT = { 'roles' => [{ 'id' => String, 'name' => String, 'description' => String }] } service = Fog::Rackspace::Identity.new id = nil username = "fog#{Time.now.to_i.to_s}" email = 'fog_user@example.com' enabled = true password = 'Fog_password1' tests('success') do tests('#create_user').formats(USER_FORMAT) do data = service.create_user(username, email, enabled).body id = data['user']['id'] data end tests('#delete_user').succeeds do service.delete_user(id) end # there appears to be a werid caching issue. It's just easier to create a new username and continue on username = "fog#{Time.now.to_i.to_s}" tests('#create_user with password').succeeds do data = service.create_user(username, email, enabled, :password => password ).body id = data['user']['id'] data end tests('#get_user_by_name').formats(USER_FORMAT) do data = service.get_user_by_name(username).body id = data['user']['id'] data end tests('#get_user_by_id').formats(USER_FORMAT) do service.get_user_by_id(id).body end tests('#list_users').formats(USERS_FORMAT) do service.list_users().body end tests('#update_user').formats(USER_FORMAT) do service.update_user(id, username, 'updated_user@example.com', enabled).body end tests('#update_user with password').succeeds do service.update_user(id, username, email, enabled, :password => password).body end tests('#list_user_roles').formats(ROLES_FORMAT) do service.list_user_roles(id).body end service.delete_user(id) # Users are only authorized to request their own credentials, # so perform credential tests with the ID of the user running tests. credential_username = Fog.credentials[:rackspace_username] credential_id = service.get_user_by_name(credential_username).body['user']['id'] tests('#list_credentials').formats(CREDENTIALS_FORMAT) do service.list_credentials(credential_id).body end end end fog-rackspace-0.1.6/tests/rackspace/requests/cdn/0000755000004100000410000000000013411315054021765 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/cdn/cdn_tests.rb0000644000004100000410000000436413411315054024307 0ustar www-datawww-dataShindo.tests('Fog::CDN[:rackspace] | CDN requests', ['rackspace']) do @container_format = [String] @containers_format = [{ "cdn_ios_uri" => String, "log_retention" => Fog::Boolean, "ttl" => Fixnum, "cdn_streaming_uri" => String, "cdn_enabled" => Fog::Boolean, "name" => String, "cdn_ssl_uri" => String, "cdn_uri" => String }] @container_headers = { "Content-Length" => String, "X-Cdn-Enabled" => String, "X-Log-Retention" => String, "X-Cdn-Ios-Uri" => String, "X-Ttl" => String, "X-Cdn-Uri" => String, "X-Cdn-Ssl-Uri" => String, "X-Cdn-Streaming-Uri" => String, "X-Trans-Id" => String, "Date" => String } begin unless Fog.mocking? @directory = Fog::Storage[:rackspace].directories.create(:key => 'fogcontainertests') @file = @directory.files.create(:key => 'fog_object', :body => lorem_file) end tests('success') do tests("#put_container('fogcontainertests')").succeeds do Fog::CDN[:rackspace].put_container('fogcontainertests', {'X-CDN-Enabled' => true }) end tests("#get_containers").formats(@containers_format) do Fog::CDN[:rackspace].get_containers.body end tests("#head_container('fogcontainertests')").formats(@container_headers) do Fog::CDN[:rackspace].head_container('fogcontainertests').headers end tests("#post_container('fogcontainertests')").succeeds do Fog::CDN[:rackspace].post_container('fogcontainertests', 'X-TTL' => 5000) end #NOTE: you are only allow 25 object purges per day. If this fails, you may be over the limit tests("#delete_object('fog_object')").succeeds do Fog::CDN[:rackspace].delete_object('fogcontainertests', 'fog_object') end end ensure unless Fog.mocking? @file.destroy if @file @directory.destroy if @directory end end tests('failure') do tests("#head_container('missing_container')").raises(Fog::Storage::Rackspace::NotFound) do Fog::CDN[:rackspace].head_container('missing_container') end tests("#post_container('missing_container')").raises(Fog::Storage::Rackspace::NotFound) do Fog::CDN[:rackspace].post_container('missing_container', 'X-TTL' => 5000) end end end fog-rackspace-0.1.6/tests/rackspace/requests/dns/0000755000004100000410000000000013411315054022005 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/dns/helper.rb0000644000004100000410000000562013411315054023614 0ustar www-datawww-dataSUBDOMAIN_FORMAT = { 'name' => String, 'id' => Integer, 'created' => String, 'updated' => String, 'emailAddress' => String } DOMAIN_FORMAT = SUBDOMAIN_FORMAT.merge({ 'accountId' => Integer }) LIST_SUBDOMAINS_FORMAT = { 'domains' => [SUBDOMAIN_FORMAT], 'totalEntries' => Integer } LIST_DOMAIN_FORMAT = { 'domains' => [DOMAIN_FORMAT], 'totalEntries' => Integer, 'links' => [ { 'rel' => String, 'href' => String } ] } RECORD_FORMAT = { 'name' => String, 'id' => String, 'type' => String, 'data' => String, 'updated' => String, 'created' => String, 'ttl' => Integer, 'priority' => Fog::Nullable::Integer } RECORD_LIST_FORMAT = { 'records' => [RECORD_FORMAT], #In some cases this is returned (domain details) and in some cases it isn't (create domain). Marking as nullable. 'totalEntries' => Fog::Nullable::Integer } NAME_SERVERS_FORMAT = [{ 'name' => String }] BASIC_DOMAIN_DETAIL_FORMAT = DOMAIN_FORMAT.merge({ 'nameservers' => NAME_SERVERS_FORMAT, 'ttl' => Integer }) LIST_DOMAIN_DETAILS_WITH_RECORDS = BASIC_DOMAIN_DETAIL_FORMAT.merge({ 'recordsList' => RECORD_LIST_FORMAT }) LIST_DOMAIN_DETAILS_WITH_RECORDS_AND_SUBDOMAINS_FORMAT = BASIC_DOMAIN_DETAIL_FORMAT.merge({ 'recordsList' => RECORD_LIST_FORMAT, 'subdomains' => { 'domains' => [SUBDOMAIN_FORMAT], 'totalEntries' => Integer } }) LIST_DOMAIN_DETAILS_WITHOUT_RECORDS_AND_SUBDOMAINS_FORMAT = BASIC_DOMAIN_DETAIL_FORMAT CREATE_DOMAINS_FORMAT = { 'domains' => [ BASIC_DOMAIN_DETAIL_FORMAT.merge({ 'recordsList' => RECORD_LIST_FORMAT }) ] } def wait_for(service, response) job_id = response.body['jobId'] Fog.wait_for do response = service.callback(job_id) response.body['status'] != 'RUNNING' end response end def domain_tests(service, domain_attributes) tests("create_domains([#{domain_attributes}])").formats(CREATE_DOMAINS_FORMAT) do response = wait_for service, service.create_domains([domain_attributes]) @domain_details = response.body['response']['domains'] @domain_id = @domain_details[0]['id'] response.body['response'] end begin if block_given? yield end ensure tests("remove_domain('#{@domain_id}')").succeeds do wait_for service, service.remove_domain(@domain_id) end end end def domains_tests(service, domains_attributes, custom_delete = false) tests("create_domains(#{domains_attributes})").formats(CREATE_DOMAINS_FORMAT) do response = wait_for service, service.create_domains(domains_attributes) @domain_details = response.body['response']['domains'] @domain_ids = @domain_details.map { |domain| domain['id'] } response.body['response'] end begin if block_given? yield end ensure if !custom_delete tests("remove_domains(#{@domain_ids})").succeeds do wait_for service, service.remove_domains(@domain_ids) end end end end fog-rackspace-0.1.6/tests/rackspace/requests/dns/dns_tests.rb0000644000004100000410000001256413411315054024350 0ustar www-datawww-dataShindo.tests('Fog::DNS[:rackspace] | DNS requests', ['rackspace', 'dns']) do pending if Fog.mocking? domain_name = uniq_id + '.com' tests('success on simple domain') do domain_tests(Fog::DNS[:rackspace], {:name => domain_name, :email => 'hostmaster@' + domain_name, :records => [{:ttl => 300, :name => domain_name, :type => 'A', :data => '192.168.1.1'}]}) do tests('list_domains').formats(LIST_DOMAIN_FORMAT.reject {|key,value| key == 'links'}) do Fog::DNS[:rackspace].list_domains.body end tests("list_domains :limit => 5, :offset => 10, :domain => #{@domain_details.first['name']} --> All possible attributes").formats(LIST_DOMAIN_FORMAT) do Fog::DNS[:rackspace].list_domains(:limit => 5, :offset => 10, :domain => @domain_details.first['name']).body end tests("list_domain_details('#{@domain_id}')").formats(LIST_DOMAIN_DETAILS_WITH_RECORDS) do Fog::DNS[:rackspace].list_domain_details(@domain_id).body end tests("modify_domain('#{@domain_id}', :ttl => 500, :comment => 'woot', :email => 'randomemail@randomhost.com')").succeeds do response = Fog::DNS[:rackspace].modify_domain @domain_id, :ttl => 500, :comment => 'woot', :email => 'randomemail@randomhost.com' wait_for Fog::DNS[:rackspace], response end end end tests('success for domain with multiple records') do domain_tests(Fog::DNS[:rackspace], { :name => domain_name, :email => 'hostmaster@' + domain_name, :records => [ { :ttl => 300, :name => domain_name, :type => 'A', :data => '192.168.1.1' }, { :ttl => 3600, :name => domain_name, :type => 'MX', :data => 'mx.' + domain_name, :priority => 10 } ] }) end tests('success for multiple domains') do domain1_name = uniq_id + '-1.com' domain2_name = uniq_id + '-2.com' domains_tests(Fog::DNS[:rackspace], [ {:name => domain1_name, :email => 'hostmaster@' + domain1_name, :records => [{:ttl => 300, :name => domain1_name, :type => 'A', :data => '192.168.1.1'}]}, {:name => domain2_name, :email => 'hostmaster@' + domain2_name, :records => [{:ttl => 300, :name => domain2_name, :type => 'A', :data => '192.168.1.1'}]} ]) end tests('success for domain with subdomain') do domains_tests(Fog::DNS[:rackspace], [ {:name => domain_name, :email => 'hostmaster@' + domain_name, :records => [{:ttl => 300, :name => domain_name, :type => 'A', :data => '192.168.1.1'}]}, {:name => 'subdomain.' + domain_name, :email => 'hostmaster@subdomain.' + domain_name, :records => [{:ttl => 300, :name =>'subdomain.' + domain_name, :type => 'A', :data => '192.168.1.1'}]} ], true) do @root_domain_id = @domain_details.find { |domain| domain['name'] == domain_name }['id'] tests("list_domain_details('#{@root_domain_id}', :show_records => false, :show_subdomains => false)") do response = Fog::DNS[:rackspace].list_domain_details(@root_domain_id, :show_records => false, :show_subdomains => false) formats(LIST_DOMAIN_DETAILS_WITHOUT_RECORDS_AND_SUBDOMAINS_FORMAT) { response.body } returns(nil) { response.body['recordsList'] } returns(nil) { response.body['subdomains'] } end tests("list_domain_details('#{@root_domain_id}', :show_records => true, :show_subdomains => true)") do response = Fog::DNS[:rackspace].list_domain_details(@root_domain_id, :show_records => true, :show_subdomains => true) formats(LIST_DOMAIN_DETAILS_WITH_RECORDS_AND_SUBDOMAINS_FORMAT) { response.body } returns(false) { response.body['recordsList'].nil? } returns(false) { response.body['subdomains'].nil? } end tests("list_subdomains('#{@root_domain_id}')").formats(LIST_SUBDOMAINS_FORMAT) do Fog::DNS[:rackspace].list_subdomains(@root_domain_id).body end tests("remove_domain('#{@root_domain_id}', :delete_subdomains => true)") do wait_for Fog::DNS[:rackspace], Fog::DNS[:rackspace].remove_domain(@root_domain_id, :delete_subdomains => true) test('domain and subdomains were really deleted') do (Fog::DNS[:rackspace].list_domains.body['domains'].map { |domain| domain['name'] } & [domain_name, 'subdomain.' + domain_name]).empty? end end end end tests( 'failure') do tests('create_domain(invalid)').returns('ERROR') do response = wait_for Fog::DNS[:rackspace], Fog::DNS[:rackspace].create_domains([{:name => 'badtestdomain.com', :email => '', :records => [{:ttl => 300, :name => 'badtestdomain.com', :type => 'A', :data => '192.168.1.1'}]}]) response.body['status'] end tests('list_domains :limit => 5, :offset => 8').raises(Fog::Rackspace::Errors::BadRequest) do Fog::DNS[:rackspace].list_domains :limit => 5, :offset => 8 end tests('list_domain_details 34335353').raises(Fog::DNS::Rackspace::NotFound) do Fog::DNS[:rackspace].list_domain_details 34335353 end #tests('create_domains(#{domains})').raises(Fog::Rackspace::Errors::Conflict) do # wait_for Fog::DNS[:rackspace].create_domains(domains) #end #tests('remove_domain(34343435)').raises(Fog::DNS::Rackspace::DeleteFault) do # Fog::DNS[:rackspace].remove_domain 34343435 #end end end fog-rackspace-0.1.6/tests/rackspace/requests/dns/records_tests.rb0000644000004100000410000000712013411315054025215 0ustar www-datawww-dataShindo.tests('Fog::DNS[:rackspace] | dns records requests', ['rackspace', 'dns']) do pending if Fog.mocking? domain_name = uniq_id + '.com' domain_tests(Fog::DNS[:rackspace], {:name => domain_name, :email => 'hostmaster@' + domain_name, :records => [{:ttl => 300, :name => domain_name, :type => 'A', :data => '192.168.1.1'}]}) do tests('success on single record') do tests("list_records(#{@domain_id})").formats(RECORD_LIST_FORMAT) do Fog::DNS[:rackspace].list_records(@domain_id).body end tests("add_records(#{@domain_id}, [{ :name => 'test1.#{domain_name}', :type => 'A', :data => '192.168.2.1', :ttl => 550}])").formats(RECORD_LIST_FORMAT) do response = wait_for Fog::DNS[:rackspace], Fog::DNS[:rackspace].add_records(@domain_id, [{ :name => 'test1.' + domain_name, :type => 'A', :data => '192.168.2.1', :ttl => 550}]) @record_id = response.body['response']['records'].first['id'] response.body['response'] end tests("list_record_details(#{@domain_id}, #{@record_id})").formats(RECORD_FORMAT) do Fog::DNS[:rackspace].list_record_details(@domain_id, @record_id).body end tests("modify_record(#{@domain_id}, #{@record_id}, { :ttl => 500, :name => 'test2.#{domain_name}', :data => '192.168.3.1' })").succeeds do wait_for Fog::DNS[:rackspace], Fog::DNS[:rackspace].modify_record(@domain_id, @record_id, { :ttl => 500, :name => 'test2.' + domain_name, :data => '192.168.3.1' }) end tests("remove_record(#{@domain_id}, #{@record_id})").succeeds do wait_for Fog::DNS[:rackspace], Fog::DNS[:rackspace].remove_record(@domain_id, @record_id) end end tests('success on multiple records') do records_attributes = [ { :name => 'test1.' + domain_name, :type => 'A', :data => '192.168.2.1'}, { :name => domain_name, :type => 'MX', :priority => 10, :data => 'mx.' + domain_name} ] tests("add_records(#{@domain_id}, #{records_attributes})").formats(RECORD_LIST_FORMAT) do response = wait_for Fog::DNS[:rackspace], Fog::DNS[:rackspace].add_records(@domain_id, records_attributes) @record_ids = response.body['response']['records'].map { |record| record['id'] } response.body['response'] end tests("remove_records(#{@domain_id}, #{@record_ids})").succeeds do wait_for Fog::DNS[:rackspace], Fog::DNS[:rackspace].remove_records(@domain_id, @record_ids) end end tests( 'failure') do tests("list_records('')").raises(ArgumentError) do Fog::DNS[:rackspace].list_records('') end tests("list_records('abc')").raises(Fog::DNS::Rackspace::NotFound) do Fog::DNS[:rackspace].list_records('abc') end tests("list_record_details(#{@domain_id}, '')").raises(ArgumentError) do Fog::DNS[:rackspace].list_record_details(@domain_id, '') end tests("list_record_details(#{@domain_id}, 'abc')").raises(Fog::DNS::Rackspace::NotFound) do Fog::DNS[:rackspace].list_record_details(@domain_id, 'abc') end tests("remove_record(#{@domain_id}, '')").raises(ArgumentError) do Fog::DNS[:rackspace].remove_record(@domain_id, '') end tests("remove_record(#{@domain_id}, 'abc')").raises(Fog::DNS::Rackspace::NotFound) do Fog::DNS[:rackspace].remove_record(@domain_id, 'abc') end tests("add_record(#{@domain_id}, [{ :name => '', :type => '', :data => ''}])").raises(Fog::Rackspace::Errors::BadRequest) do Fog::DNS[:rackspace].add_records(@domain_id, [{ :name => '', :type => '', :data => ''}]) end end end end fog-rackspace-0.1.6/tests/rackspace/requests/databases/0000755000004100000410000000000013411315054023150 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/databases/database_tests.rb0000644000004100000410000000241113411315054026461 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Database | database_tests', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new instance_name = 'fog' + Time.now.to_i.to_s begin @instance_id = service.create_instance(instance_name, 1, 1).body['instance']['id'] wait_for_request("waiting for database to be created") do service.get_instance(@instance_id).body["instance"]["status"] == 'ACTIVE' end tests('success') do database_name = 'fogdb' + Time.now.to_i.to_s tests("#create_database(#{@instance_id}, #{database_name})").returns(202) do service.create_database(@instance_id, database_name).status end tests("#list_databases{#{@instance_id})").formats(LIST_DATABASES_FORMAT) do service.list_databases(@instance_id).body end tests("#delete_database(#{@instance_id}, #{database_name})").returns(202) do service.delete_database(@instance_id, database_name).status end end tests('failure') do tests("#create_database(#{@instance_id}, '') => Invalid Create Critera").raises(Fog::Rackspace::Databases::BadRequest) do service.create_database(@instance_id, '') end end ensure service.delete_instance(@instance_id) if @instance_id end end fog-rackspace-0.1.6/tests/rackspace/requests/databases/helper.rb0000644000004100000410000000226713411315054024763 0ustar www-datawww-dataFLAVOR_FORMAT = { 'id' => Integer, 'name' => String, 'ram' => Integer, 'links' => LINKS_FORMAT } GET_FLAVOR_FORMAT = { 'flavor' => FLAVOR_FORMAT } LIST_FLAVORS_FORMAT = { 'flavors' => [FLAVOR_FORMAT] } INSTANCE_FORMAT = { 'id' => String, 'name' => String, 'status' => String, 'links' => LINKS_FORMAT, 'flavor' => { 'id' => String, 'links' => LINKS_FORMAT }, 'volume' => { 'size' => Integer } } INSTANCE_DETAILS_FORMAT = INSTANCE_FORMAT.merge({ 'created' => String, 'updated' => String, 'hostname' => String, }) CREATE_INSTANCE_FORMAT = { 'instance' => INSTANCE_DETAILS_FORMAT } GET_INSTANCE_FORMAT = { 'instance' => INSTANCE_DETAILS_FORMAT.merge({ 'volume' => { 'size' => Integer, 'used' => Float } }) } LIST_INSTANCES_FORMAT = { 'instances' => [ INSTANCE_FORMAT ] } CHECK_ROOT_USER_FORMAT = { 'rootEnabled' => Fog::Boolean } ENABLE_ROOT_USER_FORMAT = { 'user' => { 'name' => String, 'password' => String } } LIST_DATABASES_FORMAT = { 'databases' => [{ 'name' => String }] } LIST_USERS_FORMAT = { 'users' => [{ 'name' => String, 'databases' => [{ 'name' => String }] }] } fog-rackspace-0.1.6/tests/rackspace/requests/databases/instance_tests.rb0000644000004100000410000000423313411315054026525 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Database | instance_tests', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new tests('success') do instance_id = nil instance_name = 'fog' + Time.now.to_i.to_s tests("#list_instances").formats(LIST_INSTANCES_FORMAT) do service.list_instances.body end tests("#create_instance(#{instance_name}, 1, 1)").formats(CREATE_INSTANCE_FORMAT) do data = service.create_instance(instance_name, 1, 1).body instance_id = data['instance']['id'] data end until service.get_instance(instance_id).body["instance"]["status"] == 'ACTIVE' sleep 10 end tests("#get_instance(#{instance_id})").formats(GET_INSTANCE_FORMAT) do service.get_instance(instance_id).body end tests("#check_root_user(#{instance_id})").formats(CHECK_ROOT_USER_FORMAT) do service.check_root_user(instance_id).body end tests("#enable_root_user(#{instance_id})").formats(ENABLE_ROOT_USER_FORMAT) do service.enable_root_user(instance_id).body end tests("#restart_instance(#{instance_id})").succeeds do service.restart_instance(instance_id) end until service.get_instance(instance_id).body["instance"]["status"] == 'ACTIVE' sleep 10 end tests("#resize_instance(#{instance_id}, 2)").succeeds do service.resize_instance(instance_id, 2) end until service.get_instance(instance_id).body["instance"]["status"] == 'ACTIVE' sleep 10 end tests("#resize_instance_volume(#{instance_id}, 2)").succeeds do service.resize_instance_volume(instance_id, 2) end until service.get_instance(instance_id).body["instance"]["status"] == 'ACTIVE' sleep 10 end tests("#delete_instance(#{instance_id})").succeeds do service.delete_instance(instance_id) end end tests('failure') do tests("#create_instance('', 0, 0) => Invalid Create Critera").raises(Fog::Rackspace::Databases::BadRequest) do service.create_instance('', 0, 0) end tests("#get_instance('') => Does not exist").raises(Fog::Rackspace::Databases::NotFound) do service.get_instance('') end end end fog-rackspace-0.1.6/tests/rackspace/requests/databases/flavor_tests.rb0000644000004100000410000000060213411315054026206 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Database | flavor_tests', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new tests('success') do tests('#list_flavors_details').formats(LIST_FLAVORS_FORMAT) do service.list_flavors().body end tests('#get_flavor(1)').formats(GET_FLAVOR_FORMAT) do service.get_flavor(1).body end end end fog-rackspace-0.1.6/tests/rackspace/requests/databases/user_tests.rb0000644000004100000410000000224613411315054025701 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Database | user_tests', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new instance_name = 'fog' + Time.now.to_i.to_s instance_id = service.create_instance(instance_name, 1, 1).body['instance']['id'] wait_for_request("Waiting for database to be created") do service.get_instance(instance_id).body["instance"]["status"] == 'ACTIVE' end tests('success') do user_name = 'fog' + Time.now.to_i.to_s password = 'password1' tests("#create_user(#{instance_id}, #{user_name}, #{password})").returns(202) do service.create_user(instance_id, user_name, password).status end tests("#list_users{#{instance_id})").formats(LIST_USERS_FORMAT) do service.list_users(instance_id).body end tests("#delete_user(#{instance_id}, #{user_name})").returns(202) do service.delete_user(instance_id, user_name).status end end tests('failure') do tests("#create_user(#{instance_id}, '', '') => Invalid Create Critera").raises(Fog::Rackspace::Databases::BadRequest) do service.create_user(instance_id, '', '') end end service.delete_instance(instance_id) end fog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/0000755000004100000410000000000013411315054023304 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/image_tests.rb0000644000004100000410000000431213411315054026135 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | image_tests', ['rackspace']) do service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') image_format = { 'id' => String, 'name' => String, 'created' => Fog::Nullable::String, 'updated' => Fog::Nullable::String, 'status' => Fog::Nullable::String, 'user_id' => Fog::Nullable::String, 'tenant_id' => Fog::Nullable::String, 'progress' => Fog::Nullable::Integer, 'minDisk' => Fog::Nullable::Integer, 'minRam' => Fog::Nullable::Integer, 'metadata' => Fog::Nullable::Hash, 'OS-DCF:diskConfig' => Fog::Nullable::String, 'links' => [{ 'rel' => String, 'href' => String, 'type' => Fog::Nullable::String }] } list_image_format = { 'images' => [image_format] } get_image_format = { 'image' => image_format } begin test_time = Time.now.to_i.to_s @server = service.servers.create(:name => "fog-image-tests_#{test_time}", :flavor_id => rackspace_test_flavor_id(service), :image_id => rackspace_test_image_id(service)) @server.wait_for { ready? } @image_id = nil tests('success') do tests("#create_image(#{@server.id}, 'fog-test-image')").succeeds do response = service.create_image(@server.id, "fog-test-image_#{test_time}") @image_id = response.headers["Location"].match(/\/([^\/]+$)/)[1] end tests('#list_images').formats(list_image_format) do service.list_images.body end tests('#list_images_detail').formats(list_image_format) do service.list_images_detail.body end tests('#get_image').formats(get_image_format, false) do service.get_image(@image_id).body end tests('#delete_image').succeeds do service.delete_image(@image_id) end end tests('failure') do tests('#delete_image').raises(Fog::Compute::RackspaceV2::NotFound) do service.delete_image(Fog::Rackspace::MockData::NOT_FOUND_ID) end tests('#get_image').raises(Fog::Compute::RackspaceV2::NotFound) do service.get_image(Fog::Rackspace::MockData::NOT_FOUND_ID) end end ensure @image.destroy if @image @server.destroy if @server end end fog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/server_tests.rb0000644000004100000410000001403713411315054026366 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | server_tests', ['rackspace']) do service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') link_format = { 'href' => String, 'rel' => String } server_format = { 'id' => String, 'name' => String, 'hostId' => Fog::Nullable::String, 'created' => Fog::Nullable::String, 'updated' => Fog::Nullable::String, 'status' => Fog::Nullable::String, 'progress' => Fog::Nullable::Integer, 'user_id' => Fog::Nullable::String, 'tenant_id' => Fog::Nullable::String, 'links' => [link_format], 'metadata' => Fog::Nullable::Hash } list_servers_format = { 'servers' => [server_format] } get_server_format = { 'server' => server_format.merge({ 'accessIPv4' => String, 'accessIPv6' => String, 'OS-DCF:diskConfig' => String, 'rax-bandwidth:bandwidth' => Fog::Nullable::Array, 'addresses' => Fog::Nullable::Hash, 'flavor' => { 'id' => String, 'links' => [link_format] }, 'image' => { 'id' => String, 'links' => [link_format] } }) } create_server_format = { 'server' => { 'id' => String, 'adminPass' => String, 'links' => [link_format], 'OS-DCF:diskConfig' => String } } rescue_server_format = { 'adminPass' => Fog::Nullable::String } tests('success') do server_id = nil server_name = "fog#{Time.now.to_i.to_s}" image_id = rackspace_test_image_id(service) flavor_id = rackspace_test_flavor_id(service) bootable_flavor_id = if Fog.mocking? flavor_id else service.flavors.find { |f| f.name =~ /Performance/ }.id end tests("#create_server(#{server_name}, #{image_id}, #{flavor_id}, 1, 1)").formats(create_server_format) do body = service.create_server(server_name, image_id, flavor_id, 1, 1).body server_id = body['server']['id'] body end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests("#create_server(#{server_name}_bfv_1, '', #{flavor_id}, 1, 1, :boot_volume_id => bootable_volume_id)").succeeds do # First, create a bootable volume. volume_service = Fog::Rackspace::BlockStorage.new bootable_volume_id = volume_service.create_volume(100, :image_id => image_id).body['volume']['id'] wait_for_volume_state(volume_service, bootable_volume_id, 'available') body = service.create_server(server_name + "_bfv_1", '', bootable_flavor_id, 1, 1, :boot_volume_id => bootable_volume_id).body bfv_server_id = body['server']['id'] wait_for_server_state(service, bfv_server_id, 'ACTIVE', 'ERROR') service.delete_server(bfv_server_id) wait_for_volume_state(volume_service, bootable_volume_id, 'available') volume_service.delete_volume(bootable_volume_id) end tests("#create_server(#{server_name}_bfv_2, '', #{flavor_id}, 1, 1, :boot_image_id => #{image_id})").succeeds do body = service.create_server(server_name + "_bfv_2", '', bootable_flavor_id, 1, 1, :boot_image_id => image_id).body bfv_server_id = body['server']['id'] wait_for_server_state(service, bfv_server_id, 'ACTIVE', 'ERROR') service.delete_server(bfv_server_id) end tests('#list_servers').formats(list_servers_format, false) do service.list_servers.body end tests('#get_server').formats(get_server_format, false) do service.get_server(server_id).body end tests("#update_server(#{server_id}, #{server_name}_update) LEGACY").formats(get_server_format) do service.update_server(server_id, "#{server_name}_update").body end tests("#update_server(#{server_id}, { 'name' => #{server_name}_update)} ").formats(get_server_format) do service.update_server(server_id, 'name' => "#{server_name}_update").body end tests('#change_server_password').succeeds do service.change_server_password(server_id, 'some_server_password') end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#reboot_server').succeeds do service.reboot_server(server_id, 'SOFT') end wait_for_server_state(service, server_id, 'ACTIVE') tests('#rebuild_server').succeeds do rebuild_image_id = image_id service.rebuild_server(server_id, rebuild_image_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') sleep 120 unless Fog.mocking? tests('#resize_server').succeeds do resize_flavor_id = Fog.mocking? ? flavor_id : service.flavors[1].id service.resize_server(server_id, resize_flavor_id) end wait_for_server_state(service, server_id, 'VERIFY_RESIZE', 'ACTIVE') tests('#confirm_resize_server').succeeds do service.confirm_resize_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#resize_server').succeeds do resize_flavor_id = Fog.mocking? ? flavor_id : service.flavors[2].id service.resize_server(server_id, resize_flavor_id) end wait_for_server_state(service, server_id, 'VERIFY_RESIZE', 'ACTIVE') tests('#revert_resize_server').succeeds do service.revert_resize_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#rescue_server').formats(rescue_server_format, false) do service.rescue_server(server_id) end wait_for_server_state(service, server_id, 'RESCUE', 'ACTIVE') tests('#start_server').formats(rescue_server_format, false) do service.start_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#stop_server').formats(rescue_server_format, false) do service.stop_server(server_id) end wait_for_server_state(service, server_id, 'SHUTOFF') tests('#unrescue_server').succeeds do service.unrescue_server(server_id) end wait_for_server_state(service, server_id, 'ACTIVE', 'ERROR') tests('#delete_server').succeeds do service.delete_server(server_id) end tests('#get_vnc_console').succeeds do service.get_vnc_console(server_id, 'novnc') end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/attachment_tests.rb0000644000004100000410000000452413411315054027210 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | attachment_tests', ['rackspace']) do compute_service = Fog::Compute::RackspaceV2.new block_storage_service = Fog::Rackspace::BlockStorage.new image_id = rackspace_test_image_id(compute_service) flavor_id = rackspace_test_flavor_id(compute_service) attachment_format = { 'volumeAttachment' => { 'id' => String, 'serverId' => String, 'volumeId' => String, 'device' => Fog::Nullable::String } } list_attachments_format = { 'volumeAttachments' => [attachment_format['volumeAttachment']] } name = 'fog' + Time.now.to_i.to_s image_id = image_id flavor_id = flavor_id server_id = compute_service.create_server(name, image_id, flavor_id, 1, 1).body['server']['id'] volume_id = block_storage_service.create_volume(100).body['volume']['id'] device_id = '/dev/xvde' tests('success') do wait_for_request("Waiting for server to become ready") do compute_service.get_server(server_id).body['server']['status'] == 'ACTIVE' end wait_for_request("Waiting for Volume to be ready") do block_storage_service.get_volume(volume_id).body['volume']['status'] == 'available' end tests("#attach_volume(#{server_id}, #{volume_id}, #{device_id})").formats(attachment_format) do compute_service.attach_volume(server_id, volume_id, device_id).body end tests("#list_attachments(#{server_id})").formats(list_attachments_format) do compute_service.list_attachments(server_id).body end wait_for_request("Waiting for Volume to be ready") do block_storage_service.get_volume(volume_id).body['volume']['status'] == 'in-use' end tests("#get_attachment(#{server_id}, #{volume_id})").formats(attachment_format) do compute_service.get_attachment(server_id, volume_id).body end tests("#delete_attachment(#{server_id}, #{volume_id})").succeeds do compute_service.delete_attachment(server_id, volume_id) end end tests('failure') do tests("#attach_volume('', #{volume_id}, #{device_id})").raises(Fog::Compute::RackspaceV2::NotFound) do compute_service.attach_volume('', volume_id, device_id) end tests("#delete_attachment('', #{volume_id})").raises(Fog::Compute::RackspaceV2::NotFound) do compute_service.delete_attachment('', volume_id) end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/network_tests.rb0000644000004100000410000000227013411315054026545 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | network_tests', ['rackspace']) do service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') network_format = { 'id' => String, 'label' => String, 'cidr' => Fog::Nullable::String } get_network_format = { 'network' => network_format } list_networks_format = { 'networks' => [network_format] } tests('success') do network_id = nil tests('#create_network').formats(get_network_format) do service.create_network("fog_#{Time.now.to_i.to_s}", '192.168.0.0/24').body.tap do |r| network_id = r['network']['id'] end end tests('#list_networks').formats(list_networks_format) do service.list_networks.body end tests('#get_network').formats(get_network_format) do service.get_network(network_id).body end tests('#delete_network').succeeds do service.delete_network(network_id) end end test('failure') do tests('#get_network').raises(Fog::Compute::RackspaceV2::NotFound) do service.get_network(0) end tests('#delete_network').raises(Fog::Compute::RackspaceV2::NotFound) do service.delete_network(0) end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/flavor_tests.rb0000644000004100000410000000214713411315054026350 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | flavor_tests', ['rackspace']) do flavor_format = { 'id' => String, 'name' => String, 'ram' => Fog::Nullable::Integer, 'disk' => Fog::Nullable::Integer, 'vcpus' => Fog::Nullable::Integer, 'links' => [{ 'rel' => String, 'href' => String }] } list_flavor_format = { 'flavors' => [flavor_format] } get_flavor_format = { 'flavor' => flavor_format.merge({ 'OS-FLV-EXT-DATA:ephemeral' => Integer, 'rxtx_factor' => Float, 'swap' => Integer }) } service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') flavor_id = nil tests('success') do tests('#list_flavors').formats(list_flavor_format) do body = service.list_flavors.body flavor_id = body['flavors'][0]['id'] body end tests('#list_flavors_detail').formats(list_flavor_format) do body = service.list_flavors_detail.body flavor_id = body['flavors'][0]['id'] body end tests('#get_flavor').formats(get_flavor_format) do service.get_flavor(flavor_id).body end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/keypair_tests.rb0000644000004100000410000000262113411315054026520 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | keypair_tests', ['rackspace']) do keypair_format = { 'name' => String, 'public_key' => String, 'fingerprint' => String, } create_keypair_format = { 'keypair' => keypair_format.merge({ 'user_id' => String, 'private_key' => String }) } list_keypair_format = { 'keypairs' => [ 'keypair' => keypair_format ] } get_keypair_format = { 'keypair' => keypair_format } service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') keypair_name = Fog::Mock.random_letters(32) tests('success') do tests('#create_keypair').formats(create_keypair_format) do service.create_keypair(keypair_name).body end tests('#list_keypairs').formats(list_keypair_format) do service.list_keypairs.body end tests('#get_keypair').formats(get_keypair_format) do service.get_keypair(keypair_name).body end tests('#delete_keypair') do service.delete_keypair(keypair_name).body end end unknown_keypair_name = Fog::Mock.random_letters(32) tests('failure') do tests('#get_unknown_keypair').raises(Fog::Compute::RackspaceV2::NotFound) do service.get_keypair(unknown_keypair_name).body end tests('#delete_unknown_keypair').raises(Fog::Compute::RackspaceV2::NotFound) do service.delete_keypair(unknown_keypair_name).body end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/metadata_tests.rb0000644000004100000410000001114713411315054026637 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | metadata_tests', ['rackspace']) do @service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') image_id = rackspace_test_image_id(@service) flavor_id = rackspace_test_flavor_id(@service) tests('success') do begin metadata = {"tag" => "database"} unless Fog.mocking? name = "fog-server-metadata-#{Time.now.to_i}" @server = @service.servers.create(:name => name, :flavor_id => flavor_id, :image_id => image_id, :metadata => metadata) @server.wait_for { ready? } @server_id = @server.id @image = @server.create_image(name, :metadata => metadata) @image_id = @image.id else @image_id = 1 @server_id = 1 end tests("servers") do tests('list_metadata').returns("metadata" => metadata) do @service.list_metadata("servers", @server_id).body end tests('set_metadata').returns("metadata" => {"environment" => "dev"}) do @service.set_metadata("servers", @server_id, {"environment" => "dev"}).body end tests('update_metadata').returns("metadata" => {"environment" => "dev", "tag" => "database"}) do @service.update_metadata("servers", @server_id, {"environment" => "dev", "tag" => "database"}).body end tests('get_metadata_item').returns("meta" => {"environment" => "dev"}) do @service.get_metadata_item("servers", @server_id, "environment").body end tests('set_metadata_item').returns("meta" => {"environment" => "test"}) do @service.set_metadata_item("servers", @server_id, "environment", "test").body end tests('delete_metadata_item').succeeds do @service.delete_metadata_item("servers", @server_id, "environment") end end tests("images") do @image.wait_for { ready? } unless Fog.mocking? tests('list_metadata').returns(metadata) do h = @service.list_metadata("images", @image_id).body h["metadata"].reject {|k,v| k.downcase != "tag"} #only look at the metadata we created end tests('set_metadata').returns({"environment" => "dev"}) do h = @service.set_metadata("images", @image_id, {"environment" => "dev"}).body h["metadata"].reject {|k,v| k.downcase != "environment"} #only look at the metadata we created end tests('update_metadata').returns({"environment" => "dev", "tag" => "database"}) do h = @service.update_metadata("images", @image_id, {"environment" => "dev", "tag" => "database"}).body h["metadata"].reject {|k,v| !['environment', 'tag'].include?(k.downcase)} #only look at the metadata we created end tests('get_metadata_item').returns("meta" => {"environment" => "dev"}) do @service.get_metadata_item("images", @image_id, "environment").body end tests('set_metadata_item').returns("meta" => {"environment" => "test"}) do @service.set_metadata_item("images", @image_id, "environment", "test").body end tests('delete_metadata_item').succeeds do @service.delete_metadata_item("images", @image_id, "environment") end end ensure @image.destroy if @image @server.destroy if @server end end tests('failure') do ['server', 'image'].each do |collection| tests(collection) do tests('list_metadata').raises(Fog::Compute::RackspaceV2::NotFound) do @service.list_metadata(collection, 0) end tests('set_server_metadata').raises(Fog::Compute::RackspaceV2::NotFound) do @service.set_metadata(collection, 0, {"environment" => "dev"}) end tests('update_server_metadata').raises(Fog::Compute::RackspaceV2::NotFound) do @service.update_metadata(collection, 0, {"environment" => "dev", "tag" => "database"}) end tests('get_server_metadata_item').raises(Fog::Compute::RackspaceV2::NotFound) do @service.get_metadata_item(collection, 0, "environment") end tests('set_server_metadata_item').raises(Fog::Compute::RackspaceV2::NotFound) do @service.set_metadata_item(collection, 0, "environment", "test") end tests('delete_server_metadata_item').raises(Fog::Compute::RackspaceV2::NotFound) do @service.delete_metadata_item(collection, 0, "environment") end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/virtual_interface_tests.rb0000644000004100000410000000315213411315054030562 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | virtual_interface_tests', ['rackspace']) do @service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') virtual_interface_format = { "virtual_interfaces"=> [{ "ip_addresses"=> [{ "network_id"=> String, "network_label"=> String, "address"=> String }], "id"=> String, "mac_address"=> String }] } begin unless Fog.mocking? network_id = nil @server = @service.servers.create(:name => "fog_virtual_interface_test_#{Time.now.to_i.to_s}", :flavor_id => rackspace_test_flavor_id(@service), :image_id => rackspace_test_image_id(@service)) @server.wait_for { ready? } @network = @service.networks.create(:label => "fog_#{Time.now.to_i.to_s}", :cidr => '192.168.0.0/24') end tests('success') do pending if Fog.mocking? tests('#create_virtual_interface').formats(virtual_interface_format) do response = @service.create_virtual_interface @server.id, @network.id body = response.body @virtual_network_interface_id = body["virtual_interfaces"].first["id"] body end tests('#list_virtual_interfaces').formats(virtual_interface_format) do @service.list_virtual_interfaces(@server.id).body end tests('#delete_virtual_interfaces').succeeds do @service.delete_virtual_interface(@server.id, @virtual_network_interface_id) end end ensure @server.destroy if @server delete_test_network @network end end fog-rackspace-0.1.6/tests/rackspace/requests/compute_v2/address_tests.rb0000644000004100000410000000272113411315054026502 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | address requests', ['rackspace']) do @service = Fog::Compute.new(:provider => 'Rackspace', :version => 'V2') image_id = rackspace_test_image_id(@service) flavor_id = rackspace_test_flavor_id(@service) tests('success') do unless Fog.mocking? @server = @service.servers.create(:flavor_id => flavor_id, :image_id => image_id, :name => "address-tests-#{Time.now.to_i}") @server.wait_for { ready? } @server_id = @server.id else @server_id = 42 end address_format = { "addresses"=> { "private" => [{"addr" => String, "version" => Integer}], "public" => [{"addr" => String, "version" => Integer }, {"addr"=> String, "version" => Integer}]} } begin tests("#list_addresses(#{@server_id})").formats(address_format) do @service.list_addresses(@server_id).body end tests("#list_addresses_by_network(#{@server_id}, 'private')").formats(address_format["addresses"].reject {|k,v| k != "private"}) do @service.list_addresses_by_network(@server_id, "private").body end ensure @server.destroy if @server end end tests('failure') do tests('#list_addresses(0)').raises(Fog::Compute::RackspaceV2::NotFound) do @service.list_addresses(0) end tests("#list_addresses_by_network(0, 'private')").raises(Fog::Compute::RackspaceV2::NotFound) do @service.list_addresses_by_network(0, 'private') end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/0000755000004100000410000000000013411315054024152 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/content_caching_tests.rb0000644000004100000410000000137213411315054031052 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | content_caching', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do tests("#get_content_caching(#{@lb.id})").formats(CONTENT_CACHING_FORMAT) do @service.get_content_caching(@lb.id).body end @lb.wait_for { ready? } tests("#set_content_caching(#{@lb.id}, true)").succeeds do @service.set_content_caching(@lb.id, true) end end tests('failure') do tests("#set_content_caching(#{@lb.id}, 'aaa')").raises(Fog::Rackspace::LoadBalancers::InternalServerError) do @service.set_content_caching(@lb.id, 'aaa') end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/virtual_ip_tests.rb0000644000004100000410000000240513411315054030100 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | virtual_ip_tests', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do @lb.wait_for { ready? } tests('#create_virtual_ip').formats(VIRTUAL_IP_FORMAT) do data = @service.create_virtual_ip(@lb.id, 'PUBLIC').body @virtual_ip_id = data['id'] data end @lb.wait_for { ready? } tests("list_virtual_ips").formats(VIRTUAL_IPS_FORMAT) do @service.list_virtual_ips(@lb.id).body end end tests('failure') do #TODO - I feel like this should really be a BadRequest, need to dig in tests('create_virtual_ip(invalid type)').raises(Fog::Rackspace::LoadBalancers::InternalServerError) do @service.create_virtual_ip(@lb.id, 'badtype') end tests('delete_virtual_ip(0)').raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.delete_virtual_ip(@lb.id, 0) end end tests('success') do @lb.wait_for { ready? } tests("#delete_virtual_ip(#{@lb.id}, #{@virtual_ip_id})").succeeds do @service.delete_virtual_ip(@lb.id, @virtual_ip_id) end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/usage_tests.rb0000644000004100000410000000100313411315054027017 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | usage', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do tests('success') do tests("#get_usage()").formats(USAGE_FORMAT) do pending # @service.get_usage.body end tests("#get_usage(:start_time => '2010-05-10', :end_time => '2010-05-11')").formats(USAGE_FORMAT) do pending # @service.get_usage(:start_time => '2010-05-10', :end_time => '2010-05-11').body end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/helper.rb0000644000004100000410000001754013411315054025765 0ustar www-datawww-dataSINGLE_NODE_FORMAT = {'address' => String, 'id' => Integer, 'status' => String, 'weight' => Fog::Nullable::Integer, 'port' => Integer, 'condition' => String, 'type' => String} NODE_FORMAT = {'node' => SINGLE_NODE_FORMAT.merge({ 'metadata' => []})} NODES_FORMAT = {'nodes' => [SINGLE_NODE_FORMAT]} VIRTUAL_IP_FORMAT = {'type' => String, 'id' => Integer, 'type' => String, 'ipVersion' => String, 'address' => String} VIRTUAL_IPS_FORMAT = { 'virtualIps' => [VIRTUAL_IP_FORMAT] } SOURCE_ADDRESSES = { 'ipv4Servicenet' => String, 'ipv4Public' => String, 'ipv6Public' => String, } LOAD_BALANCER_USAGE_FORMAT = { 'links' => [ { 'otherAttributes' => [], 'href' => Fog::Nullable::String, 'rel' => Fog::Nullable::String } ], 'loadBalancerUsageRecords' => [ { 'id' => Fog::Nullable::Integer, 'eventType' => Fog::Nullable::String, 'averageNumConnections' => Fog::Nullable::Float, 'incomingTransfer' => Fog::Nullable::Integer, 'outgoingTransfer' => Fog::Nullable::Integer, 'numVips' => Fog::Nullable::Integer, 'numPolls' => Fog::Nullable::Integer, 'startTime' => Fog::Nullable::String, 'endTime' => Fog::Nullable::String, 'vipType' => Fog::Nullable::String, } ] } LOAD_BALANCER_STATS_FORMAT = { 'connectTimeOut' => Integer, 'connectError' => Integer, 'connectFailure' => Integer, 'dataTimedOut' => Integer, 'keepAliveTimedOut' => Integer, 'maxConn' => Integer } SSL_TERMINATION_FORMAT = { 'sslTermination' => { 'certificate' => String, 'privatekey' => String, 'enabled' => Fog::Boolean, 'securePort' => Integer, 'secureTrafficOnly' => Fog::Boolean, 'intermediateCertificate' => Fog::Nullable::String } } USAGE_FORMAT = { 'accountId' => Integer, 'loadBalancerUsages' => [ { 'loadBalancerId' => Fog::Nullable::Integer, 'loadBalancerName' => Fog::Nullable::String }.merge(LOAD_BALANCER_USAGE_FORMAT) ], 'accountUsage' => [ { 'startTime' => Fog::Nullable::String, 'numLoadBalancers' => Fog::Nullable::Integer, 'numPublicVips' => Fog::Nullable::Integer, 'numServicenetVips' => Fog::Nullable::Integer } ] } CONNECTION_LOGGING_FORMAT = { 'connectionLogging' => { 'enabled' => Fog::Boolean } } CONNECTION_THROTTLING_FORMAT = { 'connectionThrottle' => { 'maxConnections' => Fog::Nullable::Integer, 'minConnections' => Fog::Nullable::Integer, 'maxConnectionRate' => Fog::Nullable::Integer, 'rateInterval' => Fog::Nullable::Integer } } SESSION_PERSISTENCE_FORMAT = { 'sessionPersistence' => { 'persistenceType' => Fog::Nullable::String } } CONTENT_CACHING_FORMAT = { 'contentCaching' => { 'enabled' => Fog::Boolean } } ACCESS_LIST_FORMAT = { 'accessList' => [ { 'address' => String, 'id' => Integer, 'type' => String } ] } HEALTH_MONITOR_FORMAT = { 'healthMonitor' => { 'type' => Fog::Nullable::String, 'delay' => Fog::Nullable::Integer, 'timeout' => Fog::Nullable::Integer, 'attemptsBeforeDeactivation' => Fog::Nullable::Integer, 'path' => Fog::Nullable::String, 'bodyRegex' => Fog::Nullable::String, 'statusRegex' => Fog::Nullable::String } } STATUS_ACTIVE = 'ACTIVE' LOAD_BALANCERS_FORMAT = { 'loadBalancers' => [ { 'name' => String, 'id' => Integer, 'port' => Integer, 'protocol' => String, 'algorithm' => String, 'status' => String, 'virtualIps' => [VIRTUAL_IP_FORMAT], 'created' => { 'time' => String }, 'updated' => { 'time' => String }, 'nodeCount' => Integer }] } LOAD_BALANCERS_DETAIL_FORMAT = { 'loadBalancers' => [ { 'name' => String, 'id' => Integer, 'port' => Integer, 'protocol' => String, 'algorithm' => String, 'sourceAddresses' => SOURCE_ADDRESSES, 'status' => String, 'timeout' => Integer, 'virtualIps' => [VIRTUAL_IP_FORMAT], 'nodes' => [SINGLE_NODE_FORMAT], 'created' => { 'time' => String }, 'updated' => { 'time' => String } }] } LOAD_BALANCER_FORMAT = { 'loadBalancer' => { 'name' => String, 'id' => Integer, 'port' => Integer, 'protocol' => String, 'algorithm' => String, 'sourceAddresses' => SOURCE_ADDRESSES, 'status' => String, 'timeout' => Integer, 'cluster' => { 'name' => String }, 'virtualIps' => [VIRTUAL_IP_FORMAT], 'nodes' => Fog::Nullable::Array, 'created' => { 'time' => String }, 'updated' => { 'time' => String }, 'contentCaching' => { 'enabled' => Fog::Boolean } }.merge(CONNECTION_LOGGING_FORMAT) } ERROR_PAGE_FORMAT = { 'errorpage' => { 'content' => String } } PRIVATE_KEY = '-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAqSXePu8qLmniU7jNxoWq3SLkR8txMsl1gFYftpq7NIFaGfzV f4ZswYdEYDVWWRepQjS0TvsB0d5+usEUy/pcdZAlQLnn+540iLkvxKPVMzojUbG6 yOAmjC/xAZuExJHtfCrRHUQ4WQCwqyqANfP81y1inAb0zJGbtWUreV+nv8Ue77qX 77fOuqI6zOHinGZU7l25XGLcVUphgt8UtHZBzz2ahoftZ97DhUyQiSJQCaHXJd3Q eIHAq9qc7hu+usiYZWz34A0lw/gAl+RYcdvVc8kIwWxpiSieqqBPOwNzN5B0+9uu 5sDzMGMFnnSWcNKIPumX0rke3xFUl3UD6GJwvwIDAQABAoIBABQ7alT+yH3avm6j OUHYtTJUPRf1VqnrfPmH061E3sWN/1gCbQse6h1P77bOSnDHqsA3i6Wy0mnnAiOW esVXQf3x6vLOCdiH+OKtu+/6ZMMG3jikWKI0ZYf5KAu4LW5RwiVK/c5RXagPtBIV OFa7w299h0EAeAGMHSLaYhPXhDokyJa6yDkAQL3n+9L3V8kNWeCELfrqXnXF4X0K CJp622tS/fW6kzppJyLJ4GPkK9HNMpu02/n2Z7swWypfF+7set+9/aNTooDYWzCu dbnRgqEIG1IP8+t6HG6x9VujJVJLIW/WLITnQ/WTRXOQHBGhazgmwe1GPdxsQgXu /wIcsIkCgYEA8Si0q+QhmJyoAm8vTHjo6+DD06YYTvSODLJOpOqr1ncGGDJ/evBw x+9QsK3veXMbAK5G7Xss32IuXbBfjqQ89+/q/YT4BnS3T0OQa2WlR8tURNphCDr5 B3yD212kJTTehC+p7BI9zhnWXD9kImh4vm4XcOsC9iqOSCZkGfvRPRsCgYEAs46t Y85v2Pk235r1BPbgKwqYR+jElH4VWKu+EguUeQ4BlS47KktlLhvHtwrTv/UZ+lPx 8gSJTgyy7iEmzcGwPf1/MI5xg+DPgGhbr2G8EvrThmdHy+rPF2YSp1iBmJ4xq/1r 6XYKvf6ST3iujxTPU5xPEDUSLsH2ejJD/ddqSS0CgYEAkIdxyDa//8ObWWIjObSY +4zIMBcyKFeernNKeMH/3FeW+neBOT/Sh7CgblK/28ylWUIZVghlOzePTC0BB+7c b0eFUQ0YzF204rc+XW8coCt2xJEQaCtXxinUqGq1jmriFNyv/MBt9BA+DSkcrRZp js9SEyV1r+yPOyRvB7eIjhMCgYEAkd5yG+fkU1c6bfNb4/mPaUgFKD4AHUZEnzF+ ivhfWOy4+nGBXT285/VnjNs95O8AeK3jmyJ2TTLh1bSW6obUX7flsRO3QlTLHd0p xtPWT3D3kHOtDwslzDN/KfYr6klxvvB0z0e3OFxsjiVTYiecuqb8UAVdTSED1Ier Vre+v80CgYB86OqcAlR3diNaIwHgwK5kP2NAH1DaSwZXoobYpdkjsUQfJN5jwJbD 4/6HVydoc5xe0z8B+O1VUzC+QA0gdXgHbmLZBIUeQU8sE4hGELoe/eWULXGwI91M FyEWg03jZj8FkFh2954zwU6BOcbeL+9GrTdTPu1vuHoTitmNEye4iw== -----END RSA PRIVATE KEY-----' CERTIFICATE = '-----BEGIN CERTIFICATE----- MIIEWjCCA0KgAwIBAgIGATTTGu/tMA0GCSqGSIb3DQEBBQUAMHkxCzAJBgNVBAYT AlVTMQ4wDAYDVQQIEwVUZXhhczEOMAwGA1UEBxMFVGV4YXMxGjAYBgNVBAoTEVJh Y2tTcGFjZSBIb3N0aW5nMRQwEgYDVQQLEwtSYWNrRXhwIENBNTEYMBYGA1UEAxMP Y2E1LnJhY2tleHAub3JnMB4XDTEyMDExMjE4MDgwNVoXDTM5MDUzMDE4MDgwNVow gZcxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIEwVUZXhhczEUMBIGA1UEBxMLU2FuIEFu dG9uaW8xEDAOBgNVBAoTB1JhY2tFeHAxEDAOBgNVBAsTB1JhY2tEZXYxPjA8BgNV BAMMNW15c2l0ZS5jb20vZW1haWxBZGRyZXNzPXBoaWxsaXAudG9vaGlsbEByYWNr c3BhY2UuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqSXePu8q LmniU7jNxoWq3SLkR8txMsl1gFYftpq7NIFaGfzVf4ZswYdEYDVWWRepQjS0TvsB 0d5+usEUy/pcdZAlQLnn+540iLkvxKPVMzojUbG6yOAmjC/xAZuExJHtfCrRHUQ4 WQCwqyqANfP81y1inAb0zJGbtWUreV+nv8Ue77qX77fOuqI6zOHinGZU7l25XGLc VUphgt8UtHZBzz2ahoftZ97DhUyQiSJQCaHXJd3QeIHAq9qc7hu+usiYZWz34A0l w/gAl+RYcdvVc8kIwWxpiSieqqBPOwNzN5B0+9uu5sDzMGMFnnSWcNKIPumX0rke 3xFUl3UD6GJwvwIDAQABo4HIMIHFMIGjBgNVHSMEgZswgZiAFIkXQizRaftxVDaL P/Fb/F2ht017oX2kezB5MQswCQYDVQQGEwJVUzEOMAwGA1UECBMFVGV4YXMxDjAM BgNVBAcTBVRleGFzMRowGAYDVQQKExFSYWNrU3BhY2UgSG9zdGluZzEUMBIGA1UE CxMLUmFja0V4cCBDQTQxGDAWBgNVBAMTD2NhNC5yYWNrZXhwLm9yZ4IBAjAdBgNV HQ4EFgQUQUXHjce1JhjJDA4nhYcbebMrIGYwDQYJKoZIhvcNAQEFBQADggEBACLe vxcDSx91uQoc1uancb+vfkaNpvfAxOkUtrdRSHGXxvUkf/EJpIyG/M0jt5CLmEpE UedeCFlRN+Qnsqt589ZemWWJwth/Jbu0wQodfSo1cP0J2GFZDyTd5cWgm0IxD8A/ ZRGzNnTx3xskv6/lOh7so9ULppEbOsZTNqQ4ahbxbiaR2iDTQGF3XKSHha8O93RB YlnFahKZ2j0CpYvg0lJjfN0Lvj7Sm6GBA74n2OrGuB14H27wklD+PtIEFniyxKbq 5TDO0l4yDgkR7PsckmZqK22GP9c3fQkmXodtpV1wRjcSAxxVWYm+S24XvMFERs3j yXEf+VJ0H+voAvxgbAk= -----END CERTIFICATE-----' fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/connection_logging_tests.rb0000644000004100000410000000142213411315054031565 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | connection_logging', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do tests("#get_connection_logging(#{@lb.id})").formats(CONNECTION_LOGGING_FORMAT) do @service.get_connection_logging(@lb.id).body end @lb.wait_for { ready? } tests("#set_connection_logging(#{@lb.id}, true)").succeeds do @service.set_connection_logging(@lb.id, true) end end tests('failure') do tests("#set_connection_logging(#{@lb.id}, 'aaa')").raises(Fog::Rackspace::LoadBalancers::InternalServerError) do @service.set_connection_logging(@lb.id, 'aaa') end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/algorithm_tests.rb0000644000004100000410000000060313411315054027706 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | algorithm_tests', ['rackspace']) do pending if Fog.mocking? ALGORITHMS_FORMAT = { 'algorithms' => [ { 'name' => String } ]} @service = Fog::Rackspace::LoadBalancers.new tests('success') do tests('#list_algorithms').formats(ALGORITHMS_FORMAT) do @service.list_algorithms.body end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/error_page_tests.rb0000644000004100000410000000163113411315054030047 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | error_page', ['rackspace', 'loadbalancers']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do @lb.wait_for { ready? } tests("#get_error_page(#{@lb.id})").formats(ERROR_PAGE_FORMAT) do @service.get_error_page(@lb.id).body end @lb.wait_for { ready? } tests("#set_error_page(#{@lb.id}, 'hi!')").succeeds do @service.set_error_page(@lb.id, 'hi!') end @lb.wait_for { ready? } tests("#get_error_page(#{@lb.id})").formats(ERROR_PAGE_FORMAT) do @service.get_error_page(@lb.id).body end @lb.wait_for { ready? } tests("#remove_error_page()").succeeds do @service.remove_error_page(@lb.id) end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/access_list_tests.rb0000644000004100000410000000405413411315054030220 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | access_lists_tests', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do @lb.wait_for { ready? } tests("#create_access_rule(#{@lb.id}, '67.0.0.1','ALLOW')").succeeds do @service.create_access_rule(@lb.id, '67.0.0.1', 'ALLOW').body end @lb.wait_for { ready? } tests("list_access_rules").formats(ACCESS_LIST_FORMAT) do data = @service.list_access_rules(@lb.id).body returns(1) { data.size } @access_list_id = data['accessList'].first['id'] data end @lb.wait_for {ready? } tests("delete_access_rule(#{@lb.id}, #{@access_list_id}").succeeds do @service.delete_access_rule(@lb.id, @access_list_id) end @lb.wait_for {ready? } tests("delete_all_access_rules(#{@lb.id})").succeeds do #This could be refactored once we can add multiple access rules at once @service.create_access_rule(@lb.id, '67.0.0.2', 'ALLOW') @lb.wait_for {ready? } @service.create_access_rule(@lb.id, '67.0.0.3', 'ALLOW') @lb.wait_for {ready? } returns(2) { @service.list_access_rules(@lb.id).body['accessList'].size } @service.delete_all_access_rules(@lb.id) @lb.wait_for {ready? } returns(0) { @service.list_access_rules(@lb.id).body['accessList'].size } end end tests('failure') do tests('create_access_rule(invalid ip)').raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.create_access_rule(@lb.id, '', 'ALLOW') end tests('create_access_rule(invalid type)').raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.create_access_rule(@lb.id, '10.10.10.10', 'ENABLED') end tests("delete_access_rule(#{@lb.id}, 0)").raises(Fog::Rackspace::LoadBalancers::NotFound) do @service.delete_access_rule(@lb.id, 0) end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/connection_throttling_tests.rb0000644000004100000410000000232113411315054032334 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | connection_throttling', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do @lb.wait_for { ready? } tests("#get_connection_throttling(#{@lb.id})").formats(CONNECTION_THROTTLING_FORMAT) do @service.get_connection_throttling(@lb.id).body end @lb.wait_for { ready? } tests("#set_connection_throttling(#{@lb.id}, 10, 10, 10, 30)").succeeds do @service.set_connection_throttling(@lb.id, 10, 10, 10, 30) end @lb.wait_for { ready? } tests("#get_connection_throttling(#{@lb.id})").formats(CONNECTION_THROTTLING_FORMAT) do @service.get_connection_throttling(@lb.id).body end @lb.wait_for { ready? } tests("#remove_connection_throttling()").succeeds do @service.remove_connection_throttling(@lb.id) end end tests('failure') do tests("#set_connection_throttling(#{@lb.id}, -1, -1, -1, -1)").raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.set_connection_throttling(@lb.id, -1, -1, -1, -1) end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/protocol_tests.rb0000644000004100000410000000063113411315054027562 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | protocol_tests', ['rackspace']) do pending if Fog.mocking? PROTOCOLS_FORMAT = { 'protocols' => [ { 'name' => String, 'port' => Integer } ]} @service = Fog::Rackspace::LoadBalancers.new tests('success') do tests('#list_protocols').formats(PROTOCOLS_FORMAT) do @service.list_protocols.body end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/load_balancer_tests.rb0000644000004100000410000000653513411315054030500 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | load_balancer_tests', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do tests('success') do @lb_id = nil @lb_ids = [] @lb_name = 'fog' + Time.now.to_i.to_s tests("#create_load_balancer(#{@lb_name}, 'HTTP')").formats(LOAD_BALANCER_FORMAT) do data = @service.create_load_balancer(@lb_name, 'HTTP').body @lb_id = data['loadBalancer']['id'] @lb_ids << @lb_id data end tests("#create_load_balancer(#{@lb_name}, 'HTTP', 80,...)").formats(LOAD_BALANCER_FORMAT) do data = @service.create_load_balancer(@lb_name, 'HTTP', 80, [{ :type => 'PUBLIC' }], [{ :address => '1.1.1.1', :port => 80, :condition => 'ENABLED' }]).body @lb_ids << data['loadBalancer']['id'] data end tests("#create_load_balancer(#{@lb_name}, 'HTTP', 80,...with algorithm)").formats(LOAD_BALANCER_FORMAT) do data = @service.create_load_balancer(@lb_name, 'HTTP', 80, [{ :type => 'PUBLIC'}], [{ :address => '1.1.1.1', :port => 80, :condition => 'ENABLED'}], { :algorithm => 'LEAST_CONNECTIONS', :timeout => 30 }).body @lb_ids << data['loadBalancer']['id'] returns('LEAST_CONNECTIONS') { data['loadBalancer']['algorithm'] } returns(30) { data['loadBalancer']['timeout'] } data end tests("#update_load_balancer(#{@lb_id}) while immutable").raises(Fog::Rackspace::LoadBalancers::ServiceError) do @service.update_load_balancer(@lb_id, { :port => 80 }).body end tests("#get_load_balancer(#{@lb_id})").formats(LOAD_BALANCER_FORMAT) do @service.get_load_balancer(@lb_id).body end tests("#list_load_balancers()").formats(LOAD_BALANCERS_FORMAT) do @service.list_load_balancers.body end until @service.get_load_balancer(@lb_id).body["loadBalancer"]["status"] == STATUS_ACTIVE sleep 10 end tests("#list_load_balancers({:node_address => '1.1.1.1'})").formats(LOAD_BALANCERS_FORMAT) do @service.list_load_balancers({:node_address => '1.1.1.1'}).body end tests("#update_load_balancer(#{@lb_id}, { :port => 80 })").succeeds do @service.update_load_balancer(@lb_id, { :port => 80 }).body end until @service.get_load_balancer(@lb_id).body["loadBalancer"]["status"] == STATUS_ACTIVE sleep 10 end @lb_ids.each do |id| tests("#delete_load_balancer(#{id})").succeeds do @service.delete_load_balancer(id).body end end end tests('failure') do tests('#create_load_balancer(invalid name)').raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.create_load_balancer('', 'HTTP', 80, [{ :type => 'PUBLIC'}], [{ :address => '1.1.1.1', :port => 80, :condition => 'ENABLED'}]) end tests('#get_load_balancer(0)').raises(Fog::Rackspace::LoadBalancers::NotFound) do @service.get_load_balancer(0) end tests('#delete_load_balancer(0)').raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.delete_load_balancer(0) end tests('#update_load_balancer(0)').raises(Fog::Rackspace::LoadBalancers::NotFound) do @service.update_load_balancer(0, { :name => 'newname' }) end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/node_tests.rb0000644000004100000410000000701713411315054026653 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | node_tests', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do @nodes_created = [] tests('success') do @lb.wait_for { ready? } tests("#create_node(#{@lb.id}, '1.1.1.2', 80, 'ENABLED')").formats(NODES_FORMAT) do data = @service.create_node(@lb.id, '1.1.1.2', 80, 'ENABLED').body @nodes_created << data['nodes'][0]['id'] data end @lb.wait_for { ready? } tests('#create_node with weight').formats(NODES_FORMAT) do data = @service.create_node(@lb.id, '1.1.1.3', 80, 'ENABLED', { :weight => 10 }).body @nodes_created << data['nodes'][0]['id'] data end @lb.wait_for { ready? } tests('#create_node with type').formats(NODES_FORMAT) do data = @service.create_node(@lb.id, '1.1.1.4', 80, 'ENABLED', { :type => 'PRIMARY' }).body @nodes_created << data['nodes'][0]['id'] data end @lb.wait_for { ready? } tests("#list_nodes(#{@lb.id})").formats(NODES_FORMAT) do @service.list_nodes(@lb.id).body end @lb.wait_for { ready? } tests("#get_node(#{@lb.id})").formats(NODE_FORMAT) do @service.get_node(@lb.id, @nodes_created[0]).body end @lb.wait_for { ready? } tests("#update_node(#{@lb.id}, #{@nodes_created[0]}, { :condition => 'DISABLED' })").succeeds do @service.update_node(@lb.id, @nodes_created[0], { :condition => 'DISABLED' }) end @lb.wait_for { ready? } tests("#update_node(#{@lb.id}, #{@nodes_created[0]}, { :weight => 20})").succeeds do @service.update_node(@lb.id, @nodes_created[0], { :weight => 20 }) end @lb.wait_for { ready? } tests("#update_node(#{@lb.id}, #{@nodes_created[0]}, { :condition => 'DISABLED', :weight => 20 })").succeeds do @service.update_node(@lb.id, @nodes_created[0], { :condition => 'DISABLED', :weight => 20 }) end end tests('failure') do tests('#create_node(invalid ip)').raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.create_node(@lb.id, '', 80, 'ENABLED') end tests('#create_node(invalid condition)').raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.create_node(@lb.id, '1.1.1.2', 80, 'EABLED') end tests("#get_node(#{@lb.id}, 0)").raises(Fog::Rackspace::LoadBalancers::NotFound) do @service.get_node(@lb.id, 0) end tests("#delete_node(#{@lb.id}, 0)").raises(Fog::Rackspace::LoadBalancers::NotFound) do @service.delete_node(@lb.id, 0) end tests("#delete_nodes('a', 'b')").raises(Fog::Rackspace::LoadBalancers::NotFound) do @service.delete_nodes(@lb.id, 'a', 'b') end tests("#update_node(#{@lb.id}, 0, { :weight => 20 })").raises(Fog::Rackspace::LoadBalancers::NotFound) do @service.update_node(@lb.id, 0, { :weight => 20 }) end end tests('success') do @lb.wait_for { ready? } tests("#delete_nodes(multiple node)").succeeds do @service.delete_nodes(@lb.id, *@nodes_created) end @lb.wait_for { ready? } tests("#delete_node()").succeeds do node_id = @service.create_node(@lb.id, '1.1.1.3', 80, 'ENABLED').body['nodes'][0]['id'] @lb.wait_for { ready? } @service.delete_node(@lb.id, node_id) end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/session_persistence_tests.rb0000644000004100000410000000211013411315054032002 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | session_persistence', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do @lb.wait_for { ready? } tests("#set_session_persistence(#{@lb.id}, 'HTTP_COOKIE')").succeeds do @service.set_session_persistence(@lb.id, 'HTTP_COOKIE') end @lb.wait_for { ready? } tests("#get_session_persistence{@lb.id})").formats(SESSION_PERSISTENCE_FORMAT) do data = @service.get_session_persistence(@lb.id).body returns('HTTP_COOKIE') { data['sessionPersistence']['persistenceType'] } data end @lb.wait_for { ready? } tests("#remove_session_persistence()").succeeds do @service.remove_session_persistence(@lb.id) end end tests('failure') do tests("#set_session_persistence(#{@lb.id}, 'aaa')").raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.set_session_persistence(@lb.id, 'aaa') end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/get_stats_tests.rb0000644000004100000410000000056513411315054027724 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | load_balancer_get_stats', ['rackspace']) do given_a_load_balancer_service do given_a_load_balancer do tests('success') do @lb.wait_for { ready? } tests("#get_stats(#{@lb.id})").formats(LOAD_BALANCER_STATS_FORMAT) do @service.get_stats(@lb.id).body end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/ssl_termination_tests.rb0000644000004100000410000000231413411315054031133 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | ssl_termination', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do @lb.wait_for { ready? } tests("#set_ssl_termination(#{@lb.id}, 443, PRIVATE_KEY, CERTIFICATE)").succeeds do @service.set_ssl_termination(@lb.id, 443, PRIVATE_KEY, CERTIFICATE) end @lb.wait_for { ready? } tests("#get_ssl_termination(#{@lb.id})").formats(SSL_TERMINATION_FORMAT) do @service.get_ssl_termination(@lb.id).body end @lb.wait_for { ready? } tests("#remove_ssl_termination(#{@lb.id})").succeeds do @service.remove_ssl_termination(@lb.id).body end end tests('failure') do @lb.wait_for { ready? } tests("#get_ssl_termination(#{@lb.id})").raises(Fog::Rackspace::LoadBalancers::NotFound) do @service.get_ssl_termination(@lb.id).body end tests("#set_ssl_termination(#{@lb.id}, 443, '', CERTIFICATE)").raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.set_ssl_termination(@lb.id, 443, '', CERTIFICATE) end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/load_balancer_usage_tests.rb0000644000004100000410000000122213411315054031650 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | load_balancer_usage', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do @lb.wait_for { ready? } tests("#get_usage(#{@lb.id})").formats(LOAD_BALANCER_USAGE_FORMAT) do @service.get_load_balancer_usage(@lb.id).body end tests("#get_usage(:start_time => '2010-05-10', :end_time => '2010-05-11')").formats(LOAD_BALANCER_USAGE_FORMAT) do @service.get_load_balancer_usage(@lb.id, :start_time => '2010-05-10', :end_time => '2010-05-11').body end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/load_balancers/monitor_tests.rb0000644000004100000410000000302213411315054027405 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | monitor', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do tests('success') do @lb.wait_for { ready? } tests("#get_monitor(#{@lb.id})").formats(HEALTH_MONITOR_FORMAT) do @service.get_monitor(@lb.id).body end @lb.wait_for { ready? } tests("#set_monitor(#{@lb.id}, 'CONNECT', 5, 5, 5)").succeeds do @service.set_monitor(@lb.id, 'CONNECT', 5, 5, 5) end @lb.wait_for { ready? } tests("#set_monitor(#{@lb.id}, 'HTTP', 5, 5, 5, :path => '/', :body_regex => '^200$', :status_regex => '^2[0-9][0-9]$')").succeeds do @service.set_monitor(@lb.id, 'HTTP', 5, 5, 5, :path => '/', :body_regex => '^200$', :status_regex => '2[0-9][0-9]$') end @lb.wait_for { ready? } tests("#get_monitor(#{@lb.id})").formats(HEALTH_MONITOR_FORMAT) do @service.get_monitor(@lb.id).body end @lb.wait_for { ready? } tests("#remove_monitor()").succeeds do @service.remove_monitor(@lb.id) end end tests('failure') do tests("#set_monitor(#{@lb.id}, 'HTP', 5, 5, 5, 5)").raises(Fog::Rackspace::LoadBalancers::BadRequest) do @service.set_monitor(@lb.id, 5, 5, 5, 5) end tests("#remove_monitor(#{@lb.id}) => No Monitor").raises(Fog::Rackspace::LoadBalancers::ServiceError) do @service.remove_monitor(@lb.id) end end end end end fog-rackspace-0.1.6/tests/rackspace/requests/block_storage/0000755000004100000410000000000013411315054024037 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/block_storage/volume_type_tests.rb0000644000004100000410000000112413411315054030154 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::BlockStorage | volume_type_tests', ['rackspace']) do volume_type_format = { 'name' => String, 'extra_specs' => Hash, 'id' => String } service = Fog::Rackspace::BlockStorage.new tests('success') do volume_type_id = service.volume_types.first.id tests("#list_volume_types").formats('volume_types' => [volume_type_format]) do service.list_volume_types.body end tests("#get_volume_type(#{volume_type_id})").formats('volume_type' => volume_type_format) do service.get_volume_type(volume_type_id).body end end end fog-rackspace-0.1.6/tests/rackspace/requests/block_storage/volume_tests.rb0000644000004100000410000000367413411315054027127 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::BlockStorage | volume_tests', ['rackspace']) do volume_format = { 'id' => String, 'status' => String, 'display_name' => Fog::Nullable::String, 'display_description' => Fog::Nullable::String, 'size' => Integer, 'created_at' => String, 'volume_type' => String, 'availability_zone' => String, 'snapshot_id' => Fog::Nullable::String, 'image_id' => Fog::Nullable::String, 'attachments' => Array, 'metadata' => Hash } get_volume_format = { 'volume' => volume_format } list_volume_format = { 'volumes' => [volume_format] } service = Fog::Rackspace::BlockStorage.new tests('success') do ids = [] size = 100 tests("#create_volume(#{size})").formats(get_volume_format) do data = service.create_volume(size).body ids << data['volume']['id'] data end tests("#create_volume for a bootable volume").formats(get_volume_format) do # Find a suitable image. image_id = rackspace_test_image_id(Fog::Compute.new(:provider => 'rackspace')) data = service.create_volume(size, :image_id => image_id).body tests("assigned an image id").returns(image_id) do data['volume']['image_id'] end ids << data['volume']['id'] data end tests("#list_volumes").formats(list_volume_format) do service.list_volumes.body end tests("#get_volume(#{ids.first})").formats(get_volume_format) do service.get_volume(ids.first).body end ids.each do |id| tests("#delete_volume(#{id})").succeeds do wait_for_volume_state(service, id, 'available') service.delete_volume(id) end end end tests('failure') do tests("#create_volume(-1)").raises(Fog::Rackspace::BlockStorage::BadRequest) do service.create_volume(-1) end tests("#get_volume(-1)").raises(Fog::Rackspace::BlockStorage::NotFound) do service.get_volume(-1) end end end fog-rackspace-0.1.6/tests/rackspace/requests/block_storage/snapshot_tests.rb0000644000004100000410000000373313411315054027453 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::BlockStorage | snapshot_tests', ['rackspace']) do timeout = Fog.mocking? ? 1 : 10 snapshot_format = { 'id' => String, 'status' => String, 'display_name' => Fog::Nullable::String, 'display_description' => Fog::Nullable::String, 'volume_id' => String, 'size' => Integer, 'created_at' => String } get_snapshot_format = { 'snapshot' => snapshot_format } list_snapshot_format = { 'snapshots' => [snapshot_format] } def snapshot_deleted?(service, snapshot_id) begin service.get_snapshot(snapshot_id) false rescue true end end service = Fog::Rackspace::BlockStorage.new tests('success') do volume = service.create_volume(100).body['volume'] volume_id = volume['id'] snapshot_id = nil until service.get_volume(volume_id).body['volume']['status'] == 'available' sleep timeout end tests("#create_snapshot(#{volume_id})").formats(get_snapshot_format) do service.create_snapshot(volume_id).body.tap do |b| snapshot_id = b['snapshot']['id'] end end tests("#list_snapshots").formats(list_snapshot_format) do service.list_snapshots.body end tests("#get_snapshot(#{snapshot_id})").formats(get_snapshot_format) do service.get_snapshot(snapshot_id).body end until service.get_snapshot(snapshot_id).body['snapshot']['status'] == 'available' do sleep timeout end tests("#delete_snapshot(#{snapshot_id})").succeeds do service.delete_snapshot(snapshot_id) end until snapshot_deleted?(service, snapshot_id) sleep timeout end service.delete_volume(volume_id) end tests('failure') do tests("#create_snapshot('invalid')").raises(Fog::Rackspace::BlockStorage::NotFound) do service.create_snapshot('invalid') end tests("#get_snapshot('invalid')").raises(Fog::Rackspace::BlockStorage::NotFound) do service.get_snapshot('invalid') end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute/0000755000004100000410000000000013411315054022675 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/compute/helper.rb0000644000004100000410000000022613411315054024501 0ustar www-datawww-dataclass Rackspace module Compute module Formats SUMMARY = { 'id' => Integer, 'name' => String } end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute/image_tests.rb0000644000004100000410000000365213411315054025534 0ustar www-datawww-dataShindo.tests('Fog::Compute[:rackspace] | image requests', ['rackspace']) do @image_format = { 'created' => Fog::Nullable::String, 'id' => Integer, 'name' => String, 'progress' => Fog::Nullable::Integer, 'serverId' => Fog::Nullable::Integer, 'status' => String, 'updated' => String } @service = Fog::Compute.new(:provider => :rackspace, :version => :v1) tests('success') do @server = @service.servers.create(:flavor_id => 1, :image_id => 19) @server.wait_for { ready? } @image_id = nil tests("#create_image(#{@server.id})").formats(@image_format) do data = @service.create_image(@server.id).body['image'] @image_id = data['id'] data end unless Fog.mocking? @service.images.get(@image_id).wait_for { ready? } end tests("#get_image_details(#{@image_id})").formats(@image_format) do pending if Fog.mocking? @service.get_image_details(@image_id).body['image'] end tests('#list_images').formats({'images' => [Rackspace::Compute::Formats::SUMMARY]}) do @service.list_images.body end tests('#list_images_detail').formats({'images' => [@image_format]}) do @service.list_images_detail.body end unless Fog.mocking? @service.images.get(@image_id).wait_for { ready? } end tests("#delete_image(#{@image_id})").succeeds do pending if Fog.mocking? # because it will fail without the wait just above here, which won't work @service.delete_image(@image_id) end @server.destroy end tests('failure') do tests('#delete_image(0)').raises(Fog::Compute::Rackspace::NotFound) do @service.delete_image(Fog::Rackspace::MockData::NOT_FOUND_ID) end tests('#get_image_details(0)').raises(Fog::Compute::Rackspace::NotFound) do pending if Fog.mocking? @service.get_image_details(Fog::Rackspace::MockData::NOT_FOUND_ID) end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute/resize_tests.rb0000644000004100000410000000226413411315054025751 0ustar www-datawww-dataShindo.tests('Fog::Compute[:rackspace] | resize request', ['rackspace']) do @service = Fog::Compute.new(:provider => :rackspace, :version => :v1) @confirm_server = @service.servers.create(:flavor_id => 1, :image_id => 19) @revert_server = @service.servers.create(:flavor_id => 1, :image_id => 19) @confirm_server.wait_for { ready? } tests("#resize_server(#{@confirm_server.id}, 2) # to confirm").succeeds do @service.resize_server(@confirm_server.id, 2) end @revert_server.wait_for { ready? } tests("#resize_server(#{@revert_server.id}, 2) # to revert").succeeds do @service.resize_server(@revert_server.id, 2) end @confirm_server.wait_for { state == 'VERIFY_RESIZE' } tests("#confirm_resized_server(#{@confirm_server.id})").succeeds do @service.confirm_resized_server(@confirm_server.id) end @revert_server.wait_for { state == 'VERIFY_RESIZE' } tests("#revert_resized_server(#{@revert_server.id})").succeeds do @service.revert_resized_server(@revert_server.id) end @confirm_server.wait_for { ready? } @confirm_server.destroy @revert_server.wait_for { ready? } @revert_server.destroy end fog-rackspace-0.1.6/tests/rackspace/requests/compute/server_tests.rb0000644000004100000410000000533513411315054025760 0ustar www-datawww-dataShindo.tests('Fog::Compute[:rackspace] | server requests', ['rackspace']) do @server_format = { 'addresses' => { 'private' => [String], 'public' => [String] }, 'flavorId' => Integer, 'hostId' => String, 'id' => Integer, 'imageId' => Integer, 'metadata' => {}, 'name' => String, 'progress' => Integer, 'status' => String } @service = Fog::Compute.new(:provider => :rackspace, :version => :v1) tests('success') do @server_id = nil tests('#create_server(1, 19)').formats(@server_format.merge('adminPass' => String)) do # 1 => 256MB, 19 => Gentoo data = @service.create_server(1, 19).body['server'] @server_id = data['id'] data end @service.servers.get(@server_id).wait_for { ready? } tests("#get_server_details(#{@server_id})").formats(@server_format) do @service.get_server_details(@server_id).body['server'] end tests('#list_servers').formats({'servers' => [Rackspace::Compute::Formats::SUMMARY]}) do @service.list_servers.body end tests('#list_servers_detail').formats({'servers' => [@server_format]}) do @service.list_servers_detail.body end @service.servers.get(@server_id).wait_for { ready? } tests("#update_server(#{@server_id}, :name => 'fogupdatedserver', :adminPass => 'fogupdatedserver')").succeeds do @service.update_server(@server_id, :name => 'fogupdatedserver', :adminPass => 'fogupdatedserver') end @service.servers.get(@server_id).wait_for { ready? } tests("#reboot_server(#{@server_id}, 'HARD')").succeeds do pending if Fog.mocking? @service.reboot_server(@server_id, 'HARD') end @service.servers.get(@server_id).wait_for { ready? } tests("#reboot_server(#{@server_id}, 'SOFT')").succeeds do pending if Fog.mocking? @service.reboot_server(@server_id, 'SOFT') end @service.servers.get(@server_id).wait_for { ready? } tests("#delete_server(#{@server_id})").succeeds do @service.delete_server(@server_id) end end tests('failure') do tests('#delete_server(0)').raises(Fog::Compute::Rackspace::NotFound) do @service.delete_server(0) end tests('#get_server_details(0)').raises(Fog::Compute::Rackspace::NotFound) do @service.get_server_details(0) end tests("#update_server(0, :name => 'fogupdatedserver', :adminPass => 'fogupdatedserver')").raises(Fog::Compute::Rackspace::NotFound) do @service.update_server(0, :name => 'fogupdatedserver', :adminPass => 'fogupdatedserver') end tests('#reboot_server(0)').raises(Fog::Compute::Rackspace::NotFound) do pending if Fog.mocking? @service.reboot_server(0) end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute/flavor_tests.rb0000644000004100000410000000171313411315054025737 0ustar www-datawww-dataShindo.tests('Fog::Compute[:rackspace] | flavor requests', ['rackspace']) do @flavor_format = { 'disk' => Integer, 'id' => Integer, 'name' => String, 'ram' => Integer } @service = Fog::Compute.new(:provider => :rackspace, :version => :v1) tests('success') do tests('#get_flavor_details(1)').formats(@flavor_format) do pending if Fog.mocking? @service.get_flavor_details(1).body['flavor'] end tests('#list_flavors').formats({'flavors' => [Rackspace::Compute::Formats::SUMMARY]}) do pending if Fog.mocking? @service.list_flavors.body end tests('#list_flavors_detail').formats({'flavors' => [@flavor_format]}) do pending if Fog.mocking? @service.list_flavors_detail.body end end tests('failure') do tests('#get_flavor_details(0)').raises(Fog::Compute::Rackspace::NotFound) do pending if Fog.mocking? @service.get_flavor_details(0) end end end fog-rackspace-0.1.6/tests/rackspace/requests/compute/address_tests.rb0000644000004100000410000000226513411315054026076 0ustar www-datawww-dataShindo.tests('Fog::Compute[:rackspace] | address requests', ['rackspace']) do @service = Fog::Compute.new(:provider => :rackspace, :version => :v1) tests('success') do @server = @service.servers.create(:flavor_id => 1, :image_id => 19) tests("#list_addresses(#{@server.id})").formats({'addresses' => {'private' => [String], 'public' => [String]}}) do @service.list_addresses(@server.id).body end tests("#list_private_addresses(#{@server.id})").formats({'private' => [String]}) do @service.list_private_addresses(@server.id).body end tests("#list_public_addresses(#{@server.id})").formats({'public' => [String]}) do @service.list_public_addresses(@server.id).body end @server.wait_for { ready? } @server.destroy end tests('failure') do tests('#list_addresses(0)').raises(Fog::Compute::Rackspace::NotFound) do @service.list_addresses(0) end tests('#list_private_addresses(0)').raises(Fog::Compute::Rackspace::NotFound) do @service.list_private_addresses(0) end tests('#list_public_addresses(0)').raises(Fog::Compute::Rackspace::NotFound) do @service.list_public_addresses(0) end end end fog-rackspace-0.1.6/tests/rackspace/requests/monitoring/0000755000004100000410000000000013411315054023406 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/monitoring/helper.rb0000644000004100000410000000606513411315054025221 0ustar www-datawww-dataMINIMAL_HEADERS_FORMAT = { 'X-RateLimit-Window' => String, 'X-RateLimit-Limit' => String, 'X-RateLimit-Type' => String, 'Content-Type' => String, 'Date' => String, } DELETE_HEADERS_FORMAT = MINIMAL_HEADERS_FORMAT.merge({ 'Content-Length' => String }) HEADERS_FORMAT = MINIMAL_HEADERS_FORMAT.merge({ 'Content-Length' => String, 'X-Object-ID' => String, 'Location' => String }) LIST_HEADERS_FORMAT = MINIMAL_HEADERS_FORMAT.merge({ 'X-RateLimit-Remaining' => String, 'X-Response-Id' => String, 'Transfer-Encoding' => String, 'X-LB' => String, 'Vary' => String }) DATA_FORMAT = { :status => Integer, :body => String, :headers => HEADERS_FORMAT, :remote_ip => String } DELETE_DATA_FORMAT = { :status => Integer, :body => String, :headers => DELETE_HEADERS_FORMAT, :remote_ip => String } LIST_MONITORING_ZONE = { "values"=> [{"id"=>String, "label"=> Fog::Nullable::String, "country_code"=> String, "source_ips"=>[String, String]}], "metadata"=> {"count"=>Integer, "limit"=>Integer, "marker"=>Fog::Nullable::String, "next_marker"=>Fog::Nullable::String, "next_href"=>Fog::Nullable::String } } GET_MONITORING_ZONE = { "id" => String, "label" => String, "country_code" => String, "source_ips" => [String] } # {"values"=> # [{"id"=>"ch4GimHQsQ", # "label"=>nil, # "type"=>"remote.http", # "details"=> # {"url"=>"http://www.rackspace.com", # "method"=>"GET", # "follow_redirects"=>true, # "include_body"=>false}, # "monitoring_zones_poll"=>["mzdfw"], # "timeout"=>30, # "period"=>100, # "target_alias"=>nil, # "target_hostname"=>"rackspace.com", # "target_resolver"=>"IPv4", # "disabled"=>false, # "collectors"=>["coeT7x1iF3"], # "metadata"=>nil, # "created_at"=>1377803830760, # "updated_at"=>1377803830760}], # "metadata"=> # {"count"=>1, # "limit"=>100, # "marker"=>nil, # "next_marker"=>nil, # "next_href"=>nil}} # {"values"=> # [{"id"=>String, # "label"=>String, # "country_code"=>String, # "source_ips"=>[String, String]}], # "metadata"=> # {"count"=>Integer, # "limit"=>Integer, # "marker"=>nil, # "next_marker"=>nil, # "next_href"=>nil}} CHECK_CREATE_OPTIONS = { :details => { :url => 'http://www.rackspace.com', :method => 'GET', }, :type => 'remote.http', :monitoring_zones_poll => ['mzdfw'], :target_hostname => 'rackspace.com', :timeout => 30, :period => 100 } OVERVIEW_FORMAT = { :status => Integer, :body=> { :values => [ { :entity => { :id => String, :label => String, :ip_addresses => { }, :metadata => String }, :checks => [ ], :alarms => [ ], :latest_alarm_states => [ ] } ], :metadata => { :count => Integer, :limit => Integer, :marker => String, :next_marker => String, :next_href => String } }, :headers => LIST_HEADERS_FORMAT, :remote_ip => String } fog-rackspace-0.1.6/tests/rackspace/requests/monitoring/alarm_tests.rb0000644000004100000410000000424313411315054026254 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | alarm_tests', ['rackspace','rackspace_monitoring']) do account = Fog::Rackspace::Monitoring.new entity_id = account.create_entity(:label => "Foo").data[:headers]["X-Object-ID"] check_id = account.create_check(entity_id, CHECK_CREATE_OPTIONS).data[:headers]["X-Object-ID"] alarm_id = nil np = "npTechnicalContactsEmail" tests('success') do tests('#create new alarm').formats(DATA_FORMAT) do alarm_criteria = "if (metric['code'] == '404') { return new AlarmStatus(CRITICAL, 'Page not found');}" options = { :check_id => check_id, :notification_plan_id => np, :criteria => alarm_criteria } response = account.create_alarm(entity_id,options).data alarm_id = response[:headers]["X-Object-ID"] response end tests('#update alarm').formats(DATA_FORMAT) do options = { :label => "Bar"} account.update_alarm(entity_id,alarm_id,options).data end tests('#list alarms').formats(LIST_HEADERS_FORMAT) do account.list_alarms(entity_id).data[:headers] end tests('#get alarm').formats(LIST_HEADERS_FORMAT) do account.get_alarm(entity_id,alarm_id).data[:headers] end tests('#delete alarm').formats(DELETE_DATA_FORMAT) do account.delete_alarm(entity_id,alarm_id).data end end tests('failure') do tests('#fail to create new alarm(-1)').raises(Fog::Rackspace::Monitoring::BadRequest) do account.create_alarm(entity_id, {:type => ""}) end tests('#fail to update invalid alarm(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do options = { :testing => "Bar" } response = account.update_alarm(-1,-1,options) end tests('#fail to list alarms').raises(Fog::Rackspace::Monitoring::NotFound) do account.list_alarms(-1) end tests('#fail to get alarm').raises(Fog::Rackspace::Monitoring::NotFound) do account.get_alarm(-1,-1) end tests('#fail to delete alarm(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.delete_alarm(-1,-1) end end account.delete_check(entity_id,check_id) unless Fog.mocking? account.delete_entity(entity_id) unless Fog.mocking? end fog-rackspace-0.1.6/tests/rackspace/requests/monitoring/entity_tests.rb0000644000004100000410000000254213411315054026474 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | entity_tests', ['rackspace','rackspace_monitoring']) do account = Fog::Rackspace::Monitoring.new entity_id = nil tests('success') do tests('#create new entity').formats(DATA_FORMAT) do response = account.create_entity(:label => "Foo").data @entity_id = response[:headers]["X-Object-ID"] response end tests('#get entity').formats(LIST_HEADERS_FORMAT) do account.get_entity(@entity_id).data[:headers] end tests('#update entity').formats(DATA_FORMAT) do options = { :metadata => {:testing => "Bar" }} account.update_entity(@entity_id,options).data end tests('#delete entity').formats(DELETE_DATA_FORMAT) do account.delete_entity(@entity_id).data end end tests('failure') do tests('#create new entity(-1)').raises(Fog::Rackspace::Monitoring::BadRequest) do account.create_entity(:label => "") end tests('#get entity(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.get_entity(-1) end tests('#update invalid entity(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do options = { :metadata => {:testing => "Bar" }} response = account.update_entity(-1,options) end tests('#delete entity(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.delete_entity(-1) end end end fog-rackspace-0.1.6/tests/rackspace/requests/monitoring/notification_tests.rb0000644000004100000410000000332413411315054027645 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | notification_tests', ['rackspace','rackspace_monitoring']) do account = Fog::Rackspace::Monitoring.new notification_id = nil tests('success') do tests('#create new notification').formats(DATA_FORMAT) do pending if Fog.mocking? response = account.create_notification(:label => "Foo", :type => "email", :details => {:address => "test@test.com"}).data notification_id = response[:headers]["X-Object-ID"] response end tests('#get notification').formats(LIST_HEADERS_FORMAT) do account.get_notification(notification_id).data[:headers] end tests('#update notification').formats(DATA_FORMAT) do pending if Fog.mocking? options = {:testing => "Bar"} account.update_notification(notification_id,options).data end tests('#delete notification').formats(DELETE_DATA_FORMAT) do pending if Fog.mocking? account.delete_notification(notification_id).data end end tests('failure') do tests('#create new notification(-1)').raises(Fog::Rackspace::Monitoring::BadRequest) do pending if Fog.mocking? account.create_notification(:label => "") end tests('#get notification(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do pending if Fog.mocking? account.get_notification(-1) end tests('#update invalid notification(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do pending if Fog.mocking? options = { :testing => "Bar" } response = account.update_notification(-1,options) end tests('#delete notification(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do pending if Fog.mocking? account.delete_notification(-1) end end end fog-rackspace-0.1.6/tests/rackspace/requests/monitoring/agent_tests.rb0000644000004100000410000000574213411315054026263 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | agent_tests', ['rackspace','rackspace_monitoring']) do account = Fog::Rackspace::Monitoring.new agent_token = nil options = { "label" => "Bar" } values_format = Hash tests('success') do tests('#create new agent token').formats(DATA_FORMAT) do response = account.create_agent_token(options).data agent_token = response[:headers]["X-Object-ID"] response end tests('#list agent tokens').formats(LIST_HEADERS_FORMAT) do account.list_agent_tokens().data[:headers] end tests("#list_agents") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.list_agents.body } end tests("#get_agent") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_agent("agent_id").body } end tests('#get agent token').formats(LIST_HEADERS_FORMAT) do account.get_agent_token(agent_token).data[:headers] end tests('#delete agent token').formats(DELETE_HEADERS_FORMAT) do account.delete_agent_token(agent_token).data[:headers] end tests("#get_cpus_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_cpus_info("agent_id").body } end tests("#get_disks_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_disks_info("agent_id").body } end tests("#get_filesystems_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_filesystems_info("agent_id").body } end tests("#get_logged_in_user_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_logged_in_user_info("agent_id").body } end tests("#get_memory_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_memory_info("agent_id").body } end tests("#get_network_interfaces_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_network_interfaces_info("agent_id").body } end tests("#get_processes_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_processes_info("agent_id").body } end tests("#get_system_info") do data_matches_schema(values_format, {:allow_extra_keys => true}) { account.get_system_info("agent_id").body } end end tests('failure') do tests('#fail to create agent token(-1)').raises(TypeError) do account.create_agent_token(-1) end tests('#fail to get agent token(-1)').raises(TypeError) do account.create_agent_token(-1) end tests('#fail to delete agent token(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.delete_agent_token(-1) end tests('#fail to connect to agent(-1)').raises(Fog::Rackspace::Monitoring::BadRequest) do account.get_cpus_info(-1) end tests('#fail to get agent (-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.get_agent(-1) end end end fog-rackspace-0.1.6/tests/rackspace/requests/monitoring/check_tests.rb0000644000004100000410000000274313411315054026240 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | check_tests', ['rackspace', 'rackspace_monitoring']) do account = Fog::Rackspace::Monitoring.new entity_id = account.create_entity(:label => "Foo").data[:headers]["X-Object-ID"] check_id = nil tests('success') do tests('#create new check').formats(DATA_FORMAT) do response = account.create_check(entity_id, CHECK_CREATE_OPTIONS).data check_id = response[:headers]['X-Object-ID'] response end tests('#get check').formats(LIST_HEADERS_FORMAT) do account.get_check(entity_id,check_id).data[:headers] end tests('#update check').formats(DATA_FORMAT) do options = { :label => "Bar"} account.update_check(entity_id,check_id,options).data end tests('#delete check').formats(DELETE_DATA_FORMAT) do account.delete_check(entity_id,check_id).data end end tests('failure') do tests('#create new check(-1)').raises(Fog::Rackspace::Monitoring::BadRequest) do account.create_check(entity_id, {:type => ""}) end tests('#get check(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.get_check(-1, -1) end tests('#update invalid check(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do options = { :testing => "Bar" } response = account.update_check(-1,-1,options) end tests('#delete check(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.delete_check(-1,-1) end end account.delete_entity(entity_id) end fog-rackspace-0.1.6/tests/rackspace/requests/monitoring/list_tests.rb0000644000004100000410000000611613411315054026134 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | list_tests', ['rackspace','rackspace_monitoring']) do account = Fog::Rackspace::Monitoring.new if Fog.mocking? entity_id = "peoigne93" check_id = "2090wgn93" else entity_id = account.create_entity(:label => "Foo").data[:headers]["X-Object-ID"] check_id = account.create_check(entity_id,CHECK_CREATE_OPTIONS).data[:headers]["X-Object-ID"] end metric_name = "idle_percent_average" now = Time.now.to_i SLEEP_TIME= 2 sleep(SLEEP_TIME) unless Fog.mocking? tests('success') do tests('#get list of monitoring zones').formats(LIST_MONITORING_ZONE) do pending if Fog.mocking? account.list_monitoring_zones.body end tests('#get a monitoring zone').formats(GET_MONITORING_ZONE) do pending if Fog.mocking? account.get_monitoring_zone('mzdfw').body end tests('#get list of checks').formats(LIST_HEADERS_FORMAT) do account.list_checks(entity_id).data[:headers] end tests('#get list of check types').formats(LIST_HEADERS_FORMAT) do account.list_check_types().data[:headers] end tests('#get list of entities').formats(LIST_HEADERS_FORMAT) do account.list_entities().data[:headers] end tests('#get list of metrics').formats(LIST_HEADERS_FORMAT) do account.list_metrics(entity_id,check_id).data[:headers] end tests('#get overview list').formats(LIST_HEADERS_FORMAT) do account.list_overview().data[:headers] end tests('#list notification plans').formats(LIST_HEADERS_FORMAT) do account.list_notification_plans().data[:headers] end tests('#list notifications').formats(LIST_HEADERS_FORMAT) do account.list_notifications().data[:headers] end tests('#get list of data points').formats(LIST_HEADERS_FORMAT) do options = { :points => 1, :from => now * 1000, :to => (now+SLEEP_TIME) * 1000 } account.list_data_points(entity_id,check_id,metric_name,options).data[:headers] end end tests('failure') do tests('#fail to list checks').raises(Fog::Rackspace::Monitoring::NotFound) do account.list_checks(-1) end tests('#fail to list check types').raises(ArgumentError) do account.list_check_types(-1) end # This test has been put on hold due to a bug that incorrectly returns 200 OK to this request # tests('#fail to list notifications').raises(ArgumentError) do # account.list_notifications(-1) # end # This test has been put on hold due to a bug that incorrectly returns 200 OK to this request #tests('#fail to list metrics').raises(Fog::Rackspace::Monitoring::NotFound) do #account.list_metrics(-1,-1) #end tests('#fail: 1 argument instead of 0 for list_notification_plans').raises(ArgumentError) do account.list_notification_plans('fail') end tests('#fail to get list of data points').raises(Fog::Rackspace::Monitoring::BadRequest) do account.list_data_points(-1,-1,-1,-1).data end end account.delete_check(entity_id,check_id) unless Fog.mocking? account.delete_entity(entity_id) unless Fog.mocking? end fog-rackspace-0.1.6/tests/rackspace/requests/monitoring/alarm_example_tests.rb0000644000004100000410000000225513411315054027770 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | alarm_example_tests', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? account = Fog::Rackspace::Monitoring.new example_id = "remote.http_body_match_1" tests('success') do tests('#list alarm examples').formats(LIST_HEADERS_FORMAT) do account.list_alarm_examples().data[:headers] end tests('#get alarm example').formats(LIST_HEADERS_FORMAT) do account.get_alarm_example(example_id).data[:headers] end tests('#evaluate alarm example').formats(LIST_HEADERS_FORMAT) do options = { :string => "Foo"} account.evaluate_alarm_example(example_id,options).data[:headers] end end tests('failure') do tests('#fail to list alarm examples(-1)').raises(ArgumentError) do account.list_alarm_examples(-1).data[:headers] end tests('#fail to get alarm example(-1)').raises(Fog::Rackspace::Monitoring::NotFound) do account.get_alarm_example(-1).data[:headers] end tests('#fail to evaluate alarm example').raises(Fog::Rackspace::Monitoring::BadRequest) do options = { } account.evaluate_alarm_example(example_id,options).data[:headers] end end end fog-rackspace-0.1.6/tests/rackspace/requests/storage/0000755000004100000410000000000013411315054022665 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/storage/container_tests.rb0000644000004100000410000000401413411315054026415 0ustar www-datawww-dataShindo.tests('Fog::Storage[:rackspace] | container requests', ["rackspace"]) do @container_format = [{ 'hash' => String, 'last_modified' => String, 'bytes' => Integer, 'name' => String, 'content_type' => String }] @containers_format = [{ 'bytes' => Integer, 'count' => Integer, 'name' => String }] tests('success') do tests("#put_container('fogcontainertests', {})").succeeds do Fog::Storage[:rackspace].put_container('fogcontainertests') end tests("#put_container('fogcontainertests', 'X-Container-Meta-Color'=>'green')").succeeds do Fog::Storage[:rackspace].put_container('fogcontainertests', 'X-Container-Meta-Color'=>'green') response = Fog::Storage[:rackspace].head_container('fogcontainertests') returns('green') { response.headers['X-Container-Meta-Color'] } end tests("#get_container('fogcontainertests')").formats(@container_format) do Fog::Storage[:rackspace].get_container('fogcontainertests').body end tests("#get_containers").formats(@containers_format) do Fog::Storage[:rackspace].get_containers.body end tests("#head_container('fogcontainertests')").succeeds do Fog::Storage[:rackspace].head_container('fogcontainertests') end tests("#head_containers").succeeds do Fog::Storage[:rackspace].head_containers end tests("#delete_container('fogcontainertests')").succeeds do Fog::Storage[:rackspace].delete_container('fogcontainertests') end end tests('failure') do tests("#get_container('fognoncontainer')").raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].get_container('fognoncontainer') end tests("#head_container('fognoncontainer')").raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].head_container('fognoncontainer') end tests("#delete_container('fognoncontainer')").raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].delete_container('fognoncontainer') end end end fog-rackspace-0.1.6/tests/rackspace/requests/storage/large_object_tests.rb0000644000004100000410000003363713411315054027070 0ustar www-datawww-dataShindo.tests('Fog::Storage[:rackspace] | large object requests', ['rackspace']) do @directory = Fog::Storage[:rackspace].directories.create(:key => 'foglargeobjecttests') @directory2 = Fog::Storage[:rackspace].directories.create(:key => 'foglargeobjecttests2') @segments = { :a => { :container => @directory.identity, :name => 'fog_large_object/a', :data => 'a' * (1024**2 + 10), :size => 1024**2 + 10, :etag => 'c2e97007d59f0c19b850debdcb80cca5' }, :b => { :container => @directory.identity, :name => 'fog_large_object/b', :data => 'b' * (1024**2 + 20), :size => 1024**2 + 20, :etag => 'd35f50622a1259daad75ff7d5512c7ef' }, :c => { :container => @directory.identity, :name => 'fog_large_object2/a', :data => 'c' * (1024**2 + 30), :size => 1024**2 + 30, :etag => '901d3531a87d188041d4d5b43cb464c1' }, :d => { :container => @directory2.identity, :name => 'fog_large_object2/b', :data => 'd' * (1024**2 + 40), :size => 1024**2 + 40, :etag => '350c0e00525198813920a157df185c8d' } } tests('success') do tests('upload test segments').succeeds do @segments.each_value do |segment| Fog::Storage[:rackspace].put_object(segment[:container], segment[:name], segment[:data]) end end tests('dynamic large object requests') do tests('#put_object_manifest alias').succeeds do Fog::Storage[:rackspace].put_object_manifest(@directory.identity, 'fog_large_object') end tests('using default X-Object-Manifest header') do tests('#put_dynamic_obj_manifest').succeeds do Fog::Storage[:rackspace].put_dynamic_obj_manifest(@directory.identity, 'fog_large_object') end tests('#get_object streams all segments matching the default prefix').succeeds do expected = @segments[:a][:data] + @segments[:b][:data] + @segments[:c][:data] Fog::Storage[:rackspace].get_object(@directory.identity, 'fog_large_object').body == expected end # When the manifest object name is equal to the segment prefix, OpenStack treats it as if it's the first segment. # So you must prepend the manifest object's Etag - Digest::MD5.hexdigest('') tests('#head_object returns Etag that includes manifest object in calculation').succeeds do etags = ['d41d8cd98f00b204e9800998ecf8427e', @segments[:a][:etag], @segments[:b][:etag], @segments[:c][:etag]] expected = "\"#{ Digest::MD5.hexdigest(etags.join) }\"" # returned in quotes "\"2577f38428e895c50de6ea78ccc7da2a"\" Fog::Storage[:rackspace].head_object(@directory.identity, 'fog_large_object').headers['Etag'] == expected end end tests('specifying X-Object-Manifest segment prefix') do tests('#put_dynamic_obj_manifest').succeeds do options = { 'X-Object-Manifest' => "#{ @directory.identity }/fog_large_object/" } Fog::Storage[:rackspace].put_dynamic_obj_manifest(@directory.identity, 'fog_large_object', options) end tests('#get_object streams segments only matching the specified prefix').succeeds do expected = @segments[:a][:data] + @segments[:b][:data] Fog::Storage[:rackspace].get_object(@directory.identity, 'fog_large_object').body == expected end tests('#head_object returns Etag that does not include manifest object in calculation').succeeds do etags = [@segments[:a][:etag], @segments[:b][:etag]] expected = "\"#{ Digest::MD5.hexdigest(etags.join) }\"" # returned in quotes "\"0f035ed3cc38aa0ef46dda3478fad44d"\" Fog::Storage[:rackspace].head_object(@directory.identity, 'fog_large_object').headers['Etag'] == expected end end tests('storing manifest in a different container than the segments') do tests('#put_dynamic_obj_manifest').succeeds do options = { 'X-Object-Manifest' => "#{ @directory.identity }/fog_large_object/" } Fog::Storage[:rackspace].put_dynamic_obj_manifest(@directory2.identity, 'fog_large_object', options) end tests('#get_object').succeeds do expected = @segments[:a][:data] + @segments[:b][:data] Fog::Storage[:rackspace].get_object(@directory2.identity, 'fog_large_object').body == expected end end end tests('static large object requests') do tests('single container') do tests('#put_static_obj_manifest').succeeds do segments = [ { :path => "#{ @segments[:a][:container] }/#{ @segments[:a][:name] }", :etag => @segments[:a][:etag], :size_bytes => @segments[:a][:size] }, { :path => "#{ @segments[:c][:container] }/#{ @segments[:c][:name] }", :etag => @segments[:c][:etag], :size_bytes => @segments[:c][:size] } ] Fog::Storage[:rackspace].put_static_obj_manifest(@directory.identity, 'fog_large_object', segments) end tests('#head_object') do etags = [@segments[:a][:etag], @segments[:c][:etag]] etag = "\"#{ Digest::MD5.hexdigest(etags.join) }\"" # "\"ad7e633a12e8a4915b45e6dd1d4b0b4b\"" content_length = (@segments[:a][:size] + @segments[:c][:size]).to_s response = Fog::Storage[:rackspace].head_object(@directory.identity, 'fog_large_object') returns(etag, 'returns ETag computed from segments') { response.headers['Etag'] } returns(content_length , 'returns Content-Length for all segments') { response.headers['Content-Length'] } returns('True', 'returns X-Static-Large-Object header') { response.headers['X-Static-Large-Object'] } end tests('#get_object').succeeds do expected = @segments[:a][:data] + @segments[:c][:data] Fog::Storage[:rackspace].get_object(@directory.identity, 'fog_large_object').body == expected end tests('#delete_static_large_object') do expected = { 'Number Not Found' => 0, 'Response Status' => '200 OK', 'Errors' => [], 'Number Deleted' => 3, 'Response Body' => '' } returns(expected, 'deletes manifest and segments') do Fog::Storage[:rackspace].delete_static_large_object(@directory.identity, 'fog_large_object').body end end end tests('multiple containers') do tests('#put_static_obj_manifest').succeeds do segments = [ { :path => "#{ @segments[:b][:container] }/#{ @segments[:b][:name] }", :etag => @segments[:b][:etag], :size_bytes => @segments[:b][:size] }, { :path => "#{ @segments[:d][:container] }/#{ @segments[:d][:name] }", :etag => @segments[:d][:etag], :size_bytes => @segments[:d][:size] } ] Fog::Storage[:rackspace].put_static_obj_manifest(@directory2.identity, 'fog_large_object', segments) end tests('#head_object') do etags = [@segments[:b][:etag], @segments[:d][:etag]] etag = "\"#{ Digest::MD5.hexdigest(etags.join) }\"" # "\"9801a4cc4472896a1e975d03f0d2c3f8\"" content_length = (@segments[:b][:size] + @segments[:d][:size]).to_s response = Fog::Storage[:rackspace].head_object(@directory2.identity, 'fog_large_object') returns(etag, 'returns ETag computed from segments') { response.headers['Etag'] } returns(content_length , 'returns Content-Length for all segments') { response.headers['Content-Length'] } returns('True', 'returns X-Static-Large-Object header') { response.headers['X-Static-Large-Object'] } end tests('#get_object').succeeds do expected = @segments[:b][:data] + @segments[:d][:data] Fog::Storage[:rackspace].get_object(@directory2.identity, 'fog_large_object').body == expected end tests('#delete_static_large_object') do expected = { 'Number Not Found' => 0, 'Response Status' => '200 OK', 'Errors' => [], 'Number Deleted' => 3, 'Response Body' => '' } returns(expected, 'deletes manifest and segments') do Fog::Storage[:rackspace].delete_static_large_object(@directory2.identity, 'fog_large_object').body end end end end end tests('failure') do tests('dynamic large object requests') do tests('#put_dynamic_obj_manifest with missing container').raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].put_dynamic_obj_manifest('fognoncontainer', 'fog_large_object') end end tests('static large object requests') do tests('upload test segments').succeeds do Fog::Storage[:rackspace].put_object(@segments[:a][:container], @segments[:a][:name], @segments[:a][:data]) Fog::Storage[:rackspace].put_object(@segments[:b][:container], @segments[:b][:name], @segments[:b][:data]) end tests('#put_static_obj_manifest with missing container').raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].put_static_obj_manifest('fognoncontainer', 'fog_large_object', []) end tests('#put_static_obj_manifest with missing object') do segments = [ { :path => "#{ @segments[:c][:container] }/#{ @segments[:c][:name] }", :etag => @segments[:c][:etag], :size_bytes => @segments[:c][:size] } ] expected = { 'Errors' => [[segments[0][:path], '404 Not Found']] } error = nil begin Fog::Storage[:rackspace].put_static_obj_manifest(@directory.identity, 'fog_large_object', segments) rescue => err error = err end raises(Fog::Storage::Rackspace::BadRequest) do raise error if error end expected['Errors'][0][0] = error.response_data['Errors'][0][0] rescue nil returns(expected, 'returns error information') do error.response_data end end tests('#put_static_obj_manifest with invalid etag') do segments = [ { :path => "#{ @segments[:a][:container] }/#{ @segments[:a][:name] }", :etag => @segments[:b][:etag], :size_bytes => @segments[:a][:size] } ] expected = { 'Errors' => [[segments[0][:path], 'Etag Mismatch']] } error = nil begin Fog::Storage[:rackspace].put_static_obj_manifest(@directory.identity, 'fog_large_object', segments) rescue => err error = err end raises(Fog::Storage::Rackspace::BadRequest) do raise error if error end expected['Errors'][0][0] = error.response_data['Errors'][0][0] rescue nil returns(expected, 'returns error information') do error.response_data end end tests('#put_static_obj_manifest with invalid byte_size') do segments = [ { :path => "#{ @segments[:a][:container] }/#{ @segments[:a][:name] }", :etag => @segments[:a][:etag], :size_bytes => @segments[:b][:size] } ] expected = { 'Errors' => [[segments[0][:path], 'Size Mismatch']] } error = nil begin Fog::Storage[:rackspace].put_static_obj_manifest(@directory.identity, 'fog_large_object', segments) rescue => err error = err end raises(Fog::Storage::Rackspace::BadRequest) do raise error if error end expected['Errors'][0][0] = error.response_data['Errors'][0][0] rescue nil returns(expected, 'returns error information') do error.response_data end end tests('#delete_static_large_object with missing container') do response = Fog::Storage[:rackspace].delete_static_large_object('fognoncontainer', 'fog_large_object') returns(200) { response.status } returns(1) { response.body["Number Not Found"] } returns("200 OK") { response.body["Response Status"]} returns("") { response.body["Response Body"]} end tests('#delete_static_large_object with missing manifest') do response = Fog::Storage[:rackspace].delete_static_large_object(@directory.identity, 'fog_non_object') returns(200) { response.status } returns(1) { response.body["Number Not Found"] } returns("200 OK") { response.body["Response Status"]} returns("") { response.body["Response Body"]} end tests('#delete_static_large_object with missing segment') do tests('#put_static_obj_manifest for segments :a and :b').succeeds do segments = [ { :path => "#{ @segments[:a][:container] }/#{ @segments[:a][:name] }", :etag => @segments[:a][:etag], :size_bytes => @segments[:a][:size] }, { :path => "#{ @segments[:b][:container] }/#{ @segments[:b][:name] }", :etag => @segments[:b][:etag], :size_bytes => @segments[:b][:size] } ] Fog::Storage[:rackspace].put_static_obj_manifest(@directory.identity, 'fog_large_object', segments) end tests('#delete_object segment :b').succeeds do Fog::Storage[:rackspace].delete_object(@segments[:b][:container], @segments[:b][:name]) end tests('#delete_static_large_object') do expected = { 'Number Not Found' => 1, 'Response Status' => '200 OK', 'Errors' => [], 'Number Deleted' => 2, 'Response Body' => '' } returns(expected, 'deletes manifest and segment :a, and reports missing segment :b') do Fog::Storage[:rackspace].delete_static_large_object(@directory.identity, 'fog_large_object').body end end end end end @directory.destroy @directory2.destroy end fog-rackspace-0.1.6/tests/rackspace/requests/storage/account_tests.rb0000644000004100000410000000045713411315054026076 0ustar www-datawww-dataShindo.tests('Fog::Storage[:rackspace] | account requests', ["rackspace"]) do tests('success') do tests("#post_set_meta_temp_url_key('super_secret_key')").succeeds do Fog::Storage[:rackspace].post_set_meta_temp_url_key('super_secret_key') end end tests('failure') do end end fog-rackspace-0.1.6/tests/rackspace/requests/storage/object_tests.rb0000644000004100000410000002152013411315054025702 0ustar www-datawww-datarequire 'uri' require 'cgi' Shindo.tests('Fog::Storage[:rackspace] | object requests', ["rackspace"]) do @directory = Fog::Storage[:rackspace].directories.create(:key => 'fogobjecttests') module RackspaceStorageHelpers def override_path(path) @uri.path = path end end def parse_url(url_string) uri = URI.parse(url_string) query_hash = CGI.parse(uri.query) query_hash.each do |k, v| query_hash[k] = v[0] if query_hash[k].is_a?(Array) and query_hash[k].count == 1 end { :scheme => uri.scheme, :host => uri.host, :port => uri.port, :path => uri.path, :query => query_hash } end tests('success') do tests("#put_object('fogobjecttests', 'fog_object')").succeeds do Fog::Storage[:rackspace].put_object('fogobjecttests', 'fog_object', lorem_file) end tests("#get_object('fogobjectests', 'fog_object')").succeeds do Fog::Storage[:rackspace].get_object('fogobjecttests', 'fog_object').body == lorem_file.read end tests("#get_object('fogobjecttests', 'fog_object', &block)").succeeds do data = '' Fog::Storage[:rackspace].get_object('fogobjecttests', 'fog_object') do |chunk, remaining_bytes, total_bytes| data << chunk end data == lorem_file.read end tests("#head_object('fogobjectests', 'fog_object')").succeeds do Fog::Storage[:rackspace].head_object('fogobjecttests', 'fog_object') end tests("#delete_object('fogobjecttests', 'fog_object')").succeeds do Fog::Storage[:rackspace].delete_object('fogobjecttests', 'fog_object') end # an object key with no special characters tests("#get_object_http_url('fogobjecttests', 'fog_object','expiration timestamp')").succeeds do expires_at = 1344149532 # 2012-08-05 16:52:12 +1000 storage = Fog::Storage::Rackspace.new(:rackspace_temp_url_key => "super_secret") storage.extend RackspaceStorageHelpers storage.override_path('/fake_version/fake_tenant') object_url = storage.get_object_http_url('fogobjecttests', 'fog_object', expires_at) url = parse_url(object_url) [ url[:host] =~ /.*clouddrive\.com$/, url[:path] =~ /\/fogobjecttests\/fog_object$/, url[:query]['temp_url_sig'] == '7e69a73092e333095a70b3be826a7350fcbede86', url[:query]['temp_url_expires'] == '1344149532' ].all? end # an object key with no special characters tests("#get_object_https_url('fogobjecttests', 'fog_object','expiration timestamp')").succeeds do expires_at = 1344149532 # 2012-08-05 16:52:12 +1000 storage = Fog::Storage::Rackspace.new(:rackspace_temp_url_key => "super_secret") storage.extend RackspaceStorageHelpers storage.override_path('/fake_version/fake_tenant') object_url = storage.get_object_https_url('fogobjecttests', 'fog_object', expires_at) url = parse_url(object_url) [ url[:host] =~ /.*clouddrive\.com$/, url[:path] =~ /\/fogobjecttests\/fog_object$/, url[:query]['temp_url_sig'] == '7e69a73092e333095a70b3be826a7350fcbede86', url[:query]['temp_url_expires'] == '1344149532' ].all? end # an object key nested under a / tests("#get_object_https_url('fogobjecttests', 'fog/object','expiration timestamp')").succeeds do expires_at = 1344149532 # 2012-08-05 16:52:12 +1000 storage = Fog::Storage::Rackspace.new(:rackspace_temp_url_key => "super_secret") storage.extend RackspaceStorageHelpers storage.override_path('/fake_version/fake_tenant') object_url = storage.get_object_https_url('fogobjecttests', 'fog/object', expires_at) url = parse_url(object_url) [ url[:host] =~ /.*clouddrive\.com$/, url[:path] =~ /\/fogobjecttests\/fog\/object$/, url[:query]['temp_url_sig'] == '3e99892828804e3d0fdadd18c543b688591ca8b8', url[:query]['temp_url_expires'] == '1344149532' ].all? end # an object key containing a - tests("#get_object_https_url('fogobjecttests', 'fog-object','expiration timestamp')").succeeds do expires_at = 1344149532 # 2012-08-05 16:52:12 +1000 storage = Fog::Storage::Rackspace.new(:rackspace_temp_url_key => "super_secret") storage.extend RackspaceStorageHelpers storage.override_path('/fake_version/fake_tenant') object_url = storage.get_object_https_url('fogobjecttests', 'fog-object', expires_at) url = parse_url(object_url) [ url[:host] =~ /.*clouddrive\.com$/, url[:path] =~ /\/fogobjecttests\/fog-object$/, url[:query]['temp_url_sig'] == 'a24dd5fc955a57adce7d1b5bc4ec2c7660ab8396', url[:query]['temp_url_expires'] == '1344149532' ].all? end tests("put_object with block") do tests("#put_object('fogobjecttests', 'fog_object', &block)").succeeds do begin file = lorem_file buffer_size = file.stat.size / 2 # chop it up into two buffers Fog::Storage[:rackspace].put_object('fogobjecttests', 'fog_block_object', nil) do file.read(buffer_size).to_s end ensure file.close end end tests('#get_object').succeeds do Fog::Storage[:rackspace].get_object('fogobjecttests', 'fog_block_object').body == lorem_file.read end tests('#delete_object').succeeds do Fog::Storage[:rackspace].delete_object('fogobjecttests', 'fog_block_object') end end tests('#delete_multiple_objects') do Fog::Storage[:rackspace].put_object('fogobjecttests', 'fog_object', lorem_file) Fog::Storage[:rackspace].put_object('fogobjecttests', 'fog_object2', lorem_file) Fog::Storage[:rackspace].directories.create(:key => 'fogobjecttests2') Fog::Storage[:rackspace].put_object('fogobjecttests2', 'fog_object', lorem_file) expected = { "Number Not Found" => 0, "Response Status" => "200 OK", "Errors" => [], "Number Deleted" => 2, "Response Body" => "" } returns(expected, 'deletes multiple objects') do Fog::Storage[:rackspace].delete_multiple_objects('fogobjecttests', ['fog_object', 'fog_object2']).body end returns(expected, 'deletes object and container') do Fog::Storage[:rackspace].delete_multiple_objects(nil, ['fogobjecttests2/fog_object', 'fogobjecttests2']).body end end end tests('failure') do tests("#get_object('fogobjecttests', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].get_object('fogobjecttests', 'fog_non_object') end tests("#get_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].get_object('fognoncontainer', 'fog_non_object') end tests("#head_object('fogobjecttests', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].head_object('fogobjecttests', 'fog_non_object') end tests("#head_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].head_object('fognoncontainer', 'fog_non_object') end tests("#delete_object('fogobjecttests', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].delete_object('fogobjecttests', 'fog_non_object') end tests("#delete_object('fognoncontainer', 'fog_non_object')").raises(Fog::Storage::Rackspace::NotFound) do Fog::Storage[:rackspace].delete_object('fognoncontainer', 'fog_non_object') end tests('#delete_multiple_objects') do expected = { "Number Not Found" => 2, "Response Status" => "200 OK", "Errors" => [], "Number Deleted" => 0, "Response Body" => "" } returns(expected, 'reports missing objects') do Fog::Storage[:rackspace].delete_multiple_objects('fogobjecttests', ['fog_non_object', 'fog_non_object2']).body end returns(expected, 'reports missing container') do Fog::Storage[:rackspace].delete_multiple_objects('fognoncontainer', ['fog_non_object', 'fog_non_object2']).body end tests('deleting non-empty container') do Fog::Storage[:rackspace].put_object('fogobjecttests', 'fog_object', lorem_file) expected = { "Number Not Found" => 0, "Response Status" => "400 Bad Request", "Errors" => [['fogobjecttests', '409 Conflict']], "Number Deleted" => 1, "Response Body" => "" } body = Fog::Storage[:rackspace].delete_multiple_objects(nil, ['fogobjecttests', 'fogobjecttests/fog_object']).body expected['Errors'][0][0] = body['Errors'][0][0] rescue nil returns(expected, 'deletes object but not container') { body } end end end @directory.destroy end fog-rackspace-0.1.6/tests/rackspace/requests/queues/0000755000004100000410000000000013411315054022530 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/queues/claim_tests.rb0000644000004100000410000000360413411315054025367 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | claim_tests', ['rackspace']) do service = Fog::Rackspace::Queues.new queue_name = 'fog' + Time.now.to_i.to_s client_id = service.client_id claim_id = nil service.create_queue(queue_name) tests('success') do tests("#create_claim(#{queue_name}, #{VALID_TTL}, #{VALID_GRACE}) => No Messages").returns(204) do service.create_claim(queue_name, VALID_TTL, VALID_GRACE).status end tests('with messages in the queue') do before do service.create_message(client_id, queue_name, { :message => "message-body"}, 300) end #TODO - Fix it so simple text bodies pass validation tests("#create_claim(#{queue_name}, #{VALID_TTL}, #{VALID_GRACE})").formats(CREATE_CLAIM_FORMAT) do response = service.create_claim(queue_name, VALID_TTL, VALID_GRACE) claim_id = response.headers['Location'].split('/').last response.body end tests("#get_claim(#{queue_name}, #{claim_id})").formats(CLAIM_FORMAT) do service.get_claim(queue_name, claim_id).body end tests("#update_claim(#{queue_name}, #{claim_id}, 500)").succeeds do service.update_claim(queue_name, claim_id, 500) end tests("#delete_claim(#{queue_name}, #{claim_id})").succeeds do service.delete_claim(queue_name, claim_id) end tests("#create_claim(#{queue_name}, #{VALID_TTL}, #{VALID_GRACE}, { :limit => 1})") do response = service.create_claim(queue_name, VALID_TTL, VALID_GRACE, { :limit => 1}) formats(CREATE_CLAIM_FORMAT) { response.body } returns(1) { response.body.length } end end end tests('failure') do tests("#get_claim('queue_name', 'nonexistentclaim') => Does not exist").raises(Fog::Rackspace::Queues::NotFound) do service.get_claim(queue_name, 'nonexistentclaim') end end service.delete_queue(queue_name) end fog-rackspace-0.1.6/tests/rackspace/requests/queues/helper.rb0000644000004100000410000000126013411315054024333 0ustar www-datawww-dataVALID_TTL = 300 VALID_GRACE = 300 METADATA_FORMAT = { } QUEUE_FORMAT = { 'metadata' => METADATA_FORMAT } LIST_QUEUES_FORMAT = { 'queues' => [ QUEUE_FORMAT.merge({ 'name' => String, 'href' => String, }) ], 'links' => LINKS_FORMAT } MESSAGE_FORMAT = { 'href' => String, 'ttl' => Integer, 'age' => Integer, 'body' => Hash } LIST_MESSAGES_FORMAT = { 'messages' => [MESSAGE_FORMAT], 'links' => LINKS_FORMAT } CREATE_CLAIM_FORMAT = [ MESSAGE_FORMAT ] CLAIM_FORMAT = { 'ttl' => Integer, 'age' => Integer, 'messages' => [ MESSAGE_FORMAT ] } QUEUE_STATS_FORMAT = { 'messages' => { 'free' => Integer, 'claimed' => Integer } } fog-rackspace-0.1.6/tests/rackspace/requests/queues/queues_tests.rb0000644000004100000410000000211013411315054025600 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | queue_tests', ['rackspace']) do service = Fog::Rackspace::Queues.new tests('success') do queue_name = 'fog' + Time.now.to_i.to_s tests("#create_queue(#{queue_name})").succeeds do service.create_queue(queue_name) end tests("#list_queues").formats(LIST_QUEUES_FORMAT) do response = service.list_queues response.body end tests("#get_queue(#{queue_name})").formats(QUEUE_FORMAT) do service.get_queue(queue_name).body end tests("#get_queue_stats(#{queue_name})").formats(QUEUE_STATS_FORMAT) do service.get_queue_stats(queue_name).body end tests("#delete_queue(#{queue_name})").succeeds do service.delete_queue(queue_name) end end tests('failure') do tests("#create_queue('') => Invalid Create Critera").raises(Fog::Rackspace::Queues::MethodNotAllowed) do service.create_queue('') end tests("#get_queue('nonexistentqueue') => Does not exist").raises(Fog::Rackspace::Queues::NotFound) do service.get_queue('nonexistentqueue') end end end fog-rackspace-0.1.6/tests/rackspace/requests/queues/messages_tests.rb0000644000004100000410000000376613411315054026122 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | messages_tests', ['rackspace']) do service = Fog::Rackspace::Queues.new queue_name = 'fog' + Time.now.to_i.to_s client_id = service.client_id message_id = nil service.create_queue(queue_name) begin tests('success') do tests("#list_message(#{client_id}, #{queue_name}, {:echo => true}) => No Content").returns(204) do service.list_messages(client_id, queue_name, {:echo => true}).status end tests("#create_message(#{client_id}, #{queue_name}, '{ :blah => 'blah' }', 300)").succeeds do response = service.create_message(client_id, queue_name, { :blah => 'blah' }, 300) message_id = response.body['resources'][0].split('/').last end tests("#list_message(#{client_id}, #{queue_name}, {:echo => true}) => With Content").formats(LIST_MESSAGES_FORMAT) do service.list_messages(client_id, queue_name, {:echo => true}).body end tests("#get_message(#{client_id}, #{queue_name}, #{message_id})").formats(MESSAGE_FORMAT) do service.get_message(client_id, queue_name, message_id).body end tests("#delete_message(#{queue_name}, #{message_id}, { :claim_id => '10' })").raises(Fog::Rackspace::Queues::ServiceError) do #API team should be changing this pending service.delete_message(queue_name, message_id, { :claim_id => '10' }) end tests("#delete_message(#{queue_name}, #{message_id})").succeeds do service.delete_message(queue_name, message_id) end end tests('failure') do tests("#create_message('') => Invalid Create Critera").raises(Fog::Rackspace::Queues::BadRequest) do service.create_message(client_id, queue_name, '', 0) end tests("#get_message('queue_name', 'nonexistentmessage') => Does not exist").raises(Fog::Rackspace::Queues::NotFound) do service.get_message(client_id, queue_name, 'nonexistentmessage') end end ensure service.delete_queue(queue_name) end end fog-rackspace-0.1.6/tests/rackspace/requests/auto_scale/0000755000004100000410000000000013411315054023340 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/auto_scale/helper.rb0000644000004100000410000001052413411315054025146 0ustar www-datawww-data### FORMATS LIST_GROUPS_FORMAT = { "groups_links"=>[], "groups"=> [ { "state" => { "paused"=> Fog::Boolean, "desiredCapacity"=> Integer, "active"=>[], "pendingCapacity"=> Integer, "activeCapacity"=> Integer, "name"=> String } } ] } GROUP_STATE_FORMAT = { "group" => { "paused"=> Fog::Boolean, "desiredCapacity" => Integer, "active"=>[], "pendingCapacity" => Integer, "activeCapacity" => Integer, "name"=> String } } GET_GROUP_HEADERS_FORMAT = { "Content-Type"=>String, "Via"=>String, "x-response-id"=>String, "Date"=>String, "Transfer-Encoding"=>String, "Server"=>String } GROUP_DELETE_DATA_FORMAT = { :headers=> { "Content-Type"=>String, "Via"=>String, "x-response-id"=>String, "Date"=>String, "Server"=>String }, :status=>Integer, :remote_ip=>String } LAUNCH_CONFIG_FORMAT = { "args" => { "loadBalancers" => [ { "port" => Integer, "loadBalancerId" => Integer } ], "server" => { "name" => String, "imageRef" => String, "flavorRef" => String, "OS-DCF =>diskConfig" => String, "metadata" => { "build_config" => String, "meta_key_1" => String, "meta_key_2" => String }, "networks" => [ { "uuid" => String }, { "uuid" => String } ], "personality" => [ { "path" => String, "contents" => String } ] } }, "type" => String } GROUP_CONFIG_FORMAT = { "maxEntities" => Integer, "cooldown" => Integer, "name" => String, "minEntities" => Integer, "metadata" => { "gc_meta_key_2" => String, "gc_meta_key_1" => String } } POLICY_FORMAT = { "name"=> String, "links"=> Array, "cooldown"=>Integer, "type"=>String, "id"=>String, "change"=>Integer } POLICIES_FORMAT = [POLICY_FORMAT] GROUP_FORMAT = { "group" => { "launchConfiguration" => LAUNCH_CONFIG_FORMAT, "groupConfiguration" => GROUP_CONFIG_FORMAT, "scalingPolicies" => POLICIES_FORMAT, "links" => [ { "href" => String, "rel" => String } ], "id" => String } } WEBHOOK_FORMAT = { "id" => String, "name" => String, "metadata" => Hash, "links" => Array } LIST_WEBHOOKS_FORMAT = [ { "id" => String, "name" => String, "links"=>[{"href" => String, "rel" => String }], "metadata"=>{} } ] ### OPTIONS LAUNCH_CONFIG_OPTIONS = { "args" => { "loadBalancers" => [ { "port" => 8080, "loadBalancerId" => 9099 } ], "server" => { "name" => "autoscale_server", "imageRef" => "0d589460-f177-4b0f-81c1-8ab8903ac7d8", "flavorRef" => "2", "OS-DCF =>diskConfig" => "AUTO", "metadata" => { "build_config" => "core", "meta_key_1" => "meta_value_1", "meta_key_2" => "meta_value_2" }, "networks" => [ { "uuid" => "11111111-1111-1111-1111-111111111111" }, { "uuid" => "00000000-0000-0000-0000-000000000000" } ], "personality" => [ { "path" => "/root/.csivh", "contents" => "VGhpcyBpcyBhIHRlc3QgZmlsZS4=" } ] } }, "type" => "launch_server" } GROUP_CONFIG_OPTIONS = { "maxEntities" => 3, "cooldown" => 360, "name" => "testscalinggroup198547", "minEntities" => 0, "metadata" => { "gc_meta_key_2" => "gc_meta_value_2", "gc_meta_key_1" => "gc_meta_value_1" } } POLICIES_OPTIONS = [ { "cooldown" => 0, "type" => "webhook", "name" => "scale up by 1", "change" => 1 } ] POLICY_OPTIONS = { "cooldown" => 0, "type" => "webhook", "name" => "FOOBAR", "change" => 1 } GROUP_OPTIONS = { "launchConfiguration" => LAUNCH_CONFIG_OPTIONS, "groupConfiguration" => GROUP_CONFIG_OPTIONS, "scalingPolicies" => POLICIES_OPTIONS } WEBHOOK_OPTIONS = { "name" => "webhook name", "metadata" => {'foo' => 'bar'} } def deactive_auto_scale_group(group) return unless group config = group.group_config config.min_entities = 0 config.max_entities = 0 config.save end fog-rackspace-0.1.6/tests/rackspace/requests/auto_scale/config_tests.rb0000644000004100000410000000616213411315054026361 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | config_tests', ['rackspace', 'rackspace_autoscale']) do pending if Fog.mocking? service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord begin @group = service.create_group(LAUNCH_CONFIG_OPTIONS, GROUP_CONFIG_OPTIONS, POLICIES_OPTIONS).body['group'] @group_id = @group['id'] tests('success') do tests('#get_group_config').formats({"groupConfiguration" => GROUP_CONFIG_FORMAT}) do service.get_group_config(@group_id).body end tests('#update_group_config').returns(204) do data = service.update_group_config(@group_id, { 'maxEntities' => 0, 'minEntities' => 0, 'metadata' => {}, 'name' => 'foo', 'cooldown' => 20}) data.status end tests('#get_launch_config').formats(LAUNCH_CONFIG_FORMAT) do service.get_launch_config(@group_id).body["launchConfiguration"] end tests('#update_launch_config').returns(204) do data = service.update_launch_config(@group_id, { "args" => { "loadBalancers" => [ { "port" => 8000, "loadBalancerId" => 9099 } ], "server" => { "name" => "autoscale_server", "imageRef" => "0d589460-f177-4b0f-81c1-8ab8903ac7d8", "flavorRef" => "2", "OS-DCF =>diskConfig" => "AUTO", "metadata" => { "build_config" => "core", "meta_key_1" => "meta_value_1", "meta_key_2" => "meta_value_2" }, "networks" => [ { "uuid" => "11111111-1111-1111-1111-111111111111" }, { "uuid" => "00000000-0000-0000-0000-000000000000" } ], "personality" => [ { "path" => "/root/.csivh", "contents" => "VGhpcyBpcyBhIHRlc3QgZmlsZS4=" } ] } }, "type" => "launch_server" }) data.status end end ensure service.delete_group(@group_id) end tests('failure') do tests('#update group config').raises(Fog::Rackspace::AutoScale::BadRequest) do service.update_group_config(@group_id, {}) end tests('#delete group config').raises(NoMethodError) do service.delete_group_config(123) end tests('#create group config').raises(NoMethodError) do service.create_group_config({}) end tests('#update launch config').raises(Fog::Rackspace::AutoScale::BadRequest) do service.update_launch_config(@group_id, {}) end tests('#delete launch config').raises(NoMethodError) do service.delete_launch_config(123) end tests('#create launch config').raises(NoMethodError) do service.create_launch_config({}) end end # @group['scalingPolicies'].each do |p| # service.delete_policy(@group_id, p['id']) # end # service.delete_group(@group_id) end fog-rackspace-0.1.6/tests/rackspace/requests/auto_scale/webhook_tests.rb0000644000004100000410000000405213411315054026546 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | webhook_tests', ['rackspace', 'rackspace_autoscale']) do pending if Fog.mocking? service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord begin @group_id = service.create_group(LAUNCH_CONFIG_OPTIONS, GROUP_CONFIG_OPTIONS, POLICIES_OPTIONS).body['group']['id'] @policy_id = service.create_policy(@group_id, POLICY_OPTIONS).body['policies'][0]['id'] tests('success') do tests('#create_webhook').formats(201) do response = service.create_webhook(@group_id, @policy_id, WEBHOOK_OPTIONS) @webhook_id = response.body['webhooks'][0]['id'] response.data[:status] end tests('#list_webhooks').formats(LIST_WEBHOOKS_FORMAT, false) do response = service.list_webhooks(@group_id, @policy_id).body["webhooks"] end tests('#get_webhook').formats(WEBHOOK_FORMAT) do response = service.get_webhook(@group_id, @policy_id, @webhook_id) response.body['webhook'] end tests('#update_webhook').formats(204) do response = service.update_webhook(@group_id, @policy_id, @webhook_id, {'name' => 'new', 'metadata' => {}} ) response.data[:status] end tests('#delete_webhook').formats(204) do response = service.delete_webhook(@group_id, @policy_id, @webhook_id) response.data[:status] end end ensure service.delete_policy @group_id, @policy_id service.delete_group @group_id end tests('failure') do tests('#create_webhook').raises(Fog::Rackspace::AutoScale::BadRequest) do service.create_webhook(@group_id, @policy_id, {}) end tests('#get_webhook').raises(Fog::Rackspace::AutoScale::NotFound) do service.get_webhook(@group_id, @policy_id, 123) end tests('#update_webhook').raises(Fog::Rackspace::AutoScale::BadRequest) do service.update_webhook(@group_id, @policy_id, @webhook_id, {}) end tests('#delete_webhook').raises(Fog::Rackspace::AutoScale::NotFound) do service.delete_webhook(@group_id, @policy_id, 123) end end end fog-rackspace-0.1.6/tests/rackspace/requests/auto_scale/policy_tests.rb0000644000004100000410000000417213411315054026412 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | policy_tests', ['rackspace', 'rackspace_autoscale']) do pending if Fog.mocking? service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord begin @group_id = service.create_group(LAUNCH_CONFIG_OPTIONS, GROUP_CONFIG_OPTIONS, POLICIES_OPTIONS).body['group']['id'] tests('success') do tests('#list policies').formats(POLICIES_FORMAT) do service.list_policies(@group_id).body['policies'] end tests('#create_policy').returns(201) do response = service.create_policy(@group_id, POLICY_OPTIONS) @policy_id = response.body['policies'][0]['id'] response.status end tests('#get_policy').formats(POLICY_FORMAT) do response = service.get_policy(@group_id, @policy_id) response.body['policy'] end tests('#execute_policy').returns(202) do service.execute_policy(@group_id, @policy_id).status end tests('#update_policy').returns(204) do response = service.update_policy(@group_id, @policy_id, { 'name' => 'foo', 'changePercent' => 1, 'type' => 'webhook', 'cooldown' => 100 }) response.status end tests('#delete_policy').returns(204) do response = service.delete_policy(@group_id, @policy_id) response.status end end ensure group = service.groups.get(@group_id) deactive_auto_scale_group(group) group.destroy end tests('failure') do tests('#create policy').raises(Fog::Rackspace::AutoScale::BadRequest) do service.create_policy(@group_id, {}) end tests('#get policy').raises(Fog::Rackspace::AutoScale::NotFound) do service.get_policy(@group_id, 123) end tests('#update policy').raises(Fog::Rackspace::AutoScale::BadRequest) do service.update_policy(@group_id, 123, {}) end tests('#execute policy').raises(Fog::Rackspace::AutoScale::NotFound) do service.execute_policy(@group_id, 123) end tests('#delete policy').raises(Fog::Rackspace::AutoScale::NotFound) do service.delete_policy(@group_id, 123) end end end fog-rackspace-0.1.6/tests/rackspace/requests/auto_scale/group_tests.rb0000644000004100000410000000306013411315054026242 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | group_tests', ['rackspace', 'rackspace_autoscale']) do pending if Fog.mocking? service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord tests('success') do tests('#create new group').formats(GROUP_FORMAT) do response = service.create_group(LAUNCH_CONFIG_OPTIONS, GROUP_CONFIG_OPTIONS, POLICIES_OPTIONS).body @group_id = response['group']['id'] response end tests('#list_groups').formats(LIST_GROUPS_FORMAT) do service.list_groups.body end tests('#get group').succeeds do [200, 204].include? service.get_group(@group_id).status end tests('#get group - body').formats(GROUP_FORMAT) do service.get_group(@group_id).body end tests('#get_group_state').formats(GROUP_STATE_FORMAT) do service.get_group_state(@group_id).body end tests('#pause_group_state') do pending end tests('#resume_group_state') do pending end tests('#delete group').returns(204) do service.delete_group(@group_id).status end end tests('failure') do tests('#fail to create group(-1)').raises(Fog::Rackspace::AutoScale::BadRequest) do service.create_group(@launch_config, @group_config, {}) end tests('#fail to get group(-1)').raises(Fog::Rackspace::AutoScale::NotFound) do service.get_group(-1) end tests('#update group').raises(NoMethodError) do service.update_group end tests('#fail to delete group(-1)').raises(Fog::Rackspace::AutoScale::NotFound) do service.delete_group(-1) end end end fog-rackspace-0.1.6/tests/rackspace/requests/networking/0000755000004100000410000000000013411315054023410 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/requests/networking/network_tests.rb0000644000004100000410000000223313411315054026650 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Networking | network_tests', ['rackspace']) do service = Fog::Rackspace::Networking.new network_format = { 'id' => String, 'label' => String, 'cidr' => Fog::Nullable::String } get_network_format = { 'network' => network_format } list_networks_format = { 'networks' => [network_format] } tests('success') do network_id = nil tests('#create_network').formats(get_network_format) do service.create_network("fog_#{Time.now.to_i.to_s}", '192.168.0.0/24').body.tap do |r| network_id = r['network']['id'] end end tests('#list_networks').formats(list_networks_format) do service.list_networks.body end tests('#get_network').formats(get_network_format) do service.get_network(network_id).body end tests('#delete_network').succeeds do service.delete_network(network_id) end end test('failure') do tests('#get_network').raises(Fog::Rackspace::Networking::NotFound) do service.get_network(0) end tests('#delete_network').raises(Fog::Rackspace::Networking::NotFound) do service.delete_network(0) end end end fog-rackspace-0.1.6/tests/rackspace/requests/networking/virtual_interface_tests.rb0000644000004100000410000000311313411315054030663 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Networking | virtual_interface_tests', ['rackspace']) do @service = Fog::Rackspace::Networking.new virtual_interface_format = { "virtual_interfaces"=> [{ "ip_addresses"=> [{ "network_id"=> String, "network_label"=> String, "address"=> String }], "id"=> String, "mac_address"=> String }] } begin unless Fog.mocking? network_id = nil @server = @service.servers.create(:name => "fog_virtual_interface_test_#{Time.now.to_i.to_s}", :flavor_id => rackspace_test_flavor_id(@service), :image_id => rackspace_test_image_id(@service)) @server.wait_for { ready? } @network = @service.networks.create(:label => "fog_#{Time.now.to_i.to_s}", :cidr => '192.168.0.0/24') end tests('success') do pending if Fog.mocking? tests('#create_virtual_interface').formats(virtual_interface_format) do response = @service.create_virtual_interface @server.id, @network.id body = response.body @virtual_network_interface_id = body["virtual_interfaces"].first["id"] body end tests('#list_virtual_interfaces').formats(virtual_interface_format) do @service.list_virtual_interfaces(@server.id).body end tests('#delete_virtual_interfaces').succeeds do @service.delete_virtual_interface(@server.id, @virtual_network_interface_id) end end ensure @server.destroy if @server delete_test_network @network end end fog-rackspace-0.1.6/tests/rackspace/databases_tests.rb0000644000004100000410000001441113411315054023045 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Databases', ['rackspace']) do |variable| pending if Fog.mocking? def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Rackspace::Databases.new assert_method nil, :authenticate_v2 assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('authentication v1') do pending if Fog.mocking? tests('variables populated') do @service = Fog::Rackspace::Databases.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").nil? } returns(true, "identity_service was not used") { @service.instance_variable_get("@identity_service").nil? } @service.flavors end tests('custom endpoint') do @service = Fog::Rackspace::Databases.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0', :rackspace_database_url => 'https://my-custom-endpoint.com' returns(false, "auth token populated") { @service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('authentication v2') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Rackspace::Databases.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => { :ssl_verify_peer => true } returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.flavors end tests('dfw region').succeeds do @service = Fog::Rackspace::Databases.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.flavors end tests('ord region').succeeds do @service = Fog::Rackspace::Databases.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/) != nil } @service.flavors end tests('custom endpoint') do @service = Fog::Rackspace::Databases.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_database_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('no params').succeeds do @service = Fog::Rackspace::Databases.new :rackspace_region => nil returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.flavors end tests('specify old contstant style service endoint').succeeds do @service = Fog::Rackspace::Databases.new :rackspace_endpoint => Fog::Rackspace::Databases::ORD_ENDPOINT returns(true) { (@service.instance_variable_get("@uri").to_s =~ /#{Fog::Rackspace::Databases::ORD_ENDPOINT}/ ) != nil } @service.flavors end tests('specify region').succeeds do @service = Fog::Rackspace::Databases.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/ ) != nil } @service.flavors end tests('custom endpoint') do @service = Fog::Rackspace::Databases.new :rackspace_database_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? tests('should reauth with valid credentials') do @service = Fog::Rackspace::Databases.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad_token") returns(200) { @service.list_flavors.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::Rackspace::Databases.new :rackspace_api_key => 'bad_key' } end end @service = Fog::Rackspace::Databases.new tests('#flavors').succeeds do data = @service.flavors returns(true) { data.is_a? Array } end tests('#instances').succeeds do data = @service.instances returns(true) { data.is_a? Array } end tests('#databases').succeeds do data = @service.databases returns(true) { data.is_a? Array } end tests('#users').succeeds do data = @service.users returns(true) { data.is_a? Array } end end fog-rackspace-0.1.6/tests/rackspace/compute_tests.rb0000644000004100000410000001146713411315054022602 0ustar www-datawww-dataShindo.tests('Rackspace | Compute', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Compute::Rackspace.new assert_method nil, :authenticate_v2 assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('authentication v1') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Compute::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").nil? } returns(true, "identity_service was not used") { @service.instance_variable_get("@identity_service").nil? } @service.list_flavors end tests('custom endpoint') do @service = Fog::Compute::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0', :rackspace_compute_v1_url => 'https://my-custom-endpoint.com' returns(false, "auth token populated") { @service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('authentication v2') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Compute::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => { :ssl_verify_peer => true } returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host == 'servers.api.rackspacecloud.com') != nil } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.list_flavors end tests('custom endpoint') do @service = Fog::Compute::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_compute_v1_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('no params').succeeds do @service = Fog::Compute::Rackspace.new :rackspace_region => nil returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host == 'servers.api.rackspacecloud.com') != nil } @service.list_flavors end tests('specify region').succeeds do @service = Fog::Compute::Rackspace.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host == 'servers.api.rackspacecloud.com') != nil } @service.list_flavors end tests('custom endpoint') do @service = Fog::Compute::Rackspace.new :rackspace_compute_v1_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? tests('should reauth with valid credentials') do @service = Fog::Compute::Rackspace.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad-token") returns(true) { [200, 203].include?(@service.list_flavors.status) } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::Compute::Rackspace.new :rackspace_api_key => 'bad_key' } end end end fog-rackspace-0.1.6/tests/rackspace/block_storage_tests.rb0000644000004100000410000001377713411315054023752 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::BlockStorage', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Rackspace::BlockStorage.new assert_method nil, :authenticate_v2 assert_method 'auth.api.rackspacecloud.com', :authenticate_v1 # chef's default auth endpoint assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('legacy authentication') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Rackspace::BlockStorage.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").path.nil? } returns(true, "identity_service was not used") { @service.instance_variable_get("@identity_service").nil? } @service.list_volumes end tests('custom endpoint') do @service = Fog::Rackspace::BlockStorage.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0', :rackspace_block_storage_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('current authentication') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Rackspace::BlockStorage.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => {:ssl_verify_peer => true} returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").host.nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.list_volumes end tests('dfw region').succeeds do @service = Fog::Rackspace::BlockStorage.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.list_volumes end tests('ord region').succeeds do @service = Fog::Rackspace::BlockStorage.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/) != nil } @service.list_volumes end tests('custom endpoint') do @service = Fog::Rackspace::BlockStorage.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_block_storage_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('no params').succeeds do @service = Fog::Rackspace::BlockStorage.new :rackspace_region => nil returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.list_volumes end tests('specify old contstant style service endoint').succeeds do @service = Fog::Rackspace::BlockStorage.new :rackspace_endpoint => Fog::Rackspace::BlockStorage::ORD_ENDPOINT returns(true) { (@service.instance_variable_get("@uri").to_s =~ /#{Fog::Rackspace::BlockStorage::ORD_ENDPOINT}/ ) != nil } @service.list_volumes end tests('specify region') do @service = Fog::Rackspace::BlockStorage.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/ ) != nil } @service.list_volumes end tests('custom endpoint') do @service = Fog::Rackspace::BlockStorage.new :rackspace_block_storage_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? tests('should reauth with valid credentials') do @service = Fog::Rackspace::BlockStorage.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad-token") returns(200) { @service.list_volumes.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) {Fog::Rackspace::BlockStorage.new :rackspace_api_key => 'bad_key' } end end end fog-rackspace-0.1.6/tests/rackspace/helper.rb0000644000004100000410000000643013411315054021155 0ustar www-datawww-dataLINKS_FORMAT = [{ 'href' => String, 'rel' => String }] module Shindo class Tests def given_a_load_balancer_service(&block) @service = Fog::Rackspace::LoadBalancers.new instance_eval(&block) end def given_a_load_balancer(&block) @lb = @service.load_balancers.create({ :name => ('fog' + Time.now.to_i.to_s), :protocol => 'HTTP', :port => 80, :virtual_ips => [{ :type => 'PUBLIC'}], :nodes => [{ :address => '1.1.1.1', :port => 80, :condition => 'ENABLED'}] }) @lb.wait_for { ready? } begin instance_eval(&block) ensure @lb.wait_for { ready? } @lb.destroy end end def wait_for_request(description = "waiting", &block) return if Fog.mocking? tests(description) do Fog.wait_for &block end end def wait_for_server_deletion(server) return if Fog.mocking? begin @instance.wait_for { state = 'DELETED' } rescue Fog::Compute::RackspaceV2::NotFound => e # do nothing end end def wait_for_server_state(service, server_id, state, error_states=nil) current_state = nil until current_state == state current_state = service.get_server(server_id).body['server']['status'] if error_states error_states = Array(error_states) if error_states.include?(current_state) Fog::Logger.warning caller Fog::Logger.warning "ERROR! Server should have transitioned to '#{state}' not '#{current_state}'" return end end sleep 10 unless Fog.mocking? end sleep 30 unless Fog.mocking? end def wait_for_volume_state(service, volume_id, state) current_state = nil until current_state == state current_state = service.get_volume(volume_id).body['volume']['status'] if current_state == 'error' Fog::Logger.warning caller Fog::Logger.warning "Volume is in an error state!" return end sleep 10 unless Fog.mocking? end end def rackspace_test_image_id(service) image_id = Fog.credentials[:rackspace_image_id] # I chose to use the first Ubuntu because it will work with the smallest flavor and it doesn't require a license image_id ||= Fog.mocking? ? service.images.first.id : service.images.find {|image| image.name =~ /Ubuntu/}.id # use the first Ubuntu image end def rackspace_test_flavor_id(service) @flavor_id ||= Fog.credentials[:rackspace_flavor_id] || service.flavors.first.id end # After a server has been successfully deleted they are still being reported as attached to a cloud network # causing delete calls to fail. This method attempts to address that. def delete_test_network(network) return false if Fog.mocking? || network.nil? attempt = 0 begin network.destroy rescue Fog::Compute::RackspaceV2::ServiceError => e if attempt == 3 Fog::Logger.warning "Unable to delete #{network.label}" return false end Fog::Logger.warning "Network #{network.label} Delete Fail Attempt #{attempt}- #{e.inspect}" attempt += 1 sleep 60 retry end return true end end end fog-rackspace-0.1.6/tests/rackspace/compute_v2_tests.rb0000644000004100000410000001367213411315054023211 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Compute::RackspaceV2.new assert_method nil, :authenticate_v2 assert_method 'auth.api.rackspacecloud.com', :authenticate_v1 # chef's default auth endpoint assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('legacy authentication') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Compute::RackspaceV2.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").path.nil? } returns(true, "identity_service was not used") { @service.instance_variable_get("@identity_service").nil? } @service.list_flavors end tests('custom endpoint') do @service = Fog::Compute::RackspaceV2.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0', :rackspace_compute_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('current authentation') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Compute::RackspaceV2.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => {:ssl_verify_peer => true} returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").host.nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.list_flavors end tests('dfw region').succeeds do @service = Fog::Compute::RackspaceV2.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.list_flavors end tests('ord region').succeeds do @service = Fog::Compute::RackspaceV2.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/) != nil } @service.list_flavors end tests('custom endpoint') do @service = Fog::Compute::RackspaceV2.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_compute_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('no params').succeeds do @service = Fog::Compute::RackspaceV2.new :rackspace_region => nil returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.list_flavors end tests('specify old contstant style service endoint').succeeds do @service = Fog::Compute::RackspaceV2.new :rackspace_endpoint => Fog::Compute::RackspaceV2::ORD_ENDPOINT returns(true) { (@service.instance_variable_get("@uri").to_s =~ /#{Fog::Compute::RackspaceV2::ORD_ENDPOINT}/ ) != nil } @service.list_flavors end tests('specify region').succeeds do @service = Fog::Compute::RackspaceV2.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/ ) != nil } @service.list_flavors end tests('custom endpoint') do @service = Fog::Compute::RackspaceV2.new :rackspace_compute_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? tests('should reauth with valid credentials') do @service = Fog::Compute::RackspaceV2.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad_token") returns(true) { [200, 203].include? @service.list_flavors.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::Compute::RackspaceV2.new :rackspace_api_key => 'bad_key' } end end end fog-rackspace-0.1.6/tests/rackspace/monitoring_tests.rb0000644000004100000410000000716113411315054023307 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring', ['rackspace','rackspace_monitoring']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Rackspace::Monitoring.new assert_method nil, :authenticate_v2 assert_method 'auth.api.rackspacecloud.com', :authenticate_v1 # chef's default auth endpoint assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('current authentation') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Rackspace::Monitoring.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => {:ssl_verify_peer => true} returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").host.nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.list_entities end tests('custom endpoint') do @service = Fog::Rackspace::Monitoring.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_monitoring_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('no params').succeeds do @service = Fog::Rackspace::Monitoring.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /monitoring.api.rackspacecloud.com/) != nil } @service.list_entities end tests('custom endpoint') do @service = Fog::Rackspace::Monitoring.new :rackspace_monitoring_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? tests('should reauth with valid credentials') do @service = Fog::Rackspace::Monitoring.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad_token") returns(true) { [200, 203].include? @service.list_entities.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::Rackspace::Monitoring.new :rackspace_api_key => 'bad_key' } end end end fog-rackspace-0.1.6/tests/rackspace/auto_scale_tests.rb0000644000004100000410000001024413411315054023235 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Rackspace::AutoScale.new :rackspace_region => :dfw assert_method nil, :authenticate_v2 assert_method 'auth.api.rackspacecloud.com', :authenticate_v1 # chef's default auth endpoint assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('current authentation') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Rackspace::AutoScale.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => {:ssl_verify_peer => true}, :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").host.nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.list_groups end tests('dfw region').succeeds do @service = Fog::Rackspace::AutoScale.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.list_groups end tests('ord region').succeeds do @service = Fog::Rackspace::AutoScale.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/) != nil } @service.list_groups end tests('custom endpoint') do @service = Fog::Rackspace::AutoScale.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_auto_scale_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('specify region').succeeds do @service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/ ) != nil } @service.list_groups end tests('custom endpoint') do @service = Fog::Rackspace::AutoScale.new :rackspace_auto_scale_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? @service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad_token") returns(true) { [200, 203].include? @service.list_groups.status } end end fog-rackspace-0.1.6/tests/rackspace/storage_tests.rb0000644000004100000410000001425113411315054022564 0ustar www-datawww-dataShindo.tests('Rackspace | Storage', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Storage::Rackspace.new assert_method nil, :authenticate_v2 assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('authentication v1') do tests('variables populated').succeeds do @service = Fog::Storage::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").nil? } returns(true, "identity_service was not used") { @service.instance_variable_get("@identity_service").nil? } @service.head_containers end tests('custom endpoint') do @service = Fog::Storage::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0', :rackspace_storage_url => 'https://my-custom-endpoint.com' returns(false, "auth token populated") { @service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('authentation v2') do tests('variables populated').succeeds do @service = Fog::Storage::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => { :ssl_verify_peer => true } returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.head_containers end tests('dfw region').succeeds do @service = Fog::Storage::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw\d/) != nil } @service.head_containers end tests('ord region').succeeds do @service = Fog::Storage::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord\d/) != nil } @service.head_containers end tests('custom endpoint').succeeds do @service = Fog::Storage::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_storage_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do tests('no params').succeeds do @service = Fog::Storage::Rackspace.new :rackspace_region => nil returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw\d/) != nil } @service.head_containers end tests('specify region').succeeds do @service = Fog::Storage::Rackspace.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord\d/ ) != nil } @service.head_containers end tests('custom endpoint') do @service = Fog::Storage::Rackspace.new :rackspace_storage_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end tests('rackspace_servicenet') do @service = Fog::Storage::Rackspace.new :rackspace_servicenet => true returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /snet-/) != nil } end end tests('reauthentication') do tests('should reauth with valid credentials') do @service = Fog::Storage::Rackspace.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad-token") returns(204) { @service.head_containers.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::Storage::Rackspace.new :rackspace_api_key => 'bad_key' } end end tests('account').succeeds do Fog::Storage[:rackspace].account end tests('ssl') do tests('ssl enabled') do @service = Fog::Storage::Rackspace.new(:rackspace_cdn_ssl => true) returns(true) { @service.ssl? } end tests('ssl disabled') do @service = Fog::Storage::Rackspace.new(:rackspace_cdn_ssl => false) returns(false) { @service.ssl? } @service = Fog::Storage::Rackspace.new(:rackspace_cdn_ssl => nil) returns(false) { @service.ssl? } end end end fog-rackspace-0.1.6/tests/rackspace/service_tests.rb0000644000004100000410000000456513411315054022567 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Service', ['rackspace']) do tests('process_response') do @service = Fog::Rackspace::Service.new tests('nil').returns(nil) do @service.send(:process_response, nil) end tests('response missing body').returns(nil) do response = Excon::Response.new response.body = nil @service.send(:process_response, response) end tests('processes body').returns({'a'=>2, 'b'=>3}) do response = Excon::Response.new response.headers['Content-Type'] = "application/json" response.body = "{\"a\":2,\"b\":3}" @service.send(:process_response, response) response.body end tests('process body with hash').returns({:a=>2, :b=>3}) do response = Excon::Response.new response.headers['Content-Type'] = "application/json" response.body = {:a=>2, :b=>3} @service.send(:process_response, response) response.body end tests('handles malformed json').returns({}) do response = Excon::Response.new response.headers['Content-Type'] = "application/json" response.body = "I am totally not json" @service.send(:process_response, response) response.body end end tests('headers') do # adding an implementation for auth_token to service instance. Normally this would come from a subclass. def @service.auth_token "my_auth_token" end HEADER_HASH = { 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-Auth-Token' => @service.auth_token }.freeze tests('without options').returns(HEADER_HASH) do @service.send(:headers) end tests('with options not containing :header key').returns(HEADER_HASH) do @service.send(:headers, {:a => 3}) end tests('with options containing :header key').returns(HEADER_HASH.merge(:a => 3)) do @service.send(:headers, :headers => {:a => 3}) end end tests('request_params') do REQUEST_HASH = { :path=>"/endpoint/my_service", :headers=>{"Content-Type"=>"application/json", "Accept"=>"application/json", "X-Auth-Token"=>"my_auth_token"}, }.freeze uri = URI.parse("http://fog.io/endpoint") @service.instance_variable_set("@uri", uri) params = {:path => 'my_service'} tests('returns request hash').returns(REQUEST_HASH) do @service.send(:request_params, params) end end end fog-rackspace-0.1.6/tests/rackspace/models/0000755000004100000410000000000013411315054020631 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/identity/0000755000004100000410000000000013411315054022462 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/identity/credentials_tests.rb0000644000004100000410000000121513411315054026525 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity | credentials', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Identity.new user = service.users.all.first tests('success') do tests("#all").succeeds do credentials = user.credentials.all credentials.all? { |c| c.username && c.apiKey } end tests("#get").succeeds do list_credential = user.credentials.all.first credential = user.credentials.get(list_credential.identity) credential.username && credential.apiKey end end tests("failure").returns(nil) do user.credentials.get('i am a credential that does not exist') end end fog-rackspace-0.1.6/tests/rackspace/models/identity/service_catalog_tests.rb0000644000004100000410000002643713411315054027377 0ustar www-datawww-datarequire 'fog/rackspace/models/identity/service_catalog' Shindo.tests('Fog::Rackspace::ServiceCatalog | users', ['rackspace']) do tests('successful') do before_hash = {"access"=>{"token"=>{"expires"=>"2013-02-20T10:31:00.000-06:00", "tenant"=>{"name"=>"777", "id"=>"777"}, "id"=>"6ca10877-7c50-4a5c-b58f-004d835c39c3"}, "serviceCatalog"=>[{"type"=>"volume", "endpoints"=>[{"region"=>"DFW", "tenantId"=>"777", "publicURL"=>"https://dfw.blockstorage.api.rackspacecloud.com/v1/777"}, {"region"=>"ORD", "tenantId"=>"777", "publicURL"=>"https://ord.blockstorage.api.rackspacecloud.com/v1/777"}], "name"=>"cloudBlockStorage"}, {"type"=>"rax:load-balancer", "endpoints"=>[{"region"=>"ORD", "tenantId"=>"777", "publicURL"=>"https://ord.loadbalancers.api.rackspacecloud.com/v1.0/777"}, {"region"=>"DFW", "tenantId"=>"777", "publicURL"=>"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/777"}], "name"=>"cloudLoadBalancers"}, {"type"=>"object-store", "endpoints"=>[{"internalURL"=>"https://snet-storage101.dfw1.clouddrive.com/v1/Mosso777", "region"=>"DFW", "tenantId"=>"Mosso777", "publicURL"=>"https://storage101.dfw1.clouddrive.com/v1/Mosso777"}, {"internalURL"=>"https://snet-storage101.ord1.clouddrive.com/v1/Mosso777", "region"=>"ORD", "tenantId"=>"Mosso777", "publicURL"=>"https://storage101.ord1.clouddrive.com/v1/Mosso777"}], "name"=>"cloudFiles"}, {"type"=>"rax:database", "endpoints"=>[{"region"=>"DFW", "tenantId"=>"777", "publicURL"=>"https://dfw.databases.api.rackspacecloud.com/v1.0/777"}, {"region"=>"ORD", "tenantId"=>"777", "publicURL"=>"https://ord.databases.api.rackspacecloud.com/v1.0/777"}], "name"=>"cloudDatabases"}, {"type"=>"rax:dns", "endpoints"=>[{"tenantId"=>"777", "publicURL"=>"https://dns.api.rackspacecloud.com/v1.0/777"}], "name"=>"cloudDNS"}, {"type"=>"compute", "endpoints"=>[{"versionId"=>"1.0", "tenantId"=>"777", "versionList"=>"https://servers.api.rackspacecloud.com/", "versionInfo"=>"https://servers.api.rackspacecloud.com/v1.0", "publicURL"=>"https://servers.api.rackspacecloud.com/v1.0/777"}], "name"=>"cloudServers"}, {"type"=>"compute", "endpoints"=>[{"region"=>"DFW", "versionId"=>"2", "tenantId"=>"777", "versionList"=>"https://dfw.servers.api.rackspacecloud.com/", "versionInfo"=>"https://dfw.servers.api.rackspacecloud.com/v2", "publicURL"=>"https://dfw.servers.api.rackspacecloud.com/v2/777"}, {"region"=>"ORD", "versionId"=>"2", "tenantId"=>"777", "versionList"=>"https://ord.servers.api.rackspacecloud.com/", "versionInfo"=>"https://ord.servers.api.rackspacecloud.com/v2", "publicURL"=>"https://ord.servers.api.rackspacecloud.com/v2/777"}, {"versionId"=>"2", "tenantId"=>"777", "versionList"=>"https://servers.api.rackspacecloud.com/", "versionInfo"=>"https://servers.api.rackspacecloud.com/v2", "publicURL"=>"https://servers.api.rackspacecloud.com/v2/777"}], "name"=>"cloudServersOpenStack"}, {"type"=>"rax:monitor", "endpoints"=>[{"tenantId"=>"777", "publicURL"=>"https://monitoring.api.rackspacecloud.com/v1.0/777"}], "name"=>"cloudMonitoring"}, {"type"=>"rax:object-cdn", "endpoints"=>[{"region"=>"DFW", "tenantId"=>"Mosso777", "publicURL"=>"https://cdn1.clouddrive.com/v1/Mosso777"}, {"region"=>"ORD", "tenantId"=>"Mosso777", "publicURL"=>"https://cdn2.clouddrive.com/v1/Mosso777"}], "name"=>"cloudFilesCDN"}, {"type"=>"not_here", "name" => "not_here", "endpoints"=>[{"tenantId"=>"777", "region" => "LON", "publicURL"=>"https://monitoring.api.rackspacecloud.com/v1.0/777"}]} ], "user"=>{"roles"=>[{"description"=>"User Admin Role.", "name"=>"identity:user-admin", "id"=>"3"}], "name"=>"joe-racker", "RAX-AUTH:defaultRegion"=>"", "id"=>"TK421"}}} @service_catalog = Fog::Rackspace::Identity::ServiceCatalog.from_response(nil, before_hash) end tests('services') do services = ["cloudBlockStorage", "cloudDNS", "cloudDatabases", "cloudFiles", "cloudFilesCDN", "cloudLoadBalancers", "cloudMonitoring", "cloudServers", "cloudServersOpenStack", "not_here"] returns(services) { @service_catalog.services.map {|s| s.to_s }.sort } end tests('get_endpoints') do endpoints = [{"region"=>"DFW", "versionId"=>"2", "tenantId"=>"777", "versionList"=>"https://dfw.servers.api.rackspacecloud.com/", "versionInfo"=>"https://dfw.servers.api.rackspacecloud.com/v2", "publicURL"=>"https://dfw.servers.api.rackspacecloud.com/v2/777"}, {"region"=>"ORD", "versionId"=>"2", "tenantId"=>"777", "versionList"=>"https://ord.servers.api.rackspacecloud.com/", "versionInfo"=>"https://ord.servers.api.rackspacecloud.com/v2", "publicURL"=>"https://ord.servers.api.rackspacecloud.com/v2/777"}, {"versionId"=>"2", "tenantId"=>"777", "versionList"=>"https://servers.api.rackspacecloud.com/", "versionInfo"=>"https://servers.api.rackspacecloud.com/v2", "publicURL"=>"https://servers.api.rackspacecloud.com/v2/777"}] returns(endpoints) { @service_catalog.get_endpoints(:cloudServersOpenStack) } returns(endpoints) { @service_catalog.get_endpoints('cloudServersOpenStack') } returns({}) { @service_catalog.get_endpoints('non-existent') } end tests('get_endpoint') do tests('service with mulitple endpoints') do returns("https://dfw.servers.api.rackspacecloud.com/v2/777") { @service_catalog.get_endpoint(:cloudServersOpenStack, :dfw) } returns("https://ord.servers.api.rackspacecloud.com/v2/777") { @service_catalog.get_endpoint(:cloudServersOpenStack, :ord) } returns("https://dfw.servers.api.rackspacecloud.com/v2/777") { @service_catalog.get_endpoint(:cloudServersOpenStack, 'dfw') } returns("https://dfw.servers.api.rackspacecloud.com/v2/777") { @service_catalog.get_endpoint('cloudServersOpenStack', 'dfw') } returns("https://servers.api.rackspacecloud.com/v2/777") { @service_catalog.get_endpoint('cloudServersOpenStack', :global) } end tests('with one endpoint') do tests('catalog contains global endpoint') do catalog_hash = [{"type"=>"volume", "endpoints"=>[{"tenantId"=>"777", "publicURL"=>"https://blockstorage.api.rackspacecloud.com/v1/777"}], "name"=>"cloudBlockStorage"}] @service_catalog = Fog::Rackspace::Identity::ServiceCatalog.new(:service => nil, :catalog => catalog_hash) tests('no region specifed').returns("https://blockstorage.api.rackspacecloud.com/v1/777") do @service_catalog.get_endpoint(:cloudBlockStorage) end tests('region specifed').returns("https://blockstorage.api.rackspacecloud.com/v1/777") do @service_catalog.get_endpoint(:cloudBlockStorage, :ord) end end tests('catalog does not contain global endpoint') do catalog_hash = [{"type"=>"volume", "endpoints"=>[{"region" => "ORD", "tenantId"=>"777", "publicURL"=>"https://ord.blockstorage.api.rackspacecloud.com/v1/777"}], "name"=>"cloudBlockStorage"}] @service_catalog = Fog::Rackspace::Identity::ServiceCatalog.new(:service => nil, :catalog => catalog_hash) tests('non-existing region') do raises(RuntimeError) { @service_catalog.get_endpoint(:cloudBlockStorage, :dfw) } end tests('existing region').returns("https://ord.blockstorage.api.rackspacecloud.com/v1/777") do @service_catalog.get_endpoint(:cloudBlockStorage, :ord) end end end tests('endpoint type') do catalog_hash = [{"type"=>"object-store", "endpoints"=>[{"internalURL"=>"https://snet-storage101.dfw1.clouddrive.com/v1/Mosso777", "region"=>"DFW", "tenantId"=>"Mosso777", "publicURL"=>"https://storage101.dfw1.clouddrive.com/v1/Mosso777"}, {"internalURL"=>"https://snet-storage101.ord1.clouddrive.com/v1/Mosso777", "region"=>"ORD", "tenantId"=>"Mosso777", "publicURL"=>"https://storage101.ord1.clouddrive.com/v1/Mosso777"}], "name"=>"cloudFiles"}] @service_catalog = Fog::Rackspace::Identity::ServiceCatalog.new(:service => nil, :catalog => catalog_hash) returns("https://storage101.ord1.clouddrive.com/v1/Mosso777") { @service_catalog.get_endpoint(:cloudFiles, :ord) } returns("https://snet-storage101.ord1.clouddrive.com/v1/Mosso777") { @service_catalog.get_endpoint(:cloudFiles, :ord, true) } returns("https://storage101.ord1.clouddrive.com/v1/Mosso777") { @service_catalog.get_endpoint(:cloudFiles, :ord, false) } end tests('error conditions') do raises(RuntimeError) { @service_catalog.get_endpoint(:cloudServersOpenStack) } raises(RuntimeError) { @service_catalog.get_endpoint(:cloudServersOpenStack, :sat) } raises(RuntimeError) { @service_catalog.get_endpoint(:cloudServersOpenStack, :sat, true) } raises(RuntimeError) { @service_catalog.get_endpoint(:not_here, :dfw) } raises(RuntimeError) { @service_catalog.get_endpoint('non-existent') } raises(RuntimeError) { @service_catalog.get_endpoint(:cloudServersOpenStack, :ord, true) } end end tests('reload').succeeds do pending if Fog.mocking? service = Fog::Identity[:rackspace] service_catalog = service.service_catalog service_catalog.catalog << {"name"=>"fakeService", "endpoints"=>[{ "publicURL"=>"http:///fake-endpoint.com"}]} returns("http:///fake-endpoint.com") { service_catalog.get_endpoint :fakeService } returns("http:///fake-endpoint.com") { service.service_catalog.get_endpoint :fakeService } service_catalog.reload raises(RuntimeError) { service_catalog.get_endpoint :fakeService } raises(RuntimeError) { service.service_catalog.get_endpoint :fakeService } end tests('display_service_regions') do tests('with global endpoint').returns(":dfw, :ord, :global") do catalog_hash = [{"type"=>"compute", "endpoints"=>[{"region"=>"DFW", "versionId"=>"2", "tenantId"=>"777", "versionList"=>"https://dfw.servers.api.rackspacecloud.com/", "versionInfo"=>"https://dfw.servers.api.rackspacecloud.com/v2", "publicURL"=>"https://dfw.servers.api.rackspacecloud.com/v2/777"}, {"region"=>"ORD", "versionId"=>"2", "tenantId"=>"777", "versionList"=>"https://ord.servers.api.rackspacecloud.com/", "versionInfo"=>"https://ord.servers.api.rackspacecloud.com/v2", "publicURL"=>"https://ord.servers.api.rackspacecloud.com/v2/777"}, {"versionId"=>"2", "tenantId"=>"777", "versionList"=>"https://servers.api.rackspacecloud.com/", "versionInfo"=>"https://servers.api.rackspacecloud.com/v2", "publicURL"=>"https://servers.api.rackspacecloud.com/v2/777"}], "name"=>"cloudServersOpenStack"}] @service_catalog = Fog::Rackspace::Identity::ServiceCatalog.new(:service => nil, :catalog => catalog_hash) @service_catalog.display_service_regions(:cloudServersOpenStack) end tests('endpoint types') do catalog_hash = [{"type"=>"object-store", "endpoints"=>[{"internalURL"=>"https://snet-storage101.dfw1.clouddrive.com/v1/Mosso777", "region"=>"DFW", "tenantId"=>"Mosso777", "publicURL"=>"https://storage101.dfw1.clouddrive.com/v1/Mosso777"}, { "region"=>"ORD", "tenantId"=>"Mosso777", "publicURL"=>"https://storage101.ord1.clouddrive.com/v1/Mosso777"}], "name"=>"cloudFiles"},] @service_catalog = Fog::Rackspace::Identity::ServiceCatalog.new(:service => nil, :catalog => catalog_hash) tests('public').returns(":dfw, :ord") do @service_catalog.display_service_regions(:cloudFiles) end tests('private').returns(":dfw") do @service_catalog.display_service_regions(:cloudFiles, true) end end end end fog-rackspace-0.1.6/tests/rackspace/models/identity/users_tests.rb0000644000004100000410000000065413411315054025377 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity | users', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Identity.new username = "fog#{Time.now.to_i.to_s}" options = { :username => username, :email => 'email@example.com', :enabled => true } collection_tests(service.users, options, false) do tests('#get_by_name').succeeds do service.users.get_by_name(username) end end end fog-rackspace-0.1.6/tests/rackspace/models/identity/tenants_tests.rb0000644000004100000410000000071713411315054025712 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity | tenants', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Identity.new username = "fog_user_#{Time.now.to_i.to_s}" options = { :username => username, :email => 'email@example.com', :enabled => true } tests("#all").succeeds do service.tenants.all end tests("#get").succeeds do tenant = service.tenants.all.first service.tenants.get(tenant.identity) end end fog-rackspace-0.1.6/tests/rackspace/models/identity/user_tests.rb0000644000004100000410000000061013411315054025204 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity | user', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Identity.new options = { :username => "fog#{Time.now.to_i.to_s}", :email => 'email@example.com', :enabled => true } model_tests(service.users, options, false) do tests('#save with existing user').succeeds do @instance.save end end end fog-rackspace-0.1.6/tests/rackspace/models/identity/roles_tests.rb0000644000004100000410000000051013411315054025351 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity | roles', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Identity.new user = service.users.all.first tests("#all").succeeds do user.roles.all end tests("#get").succeeds do role = user.roles.all.first user.roles.get(role.identity) end end fog-rackspace-0.1.6/tests/rackspace/models/dns/0000755000004100000410000000000013411315054021415 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/dns/zones_tests.rb0000644000004100000410000000273513411315054024331 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::DNS | zones', ['rackspace']) do provider = Fog::DNS[:rackspace] domain_sld = uniq_id domain_name = domain_sld + '.com' begin unless Fog.mocking? zone = provider.zones.create({:domain => domain_name, :email => "hostmaster@#{domain_name}"}) end tests("zones.find(#{domain_sld}) => finds domain_name") do pending if Fog.mocking? returns(true) { provider.zones.all.any? {|z| z.domain == domain_name} } end random_name = uniq_id tests("zones.find(#{random_name}) => finds nothing") do pending if Fog.mocking? returns(false) { provider.zones.all.any? {|z| z.domain == random_name} } end ensure zone.destroy unless Fog.mocking? end tests('next_params') do zones = Fog::DNS::Rackspace::Zones.new returns(nil, "no body") { zones.send(:next_params, nil)} returns(nil, "no links") { zones.send(:next_params, {}) } returns(nil, "links are empty") { zones.send(:next_params, {'links' => []}) } returns(nil, "links does not contain next hash") { zones.send(:next_params, {'links' => [ {'rel' => 'previous'} ] }) } returns(nil, "contains a link without parameters") { zones.send(:next_params, {'links' => [ {'rel' => 'next', 'href' => "http://localhost/next"} ] }) } returns({"offset"=>["3"], "limit"=>["3"]}, "contains a link without parameters") { zones.send(:next_params, {'links' => [ {'rel' => 'next', 'href' => "http://localhost/next?offset=3&limit=3"} ] }) } end end fog-rackspace-0.1.6/tests/rackspace/models/dns/zone_tests.rb0000644000004100000410000000072113411315054024137 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::DNS | zone', ['rackspace']) do pending if Fog.mocking? provider = Fog::DNS[:rackspace] domain_name = uniq_id + '.com' zone = provider.zones.create({:domain => domain_name, :email => 'hostmaster@' + domain_name}) tests('adding same domain twice throws error').raises(Fog::DNS::Rackspace::CallbackError) do provider.zones.create({:domain => domain_name, :email => 'hostmaster@' + domain_name}) end zone.destroy end fog-rackspace-0.1.6/tests/rackspace/models/databases/0000755000004100000410000000000013411315054022560 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/databases/databases_tests.rb0000644000004100000410000000065113411315054026260 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Databases | databases', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new instance = service.instances.create({ :name => "fog_instance_#{Time.now.to_i.to_s}", :flavor_id => 1, :volume_size => 1 }) instance.wait_for { ready? } collection_tests(instance.databases, { :name => "db_#{Time.now.to_i.to_s}" }, false) instance.destroy end fog-rackspace-0.1.6/tests/rackspace/models/databases/database_tests.rb0000644000004100000410000000147313411315054026100 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Databases | database', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new instance = service.instances.create({ :name => "fog_instance_#{Time.now.to_i.to_s}", :flavor_id => 1, :volume_size => 1 }) instance.wait_for { ready? } model_tests(instance.databases, { :name => "db_#{Time.now.to_i.to_s}" }, false) user_no_host = instance.users.create(:name => "foo", :password => "foo") user_with_host = instance.users.create(:name => "bar", :host => "10.20.30.40", :password => "bar") db = instance.databases.create(:name => "Test_#{Time.now.to_i}") db.grant_access_for(user_no_host) db.grant_access_for(user_with_host) db.revoke_access_for(user_no_host) db.revoke_access_for(user_with_host) instance.destroy end fog-rackspace-0.1.6/tests/rackspace/models/databases/instances_tests.rb0000644000004100000410000000054313411315054026320 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Databases | instances', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new options = { :name => "fog_instance_#{Time.now.to_i.to_s}", :flavor_id => 1, :volume_size => 1 } collection_tests(service.instances, options, false) do @instance.wait_for { ready? } end end fog-rackspace-0.1.6/tests/rackspace/models/databases/users_tests.rb0000644000004100000410000000073213411315054025472 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Databases | users', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new instance = service.instances.create({ :name => "fog_instance_#{Time.now.to_i.to_s}", :flavor_id => 1, :volume_size => 1 }) instance.wait_for { ready? } options = { :name => "user_#{Time.now.to_i.to_s}", :password => "fog_user" } collection_tests(instance.users, options, false) instance.destroy end fog-rackspace-0.1.6/tests/rackspace/models/databases/instance_tests.rb0000644000004100000410000000224313411315054026134 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Databases | instance', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new options = { :name => "fog_instance_#{Time.now.to_i.to_s}", :flavor_id => 1, :volume_size => 1 } model_tests(service.instances, options, false) do @instance.wait_for { ready? } tests('root_user_enabled before user is enabled').returns(false) do @instance.root_user_enabled? end @instance.wait_for { ready? } tests('enable_root_user sets root user and password').succeeds do @instance.enable_root_user returns(false) { @instance.root_user.nil? } returns(false) { @instance.root_password.nil? } end @instance.wait_for { ready? } tests('restarts instance').succeeds do @instance.restart returns('REBOOT') { @instance.state } end @instance.wait_for { ready? } tests('resizes instance').succeeds do @instance.resize(2) returns('RESIZE') { @instance.state } end @instance.wait_for { ready? } tests('restarts instance').succeeds do @instance.resize_volume(2) returns('RESIZE') { @instance.state } end end end fog-rackspace-0.1.6/tests/rackspace/models/databases/flavors_tests.rb0000644000004100000410000000061313411315054026003 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Databases | flavors', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new tests("success") do tests("#all").succeeds do service.flavors.all end tests("#get").succeeds do service.flavors.get(1) end end tests("failure").returns(nil) do service.flavors.get('some_random_identity') end end fog-rackspace-0.1.6/tests/rackspace/models/databases/user_tests.rb0000644000004100000410000000072413411315054025310 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Databases | user', ['rackspace']) do pending if Fog.mocking? service = Fog::Rackspace::Databases.new instance = service.instances.create({ :name => "fog_instance_#{Time.now.to_i.to_s}", :flavor_id => 1, :volume_size => 1 }) instance.wait_for { ready? } options = { :name => "user_#{Time.now.to_i.to_s}", :password => "fog_user" } model_tests(instance.users, options, false) instance.destroy end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/0000755000004100000410000000000013411315054022714 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/compute_v2/images_tests.rb0000644000004100000410000000067613411315054025741 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | images', ['rackspace']) do service = Fog::Compute::RackspaceV2.new image_id = nil tests("success") do tests("#all").succeeds do images = service.images.all image_id = images.first.id end tests("#get").succeeds do service.images.get(image_id) end end tests("failure").returns(nil) do service.images.get(Fog::Rackspace::MockData::NOT_FOUND_ID) end end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/image_tests.rb0000644000004100000410000000461513411315054025553 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | image', ['rackspace']) do service = Fog::Compute::RackspaceV2.new test_time = Time.now.to_i.to_s options = { :name => "fog_server_#{test_time}", :flavor_id => rackspace_test_flavor_id(service), :image_id => rackspace_test_image_id(service) } tests('ready?') do @server = Fog::Compute::RackspaceV2::Image.new tests('default in ready state').returns(true) do @server.state = Fog::Compute::RackspaceV2::Image::ACTIVE @server.ready? end tests('custom ready state').returns(true) do @server.state = Fog::Compute::RackspaceV2::Image::SAVING @server.ready?(Fog::Compute::RackspaceV2::Image::SAVING) end tests('default NOT in ready state').returns(false) do @server.state = Fog::Compute::RackspaceV2::Image::SAVING @server.ready? end tests('custom NOT ready state').returns(false) do @server.state = Fog::Compute::RackspaceV2::Image::UNKNOWN @server.ready?(Fog::Compute::RackspaceV2::Image::SAVING) end tests('default error state').returns(true) do @server.state = Fog::Compute::RackspaceV2::Image::ERROR exception_occurred = false begin @server.ready? rescue Fog::Compute::RackspaceV2::InvalidImageStateException => e exception_occurred = true returns(true) {e.desired_state == Fog::Compute::RackspaceV2::Image::ACTIVE } returns(true) {e.current_state == Fog::Compute::RackspaceV2::Image::ERROR } end exception_occurred end tests('custom error state').returns(true) do @server.state = Fog::Compute::RackspaceV2::Image::UNKNOWN exception_occurred = false begin @server.ready?(Fog::Compute::RackspaceV2::Image::SAVING, Fog::Compute::RackspaceV2::Image::UNKNOWN) rescue Fog::Compute::RackspaceV2::InvalidImageStateException => e exception_occurred = true returns(true) {e.desired_state == Fog::Compute::RackspaceV2::Image::SAVING } returns(true) {e.current_state == Fog::Compute::RackspaceV2::Image::UNKNOWN } end exception_occurred end end tests("success") do begin server = service.servers.create(options) server.wait_for { ready? } image = server.create_image("fog_image_#{test_time}") tests("destroy").succeeds do image.destroy end ensure server.destroy if server end end end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/keypairs_tests.rb0000644000004100000410000000230713411315054026314 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | key_pairs', ['rackspace']) do service = Fog::Compute::RackspaceV2.new name = Fog::Mock.random_letters(32) key = nil tests("API access") do begin tests("create").succeeds do key = service.key_pairs.create({:name => name}) end tests("list all").succeeds do service.key_pairs.all end tests("get").succeeds do service.key_pairs.get(name) end tests("delete").succeeds do key = nil if service.key_pairs.destroy(name) key == nil end tests("get unknown").returns(nil) do service.key_pairs.get(Fog::Mock.random_letters(32)) end tests("delete unknown").raises(Fog::Compute::RackspaceV2::NotFound) do service.key_pairs.destroy(Fog::Mock.random_letters(32)) end tests("create again after delete").succeeds do key = service.key_pairs.create({:name => name}) end tests("create already existing").raises(Fog::Compute::RackspaceV2::ServiceError) do service.key_pairs.create({:name => name}) end ensure key.destroy if key end end end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/networks_tests.rb0000644000004100000410000000041613411315054026340 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | networks', ['rackspace']) do service = Fog::Compute::RackspaceV2.new options = { :label => "fog_network_#{Time.now.to_i.to_s}", :cidr => '192.168.0.0/24' } collection_tests(service.networks, options, true) end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/server_tests.rb0000644000004100000410000002060713411315054025776 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | server', ['rackspace']) do service = Fog::Compute::RackspaceV2.new cbs_service = Fog::Rackspace::BlockStorage.new tests('setup test network').succeeds do @network = service.networks.create :label => "fog_test_net_#{Time.now.to_i.to_s}", :cidr => '192.168.1.0/24' end options = { :name => "fog_server_#{Time.now.to_i.to_s}", :flavor_id => rackspace_test_flavor_id(service), :image_id => rackspace_test_image_id(service), :metadata => { 'fog_test' => 'true' }, :networks => [@network.id] } tests('ready?') do @server = Fog::Compute::RackspaceV2::Server.new tests('default in ready state').returns(true) do @server.state = Fog::Compute::RackspaceV2::Server::ACTIVE @server.ready? end tests('custom ready state').returns(true) do @server.state = Fog::Compute::RackspaceV2::Server::VERIFY_RESIZE @server.ready?(Fog::Compute::RackspaceV2::Server::VERIFY_RESIZE) end tests('default NOT in ready state').returns(false) do @server.state = Fog::Compute::RackspaceV2::Server::REBOOT @server.ready? end tests('custom NOT ready state').returns(false) do @server.state = Fog::Compute::RackspaceV2::Server::REBOOT @server.ready?(Fog::Compute::RackspaceV2::Server::VERIFY_RESIZE) end tests('default error state').returns(true) do @server.state = Fog::Compute::RackspaceV2::Server::ERROR exception_occurred = false begin @server.ready? rescue Fog::Compute::RackspaceV2::InvalidServerStateException => e exception_occurred = true returns(true) {e.desired_state == Fog::Compute::RackspaceV2::Server::ACTIVE } returns(true) {e.current_state == Fog::Compute::RackspaceV2::Server::ERROR } end exception_occurred end tests('custom error state').returns(true) do @server.state = Fog::Compute::RackspaceV2::Server::ACTIVE exception_occurred = false begin @server.ready?(Fog::Compute::RackspaceV2::Server::VERIFY_RESIZE, Fog::Compute::RackspaceV2::Server::ACTIVE) rescue Fog::Compute::RackspaceV2::InvalidServerStateException => e exception_occurred = true returns(true) {e.desired_state == Fog::Compute::RackspaceV2::Server::VERIFY_RESIZE } returns(true) {e.current_state == Fog::Compute::RackspaceV2::Server::ACTIVE } end exception_occurred end end model_tests(service.servers, options, true) do @instance.wait_for { ready? } tests('#metadata[\'fog_test\']').returns('true') do @instance.metadata['fog_test'] end tests("includes #{@network.label}").returns(true) do @instance.addresses.keys.include?(@network.label) end tests('#create').succeeds do pending unless Fog.mocking? original_options = Marshal.load(Marshal.dump(options)) @instance.create(options) returns(true) { original_options == options } end tests('#update').succeeds do new_name = "fog_server_update#{Time.now.to_i.to_s}" @instance.name = new_name @instance.access_ipv4_address= "10.10.0.1" @instance.access_ipv6_address= "::1" @instance.save sleep 60 unless Fog.mocking? @instance.reload returns("10.10.0.1") { @instance.access_ipv4_address } returns("::1") { @instance.access_ipv6_address } returns(new_name) { @instance.name } end tests('#reboot("SOFT")').succeeds do @instance.reboot('SOFT') returns('REBOOT') { @instance.state } end @instance.wait_for { ready? } tests('#reboot("HARD")').succeeds do @instance.reboot('HARD') returns('HARD_REBOOT') { @instance.state } end sleep 30 unless Fog.mocking? @instance.wait_for { ready? } sleep 60 unless Fog.mocking? tests('#rebuild').succeeds do @instance.rebuild rackspace_test_image_id(service) returns('REBUILD') { @instance.state } end sleep 30 unless Fog.mocking? @instance.wait_for { ready? } sleep 60 unless Fog.mocking? tests('#resize').succeeds do @instance.resize(3) returns('RESIZE') { @instance.state } end sleep 30 unless Fog.mocking? @instance.wait_for { ready?('VERIFY_RESIZE', ['ACTIVE', 'ERROR']) } sleep 60 unless Fog.mocking? tests('#confirm_resize').succeeds do @instance.confirm_resize end sleep 30 unless Fog.mocking? @instance.wait_for { ready? } sleep 60 unless Fog.mocking? tests('#resize').succeeds do @instance.resize(2) returns('RESIZE') { @instance.state } end @instance.wait_for { ready?('VERIFY_RESIZE') } sleep 60 unless Fog.mocking? tests('#revert_resize').succeeds do @instance.revert_resize end @instance.wait_for { ready? } tests('#rescue').succeeds do @instance.rescue end @instance.wait_for { ready?('RESCUE') } tests('#start').succeeds do @instance.start end sleep 30 unless Fog.mocking? @instance.wait_for { ready?('ACTIVE') } tests('#stop').succeeds do @instance.stop end sleep 30 unless Fog.mocking? @instance.wait_for { ready?('SHUTOFF') } tests('#unrescue').succeeds do @instance.unrescue end @instance.wait_for { ready? } tests('#change_admin_password').succeeds do @instance.change_admin_password('somerandompassword') returns('PASSWORD') { @instance.state } returns('somerandompassword') { @instance.password } end @instance.wait_for { ready? } @test_image = nil begin tests('#create_image').succeeds do @test_image = @instance.create_image('fog-test-image') @test_image.reload returns('SAVING') { @test_image.state } end ensure @test_image.destroy unless @test_image.nil? || Fog.mocking? end tests('attachments') do begin @volume = cbs_service.volumes.create(:size => 100, :display_name => "fog-#{Time.now.to_i.to_s}") @volume.wait_for { ready? } tests('#attach_volume').succeeds do @instance.attach_volume(@volume) end tests('#attachments').returns(true) do @instance.wait_for do !attachments.empty? end @instance.attachments.any? {|a| a.volume_id == @volume.id } end ensure @volume.wait_for { !attachments.empty? } @instance.attachments.each {|a| a.detach } @volume.wait_for { ready? && attachments.empty? } @volume.destroy if @volume end end @instance.wait_for { ready? } end tests('#setup') do ATTRIBUTES = { :name => "foo", :image_id => 42, :flavor_id => 42 } create_server = lambda { |attributes| service = Fog::Compute::RackspaceV2.new attributes.merge!(:service => service) Fog::SSH::Mock.data.clear server = Fog::Compute::RackspaceV2::Server.new(attributes) server.save(attributes) @address = 123 server.ipv4_address = @address server.identity = "bar" server.public_key = "baz" server.setup server } commands = lambda { Fog::SSH::Mock.data[@address].first[:commands] } test("lock user when requested") do create_server.call(ATTRIBUTES.merge(:passwd_lock => true)) commands.call.one? { |c| c =~ /passwd\s+-l\s+root/ } end test("provide a password when the passed isn't locked") do pwd = create_server.call( ATTRIBUTES.merge(:passwd_lock => false) ).password # shindo expects a boolean not truthyness :-( !!pwd end test("leaves user unlocked by default") do create_server.call(ATTRIBUTES) commands.call.none? { |c| c =~ /passwd\s+-l\s+root/ } end test("nils password when password is locked") do pwd = create_server.call(ATTRIBUTES.merge(:passwd_lock => true)).password pwd.nil? end end #When after testing resize/resize_confirm we get a 409 when we try to resize_revert so I am going to split it into two blocks model_tests(service.servers, options, true) do @instance.wait_for { ready? } tests('#resize').succeeds do @instance.resize(4) returns('RESIZE') { @instance.state } end @instance.wait_for { ready?('VERIFY_RESIZE') } sleep 60 unless Fog.mocking? tests('#revert_resize').succeeds do @instance.revert_resize end @instance.wait_for { ready? } end wait_for_server_deletion(@instance) delete_test_network(@network) end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/network_tests.rb0000644000004100000410000000041013411315054026147 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | network', ['rackspace']) do service = Fog::Compute::RackspaceV2.new options = { :label => "fog_network_#{Time.now.to_i.to_s}", :cidr => '192.168.0.0/24' } model_tests(service.networks, options, true) end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/flavors_tests.rb0000644000004100000410000000062613411315054026143 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | flavors', ['rackspace']) do service = Fog::Compute::RackspaceV2.new tests("success") do tests("#all").succeeds do service.flavors.all end tests("#get").succeeds do service.flavors.get(service.flavors.first.id) end end tests("failure").returns(nil) do service.flavors.get(Fog::Rackspace::MockData::NOT_FOUND_ID) end end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/servers_tests.rb0000644000004100000410000000103413411315054026152 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | servers', ['rackspace']) do service = Fog::Compute::RackspaceV2.new options = { :name => "fog_server_#{Time.now.to_i.to_s}", :flavor_id => rackspace_test_flavor_id(service), :image_id => rackspace_test_image_id(service) } collection_tests(service.servers, options, true) do @instance.wait_for { ready? } end tests("#bootstrap").succeeds do pending if Fog.mocking? @server = service.servers.bootstrap(options) end if @server @server.destroy end end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/metadata_tests.rb0000644000004100000410000000250213411315054026242 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | metadata', ['rackspace']) do pending if Fog.mocking? service = Fog::Compute::RackspaceV2.new test_time = Time.now.to_i.to_s tests('success') do begin @server = service.servers.create(:name => "fog_server_#{test_time}", :flavor_id => rackspace_test_flavor_id(service), :image_id => rackspace_test_image_id(service)) @server.wait_for { ready? } tests('server') do collection_tests(@server.metadata, {:key => 'my_key', :value => 'my_value'}) do @server.wait_for { ready? } end end tests('image') do @image = @server.create_image("fog_image_#{test_time}", :metadata => {:my_key => 'my_value'}) @image.wait_for { ready? } tests("#all").succeeds do pending if Fog.mocking? && !mocks_implemented metadata = @image.metadata.all my_metadata = metadata.select {|datum| datum.key == 'my_key'} returns(1) { my_metadata.size } returns('my_value') {my_metadata[0].value } end tests("#get('my_key')").returns('my_value') do pending if Fog.mocking? && !mocks_implemented @image.metadata.get('my_key').value end end ensure @image.destroy if @image @server.destroy if @server end end end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/virtual_interface_tests.rb0000644000004100000410000000156113411315054030174 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | virtual_interface', ['rackspace']) do service = Fog::Compute::RackspaceV2.new net_options = { :label => "fog_network_#{Time.now.to_i.to_s}", :cidr => '192.168.0.0/24' } server_options = { :name => "fog_server_#{Time.now.to_i.to_s}", :flavor_id => rackspace_test_flavor_id(service), :image_id => rackspace_test_image_id(service) } tests('virtual_interface') do pending if Fog.mocking? begin @server = service.servers.create server_options @network = service.networks.create net_options @server.wait_for { ready? } model_tests(@server.virtual_interfaces, {:network => @network}, false) ensure if @server @server.destroy # wait_for_server_deletion(@server) if @server delete_test_network(@network) if @network end end end end fog-rackspace-0.1.6/tests/rackspace/models/compute_v2/virtual_interfaces_tests.rb0000644000004100000410000000113713411315054030356 0ustar www-datawww-dataShindo.tests('Fog::Compute::RackspaceV2 | virtual_interfaces', ['rackspace']) do service = Fog::Compute::RackspaceV2.new options = { :name => "fog_server_#{Time.now.to_i.to_s}", :flavor_id => rackspace_test_flavor_id(service), :image_id => rackspace_test_image_id(service) } tests('virtual_interfaces') do pending if Fog.mocking? begin @server = service.servers.create options @server.wait_for { ready? } tests('#virtual_interfaces').succeeds do @server.virtual_interfaces.all end ensure @server.destroy if @server end end end fog-rackspace-0.1.6/tests/rackspace/models/load_balancers/0000755000004100000410000000000013411315054023562 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/load_balancers/virtual_ips_tests.rb0000644000004100000410000000045613411315054027677 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | virtual_ips', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do collection_tests(@lb.virtual_ips, { :type => 'PUBLIC'}, false) do @lb.wait_for { ready? } end end end end fog-rackspace-0.1.6/tests/rackspace/models/load_balancers/virtual_ip_tests.rb0000644000004100000410000000063213411315054027510 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | virtual_ip', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do model_tests(@lb.virtual_ips, { :type => 'PUBLIC'}, false) do @lb.wait_for { ready? } tests("#save => existing virtual IP").raises(Fog::Errors::Error) do @instance.save end end end end end fog-rackspace-0.1.6/tests/rackspace/models/load_balancers/access_list_tests.rb0000644000004100000410000000050013411315054027620 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | access_list', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do model_tests(@lb.access_rules, { :address => '1.1.1.2', :type => 'ALLOW'}, false) do @lb.wait_for { ready? } end end end end fog-rackspace-0.1.6/tests/rackspace/models/load_balancers/load_balancer_tests.rb0000644000004100000410000001475713411315054030115 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | load_balancer', ['rackspace']) do pending if Fog.mocking? MINIMAL_LB_ATTRIBUTES = { :name => "fog#{Time.now.to_i}", :protocol => 'HTTP', :virtual_ips => [{ :type => 'PUBLIC' }], } NORMAL_LB_ATTRIBUTES = MINIMAL_LB_ATTRIBUTES.merge({ :port => 8080, :nodes => [{ :address => '1.1.1.1', :port => 80, :condition => 'ENABLED' }] }) FULL_LB_ATTRIBUTES = NORMAL_LB_ATTRIBUTES.merge({ :algorithm => 'LEAST_CONNECTIONS', :timeout => 60 }) HTTPS_REDIRECT_LB_ATTRIBUTES = FULL_LB_ATTRIBUTES.merge({ :protocol => 'HTTPS', :https_redirect => true }) given_a_load_balancer_service do model_tests(@service.load_balancers, NORMAL_LB_ATTRIBUTES, false) do @instance.wait_for { ready? } tests('#save => saving existing with port = 88').succeeds do @instance.port = 88 @instance.save end @instance.wait_for { ready? } tests('#stats').succeeds do @instance.stats end tests('#enable_connection_logging').succeeds do @instance.enable_connection_logging returns(true) { @instance.connection_logging } end tests('#enable_connection_logging after reload').succeeds do @instance.reload returns(true) { @instance.connection_logging } end @instance.wait_for { ready? } tests('#disable_connection_logging').succeeds do @instance.disable_connection_logging returns(false) { @instance.connection_logging } end @instance.wait_for { ready? } tests('#enable_content_caching').succeeds do @instance.enable_content_caching returns(true) { @instance.content_caching } end tests('#enable_content_caching after reload').succeeds do @instance.reload returns(true) { @instance.content_caching } end @instance.wait_for { ready? } tests('#disable_content_caching').succeeds do @instance.disable_content_caching returns(false) { @instance.content_caching } end tests('#usage').succeeds do @instance.usage end tests("#usage(:start_time => '2010-05-10', :end_time => '2010-05-11')").succeeds do @instance.usage(:start_time => '2010-05-10', :end_time => '2010-05-11') end tests("#health_monitor").returns(nil) do @instance.health_monitor end @instance.wait_for { ready? } tests("#enable_health_monitor('CONNECT', 5, 5, 5)").succeeds do @instance.enable_health_monitor('CONNECT', 5, 5, 5) end @instance.wait_for { ready? } tests("#health_monitor").succeeds do monitor = @instance.health_monitor returns('CONNECT') { monitor['type'] } end @instance.wait_for { ready? } tests("#enable_health_monitor('HTTP', 10, 5, 2, {:status_regex => '^[234][0-9][0-9]$', :path=>'/', :body_regex=>' '})").succeeds do @instance.enable_health_monitor('HTTP', 10, 5, 2, {:status_regex => '^[234][0-9][0-9]$', :path=>'/', :body_regex=>' '}) end @instance.wait_for { ready? } tests("#disable_health_monitor").succeeds do @instance.disable_health_monitor end @instance.wait_for { ready? } tests("#connection_throttling").returns(nil) do @instance.connection_throttling end tests("#enable_connection_throttling(5, 5, 5, 5)").succeeds do @instance.enable_connection_throttling(5, 5, 5, 5) end @instance.wait_for { ready? } tests("#connection_throttling").succeeds do throttle = @instance.connection_throttling returns(5) { throttle['maxConnections'] } end @instance.wait_for { ready? } tests("#disable_connection_throttling").succeeds do @instance.disable_connection_throttling end @instance.wait_for { ready? } tests("#session_persistence").returns(nil) do @instance.session_persistence end tests("#enable_session_persistence('HTTP_COOKIE')").succeeds do @instance.enable_session_persistence('HTTP_COOKIE') end @instance.wait_for { ready? } tests("#connction_throttling").succeeds do persistence = @instance.session_persistence returns('HTTP_COOKIE') { persistence['persistenceType'] } end @instance.wait_for { ready? } tests("#disable_session_persistence").succeeds do @instance.disable_session_persistence end @instance.wait_for { ready? } tests("#error_page").succeeds do @instance.error_page end @instance.wait_for { ready? } tests("#error_page = 'asdf'").succeeds do @instance.error_page = 'asdf' end @instance.wait_for { ready? } tests("#reset_error_page").succeeds do @instance.reset_error_page end @instance.wait_for { ready? } tests("#ssl_termination is nil").returns(nil) do @instance.ssl_termination end @instance.wait_for { ready? } tests("#enable_ssl_termination(443, PRIVATE_KEY, CERTIFICATE").succeeds do @instance.enable_ssl_termination(443, PRIVATE_KEY, CERTIFICATE) end @instance.wait_for { ready? } tests("#ssl_termination").succeeds do @instance.ssl_termination end @instance.wait_for { ready? } tests("#disable_ssl_termination").succeeds do @instance.disable_ssl_termination end @instance.wait_for { ready? } end tests('create with minimal attributes') do @lb = @service.load_balancers.create MINIMAL_LB_ATTRIBUTES returns(MINIMAL_LB_ATTRIBUTES[:name]) { @lb.name } returns('HTTP') { @lb.protocol } returns(80) { @lb.port } @lb.wait_for { ready? } @lb.destroy end tests('create with full attributes') do @lb = @service.load_balancers.create FULL_LB_ATTRIBUTES returns('LEAST_CONNECTIONS') { @lb.algorithm } returns(60) { @lb.timeout } @lb.wait_for { ready? } @lb.destroy end tests('create with httpsRedirect') do @lb = @service.load_balancers.create HTTPS_REDIRECT_LB_ATTRIBUTES returns('HTTPS') { @lb.protocol } returns(true) { @lb.https_redirect } @lb.wait_for { ready? } @lb.destroy end tests('failure') do @lb = @service.load_balancers.new NORMAL_LB_ATTRIBUTES tests('#usage => Requires ID').raises(ArgumentError) do @lb.usage end tests('#health_monitor => Requires ID').raises(ArgumentError) do @lb.health_monitor end end end end fog-rackspace-0.1.6/tests/rackspace/models/load_balancers/load_balancers_tests.rb0000644000004100000410000000101713411315054030261 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | load_balancers', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do @lb_name = 'fog' + Time.now.to_i.to_s collection_tests(@service.load_balancers, { :name => @lb_name, :protocol => 'HTTP', :port => 80, :virtual_ips => [{ :type => 'PUBLIC'}], :nodes => [{ :address => '1.1.1.1', :port => 80, :condition => 'ENABLED'}] }, false) do @instance.wait_for { ready? } end end end fog-rackspace-0.1.6/tests/rackspace/models/load_balancers/node_tests.rb0000644000004100000410000000076013411315054026261 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | node', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do model_tests(@lb.nodes, { :address => '1.1.1.2', :port => 80, :condition => 'ENABLED'}, false) do @lb.wait_for { ready? } tests("#save() => existing node with port = 88").succeeds do @instance.port = 88 @instance.save end @lb.wait_for { ready? } end end end end fog-rackspace-0.1.6/tests/rackspace/models/load_balancers/nodes_tests.rb0000644000004100000410000000051413411315054026441 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | nodes', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do collection_tests(@lb.nodes, { :address => '1.1.1.2', :port => 80, :condition => 'ENABLED'}, false) do @lb.wait_for { ready? } end end end end fog-rackspace-0.1.6/tests/rackspace/models/load_balancers/access_lists_tests.rb0000644000004100000410000000050613411315054030011 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers | access_lists', ['rackspace']) do pending if Fog.mocking? given_a_load_balancer_service do given_a_load_balancer do collection_tests(@lb.access_rules, { :address => '1.1.1.2', :type => 'ALLOW'}, false) do @lb.wait_for { ready? } end end end end fog-rackspace-0.1.6/tests/rackspace/models/block_storage/0000755000004100000410000000000013411315054023447 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/block_storage/volume_types_tests.rb0000644000004100000410000000064613411315054027757 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::BlockStorage | volume_types', ['rackspace']) do service = Fog::Rackspace::BlockStorage.new tests("success") do tests("#all").succeeds do service.volume_types.all end tests("#get").succeeds do service.volume_types.get(service.volume_types.first.id) end end tests("failure").returns(nil) do service.volume_types.get('some_random_identity') end end fog-rackspace-0.1.6/tests/rackspace/models/block_storage/volume_tests.rb0000644000004100000410000000150313411315054026524 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::BlockStorage | volume', ['rackspace']) do service = Fog::Rackspace::BlockStorage.new options = { :display_name => "fog_#{Time.now.to_i.to_s}", :size => 100 } model_tests(service.volumes, options, true) do @instance.wait_for{ ready? } tests('double save').raises(Fog::Rackspace::BlockStorage::IdentifierTaken) do @instance.save end tests('#attached?').succeeds do @instance.state = 'in-use' returns(true) { @instance.attached? } end tests('#snapshots').succeeds do begin snapshot = @instance.create_snapshot snapshot.wait_for { ready? } returns(true) { @instance.snapshots.first.id == snapshot.id } ensure snapshot.destroy if snapshot end end @instance.wait_for { snapshots.empty? } end end fog-rackspace-0.1.6/tests/rackspace/models/block_storage/snapshots_tests.rb0000644000004100000410000000076713411315054027252 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::BlockStorage | snapshots', ['rackspace']) do service = Fog::Rackspace::BlockStorage.new volume = service.volumes.create({ :display_name => "fog_#{Time.now.to_i.to_s}", :size => 100 }) volume.wait_for { ready? } options = { :display_name => "fog_#{Time.now.to_i.to_s}", :volume_id => volume.id } collection_tests(service.snapshots, options, true) do @instance.wait_for { ready? } end volume.wait_for { snapshots.empty? } volume.destroy end fog-rackspace-0.1.6/tests/rackspace/models/block_storage/volumes_tests.rb0000644000004100000410000000044513411315054026713 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::BlockStorage | volumes', ['rackspace']) do service = Fog::Rackspace::BlockStorage.new options = { :display_name => "fog_#{Time.now.to_i.to_s}", :size => 100 } collection_tests(service.volumes, options, true) do @instance.wait_for { ready? } end end fog-rackspace-0.1.6/tests/rackspace/models/block_storage/snapshot_tests.rb0000644000004100000410000000123613411315054027057 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::BlockStorage | snapshot', ['rackspace']) do service = Fog::Rackspace::BlockStorage.new begin volume = service.volumes.create({ :display_name => "fog_#{Time.now.to_i.to_s}", :size => 100 }) volume.wait_for { ready? } options = { :display_name => "fog_#{Time.now.to_i.to_s}", :volume_id => volume.id } model_tests(service.snapshots, options, true) do @instance.wait_for { ready? } tests('double save').raises(Fog::Rackspace::BlockStorage::IdentifierTaken) do @instance.save end end volume.wait_for { snapshots.empty? } ensure volume.destroy if volume end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/0000755000004100000410000000000013411315054023016 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/monitoring/data_points_tests.rb0000644000004100000410000000132513411315054027073 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | datapoints', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new begin label = "fog_#{Time.now.to_i.to_s}" @entity = service.entities.create :label => label @check = service.checks.create CHECK_CREATE_OPTIONS.merge(:label => label, :entity => @entity) sleep(@check.period + 30) unless Fog.mocking? @metric = service.metrics(:check => @check).first tests('#datapoints').succeeds do service.data_points(:metric => @metric).fetch({ :from => ((Time.now.to_i * 1000) - (3600 * 1000)) }) end ensure @check.destroy rescue nil if @check @entity.destroy rescue nil if @entity end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/notifications_tests.rb0000644000004100000410000000054613411315054027443 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | notifications', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new options = { :label => "fog_#{Time.now.to_i.to_s}", :type => "email", :details => {:address => "test@test.com"} } collection_tests(service.notifications, options, false) do end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/check_types_tests.rb0000644000004100000410000000050113411315054027062 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | check_types', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new @check_types = service.check_types tests('#all').succeeds do @check_types.all end tests('#new').succeeds do @check_types.new end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/alarm_tests.rb0000644000004100000410000000377513411315054025675 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | alarm', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new tests('#alarm=') do tests('should assign alarm id if object is a string') do alarm = Fog::Rackspace::Monitoring::Alarm.new id = "123123" alarm.id = "123123" returns(Fog::Rackspace::Monitoring::Alarm) { alarm.class } returns(id) { alarm.id } end tests('should set check if object is a check') do entity_id = "555" entity = Fog::Rackspace::Monitoring::Entity.new(:id => entity_id) check_id = "54321" check = Fog::Rackspace::Monitoring::Check.new(:id => check_id) check.entity = entity alarm = Fog::Rackspace::Monitoring::Alarm.new alarm.check = check.id returns(Fog::Rackspace::Monitoring::Alarm) { alarm.class } returns(check_id) { alarm.check.id } end end begin @entity = service.entities.create :label => "fog_#{Time.now.to_i.to_s}" @check = service.checks.create(CHECK_CREATE_OPTIONS.merge( :label => "fog_#{Time.now.to_i.to_s}", :entity => @entity) ) np = "npTechnicalContactsEmail" options = CHECK_CREATE_OPTIONS.merge( :disabled => false, :label => "fog_#{Time.now.to_i.to_s}", :entity => @entity, :entity_id => @entity.id, :check => @check, :check_id => @check.id, :notification_plan_id => np ) collection = service.alarms(:entity => @entity) model_tests(collection, options, false) do tests('#update').succeeds do @instance.disabled = true new_label = "new_label_#{Time.now.to_i.to_s}" @instance.label = new_label @instance.save @instance.label = nil # blank out label just to make sure @instance.reload returns(new_label) { @instance.label} returns(true) { @instance.disabled } end end ensure @entity.destroy if @entity end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/entities_tests.rb0000644000004100000410000000062013411315054026407 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | entities', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new options = { :label => "fog_#{Time.now.to_i.to_s}", :ip_addresses => {:default => "127.0.0.1"} } collection_tests(service.entities, options, false) do end tests('overview').succeeds do service.entities.overview end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/agent_token_tests.rb0000644000004100000410000000040713411315054027064 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | agent token', ['rackspace','rackspace_monitoring']) do service = Fog::Rackspace::Monitoring.new options = { :label => "fog_#{Time.now.to_i.to_s}" } model_tests(service.agent_tokens, options, false) do end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/entity_tests.rb0000644000004100000410000000133613411315054026104 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | entity', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new options = { :label => "fog_#{Time.now.to_i.to_s}", :ip_addresses => {:default => "127.0.0.1"} } model_tests(service.entities, options, false) do tests('#update').succeeds do new_label = "new_label_#{Time.now.to_i.to_s}" @instance.label = new_label @instance.save @instance.label = nil # blank out label just to make sure @instance.reload returns(new_label) { @instance.label } end tests('#checks').succeeds do @instance.checks end tests('#alarms').succeeds do @instance.alarms end end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/notification_tests.rb0000644000004100000410000000117113411315054027253 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | notification', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new options = { :label => "fog_#{Time.now.to_i.to_s}", :type => "email", :details => {:address => "test@test.com"} } model_tests(service.notifications, options, false) do tests('#update').succeeds do new_label = "new_label_#{Time.now.to_i.to_s}" @instance.label = new_label @instance.save @instance.label = nil # blank out label just to make sure @instance.reload returns(new_label) { @instance.label } end end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/agent_tokens_tests.rb0000644000004100000410000000041513411315054027246 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | agent tokens', ['rackspace','rackspace_monitoring']) do service = Fog::Rackspace::Monitoring.new options = { :label => "fog_#{Time.now.to_i.to_s}" } collection_tests(service.agent_tokens, options, false) do end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/check_tests.rb0000644000004100000410000000323213411315054025642 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | check', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new tests('#entity=') do tests('should create new entity if object is a string') do check = Fog::Rackspace::Monitoring::Check.new id = "123123" check.entity = "123123" returns(Fog::Rackspace::Monitoring::Entity) { check.entity.class } returns(id) { check.entity.id } end tests('should set entity if object is an entity') do id = "555" entity = Fog::Rackspace::Monitoring::Entity.new(:id => id) check = Fog::Rackspace::Monitoring::Check.new check.entity = entity returns(Fog::Rackspace::Monitoring::Entity) { check.entity.class } returns(id) { check.entity.id } end end begin @entity = service.entities.create :label => "fog_#{Time.now.to_i.to_s}" options = CHECK_CREATE_OPTIONS.merge(:label => "fog_#{Time.now.to_i.to_s}", :entity => @entity) collection = service.checks(:entity => @entity) model_tests(collection, options, false) do tests('#update').succeeds do new_label = "new_label_#{Time.now.to_i.to_s}" @instance.label = new_label timeout = 2 @instance.timeout = 2 @instance.save @instance.timeout = -1 # blank out timeout just to make sure @instance.label = nil # blank out label just to make sure @instance.reload returns(timeout) { @instance.timeout } returns(new_label) { @instance.label} end tests('#metrics').succeeds do @instance.metrics end end ensure @entity.destroy if @entity end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/metric_tests.rb0000644000004100000410000000120013411315054026041 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | metrics', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new begin label = "fog_#{Time.now.to_i.to_s}" @entity = service.entities.create :label => label @check = service.checks.create CHECK_CREATE_OPTIONS.merge(:label => label, :entity => @entity) sleep(@check.period + 30) unless Fog.mocking? @metric = service.metrics(:check => @check).first tests('#datapoints').succeeds do @metric.datapoints end ensure @check.destroy rescue nil if @check @entity.destroy rescue nil if @entity end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/alarms_tests.rb0000644000004100000410000000157013411315054026047 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | alarms', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new begin @entity = service.entities.create :label => "fog_#{Time.now.to_i.to_s}" @check = service.checks.create(CHECK_CREATE_OPTIONS.merge( :label => "fog_#{Time.now.to_i.to_s}", :entity => @entity) ) np = "npTechnicalContactsEmail" options = CHECK_CREATE_OPTIONS.merge( :label => "fog_#{Time.now.to_i.to_s}", :entity => @entity, :entity_id => @entity.id, :check => @check, :check_id => @check.id, :notification_plan_id => np ) collection = service.alarms(:entity => @entity) collection_tests(collection, options, false) do end ensure @entity.destroy if @entity end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/checks_tests.rb0000644000004100000410000000077713411315054026040 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | checks', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new begin @entity = service.entities.create :label => "fog_#{Time.now.to_i.to_s}" options = CHECK_CREATE_OPTIONS.merge(:label => "fog_#{Time.now.to_i.to_s}", :entity => @entity) collection = service.checks(:entity => @entity) collection_tests(collection, options, false) do end ensure @entity.destroy if @entity end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/alarm_example_tests.rb0000644000004100000410000000112213411315054027370 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | alarm_example', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new alarm_example_id = 'remote.http_body_match_1' alarm = service.alarm_examples.get(alarm_example_id) tests('#bound?') do tests('should return false if not bound') do returns(false) {alarm.bound?} end tests('should return true if bound') do values = {'string' => '12345'} alarm = service.alarm_examples.evaluate(alarm_example_id,values) returns(true) {alarm.bound?} end end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/metrics_tests.rb0000644000004100000410000000105613411315054026235 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | metrics', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new begin label = "fog_#{Time.now.to_i.to_s}" @entity = service.entities.create :label => label @check = service.checks.create CHECK_CREATE_OPTIONS.merge(:label => label, :entity => @entity) tests('#list_metrics').succeeds do service.metrics(:check => @check).all end ensure @check.destroy rescue nil if @check @entity.destroy rescue nil if @entity end end fog-rackspace-0.1.6/tests/rackspace/models/monitoring/alarm_examples_tests.rb0000644000004100000410000000104713411315054027561 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Monitoring | alarm_examples', ['rackspace','rackspace_monitoring']) do pending if Fog.mocking? service = Fog::Rackspace::Monitoring.new alarm_example_id = 'remote.http_body_match_1' tests('success') do tests('all').succeeds do service.alarm_examples.all end tests('get').succeeds do service.alarm_examples.get(alarm_example_id) end tests('evaluate').succeeds do values = {'string'=> '12345'} service.alarm_examples.evaluate(alarm_example_id,values) end end end fog-rackspace-0.1.6/tests/rackspace/models/storage/0000755000004100000410000000000013411315054022275 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/storage/account_tests.rb0000644000004100000410000000150713411315054025503 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Storage | account', ['rackspace']) do @account = Fog::Storage[:rackspace].account tests('load') do headers = @account.service.head_containers.headers returns(headers['X-Account-Meta-Temp-Url-Key']) { @account.meta_temp_url_key } returns(headers['X-Account-Container-Count'].to_i) { @account.container_count } returns(headers['X-Account-Bytes-Used'].to_i) { @account.bytes_used } returns(headers['X-Account-Object-Count'].to_i) { @account.object_count } end tests('reload') do @account.reload end tests('save') do key = "testing-update-#{Time.now.to_i}" @account.meta_temp_url_key = "testing-update-#{Time.now.to_i}" @account.save headers = @account.service.head_containers.headers returns(key) { headers['X-Account-Meta-Temp-Url-Key'] } end end fog-rackspace-0.1.6/tests/rackspace/models/storage/file_tests.rb0000644000004100000410000002742013411315054024770 0ustar www-datawww-datarequire 'fog/rackspace/models/storage/file' Shindo.tests('Fog::Rackspace::Storage | file', ['rackspace']) do tests("last_modified=") do tests("no timezone") do file = Fog::Storage::Rackspace::File.new file.last_modified = "2013-05-09T22:20:59.287990" returns(Fog::Time.utc(2013, 5, 9, 22, 20, 59, 287990, nil) == file.last_modified) { true } end tests("with timezone") do file = Fog::Storage::Rackspace::File.new file.last_modified = "Thu, 09 May 2015 22:20:59 GMT" returns(Fog::Time.utc(2015, 5, 9, 22, 20, 59, 0, nil).to_i == file.last_modified.to_i) { true } end tests("with time") do file = Fog::Storage::Rackspace::File.new file.last_modified = Fog::Time.utc(2015, 5, 9, 22, 20, 59, 0, nil) returns(Fog::Time.utc(2015, 5, 9, 22, 20, 59, 0, nil) == file.last_modified) { true } end tests("nil") do file = Fog::Storage::Rackspace::File.new file.last_modified = nil returns(nil) { file.last_modified } end tests("empty string") do file = Fog::Storage::Rackspace::File.new file.last_modified = "" returns("") { file.last_modified } end end def object_attributes(file=@instance) @instance.service.head_object(@directory.key, file.key).headers end def object_meta_attributes(file=@instance) object_attributes(file).reject {|k, v| !(k =~ /X-Object-Meta-/)} end def clear_metadata @instance.metadata.tap do |metadata| metadata.each_pair {|k, v| metadata[k] = nil } end end file_attributes = { :key => 'fog_file_tests', :body => lorem_file } directory_attributes = { # Add a random suffix to prevent collision :key => "fogfilestests-#{rand(65536)}" } @service = Fog::Storage.new :provider => 'rackspace', :rackspace_temp_url_key => "my_secret" @directory = @service.directories.create(directory_attributes) model_tests(@directory.files, file_attributes, Fog.mocking?) do tests("#metadata should load empty metadata").returns({}) do @instance.metadata.data end tests('#save') do tests('#metadata') do before do @instance.metadata[:foo] = 'bar' @instance.save end after do clear_metadata @instance.save end tests("should update metadata").returns('bar') do object_meta_attributes['X-Object-Meta-Foo'] end tests('should cache metadata').returns('bar') do @instance.metadata[:foo] end tests('should remove empty metadata').returns({}) do @instance.metadata[:foo] = nil @instance.save object_meta_attributes end tests("removes one key while leaving the other") do @instance.metadata[:color] = "green" @instance.save returns({"X-Object-Meta-Foo"=>"bar", "X-Object-Meta-Color"=>"green"}) { object_meta_attributes } tests("set metadata[:color] = nil").returns({"X-Object-Meta-Foo"=>"bar"}) do @instance.metadata[:color] = nil @instance.save object_meta_attributes end end end begin tests("sets metadata on create").returns("true") do @file = @directory.files.create :key => 'meta-test', :body => lorem_file, :metadata => {:works => true } object_meta_attributes(@file)["X-Object-Meta-Works"] end tests("sets Content-Disposition on create").returns("ho-ho-ho") do @file = @directory.files.create :key => 'meta-test', :body => lorem_file, :content_disposition => 'ho-ho-ho' object_attributes(@file)["Content-Disposition"] end ensure @file.destroy if @file end tests('urls') do tests('no CDN') do tests('url') do tests('http').succeeds do expire_time = Time.now + 3600 url = @instance.url(expire_time) url =~ /^http:/ end tests('https').succeeds do @directory.service.instance_variable_set "@rackspace_cdn_ssl", true expire_time = Time.now + 3600 url = @instance.url(expire_time) url =~ /^https:/ end @directory.service.instance_variable_set "@rackspace_cdn_ssl", false end tests('#public_url') do tests('http').returns(nil) do @instance.public_url end @directory.cdn_cname = "my_cname.com" tests('cdn_cname').returns(nil) do @instance.public_url end @directory.cdn_cname = nil @directory.service.instance_variable_set "@rackspace_cdn_ssl", true tests('ssl').returns(nil) do @instance.public_url end @directory.service.instance_variable_set "@rackspace_cdn_ssl", nil end tests('#ios_url').returns(nil) do @instance.ios_url end tests('#streaming_url').returns(nil) do @instance.streaming_url end end tests('With CDN') do tests('#public_url') do @directory.public = true @directory.save tests('http').returns(0) do @instance.public_url =~ /http:\/\/.*#{@instance.key}/ end @directory.cdn_cname = "my_cname.com" tests('cdn_cname').returns(0) do @instance.public_url =~ /my_cname\.com.*#{@instance.key}/ end @directory.cdn_cname = nil @directory.service.instance_variable_set "@rackspace_cdn_ssl", true tests('ssl').returns(0) do @instance.public_url =~ /https:\/\/.+\.ssl\..*#{@instance.key}/ end @directory.service.instance_variable_set "@rackspace_cdn_ssl", nil end tests('#ios_url').returns(0) do @instance.ios_url =~ /http:\/\/.+\.iosr\..*#{@instance.key}/ end tests('#streaming_url').returns(0) do @instance.streaming_url =~ /http:\/\/.+\.stream\..*#{@instance.key}/ end end tests('etags') do text = lorem_file.read md5 = Digest::MD5.new md5 << text etag = md5.hexdigest begin tests('valid tag').returns(true) do @file = @directory.files.create :key => 'valid-etag.txt', :body => text, :etag => etag @file.reload @file.etag == etag end ensure @file.destroy if @file end tests('invalid tag').raises(Fog::Storage::Rackspace::ServiceError) do @directory.files.create :key => 'invalid-etag.txt', :body => text, :etag => "bad-bad-tag" end end end tests('#metadata keys') do after do clear_metadata @instance.save end @instance.metadata[:foo_bar] = 'baz' tests("should support compound key names").returns('baz') do @instance.save object_meta_attributes['X-Object-Meta-Foo-Bar'] end @instance.metadata['foo'] = 'bar' tests("should support string keys").returns('bar') do @instance.save object_meta_attributes['X-Object-Meta-Foo'] end @instance.metadata['foo_bar'] = 'baz' tests("should support compound string key names").returns('baz') do @instance.save object_meta_attributes['X-Object-Meta-Foo-Bar'] end @instance.metadata['foo-bar'] = 'baz' tests("should support hyphenated keys").returns('baz') do @instance.save object_meta_attributes['X-Object-Meta-Foo-Bar'] end end end tests("#access_control_allow_origin") do tests("#access_control_allow_origin should default to nil").returns(nil) do @instance.access_control_allow_origin end @instance.access_control_allow_origin = 'http://example.com' @instance.save tests("#access_control_allow_origin should return access control attribute").returns('http://example.com') do @instance.access_control_allow_origin end @instance.access_control_allow_origin = 'foo' @instance.save tests("#access_control_allow_origin= should update access_control_allow_origin").returns('bar') do @instance.access_control_allow_origin = 'bar' @instance.save @instance.access_control_allow_origin end tests("#access_control_allow_origin= should not blow up on nil") do @instance.access_control_allow_origin = nil @instance.save end end tests("#delete_at") do @delete_at_time = (Time.now + 300).to_i tests("#delete_at should default to nil").returns(nil) do @instance.delete_at end @instance.delete_at = @delete_at_time @instance.save tests("#delete_at should return delete_at attribute").returns(@delete_at_time) do @instance.delete_at end @instance.delete_at = @delete_at_time @instance.save tests("#delete_at= should update delete_at").returns(@delete_at_time + 100) do @instance.delete_at = @delete_at_time + 100 @instance.save @instance.delete_at end tests("#delete_at= should not blow up on nil") do @instance.delete_at = nil @instance.save end end tests("#delete_after") do @delete_after_time = (Time.now + 300).to_i tests("#delete_after should default to nil").returns(nil) do @instance.delete_after end @instance.delete_after = @delete_after_time @instance.save tests("#delete_after should return delete_after attribute").returns(@delete_after_time) do @instance.delete_after end @instance.delete_after = @delete_after_time @instance.save tests("#delete_after= should update delete_after").returns(@delete_after_time + 100) do @instance.delete_after = @delete_after_time + 100 @instance.save @instance.delete_after end tests("#delete_after= should not blow up on nil") do @instance.delete_after = nil @instance.save end end end model_tests(@directory.files, file_attributes, Fog.mocking?) do tests("#origin") do tests("#origin should default to nil").returns(nil) do @instance.save @instance.origin end @instance.origin = 'http://example.com' @instance.save tests("#origin should return access control attributes").returns('http://example.com') do @instance.origin end @instance.attributes.delete('Origin') @instance.origin = 'foo' @instance.save tests("#origin= should update origin").returns('bar') do @instance.origin = 'bar' @instance.save @instance.origin end tests("#origin= should not blow up on nil") do @instance.origin = nil @instance.save end end tests("#content_encoding") do tests("#content_encoding should default to nil").returns(nil) do @instance.save @instance.content_encoding end @instance.content_encoding = 'gzip' @instance.save tests("#content_encoding should return the content encoding").returns('gzip') do @instance.content_encoding end @instance.attributes.delete('content_encoding') @instance.content_encoding = 'foo' @instance.save tests("#content_encoding= should update content_encoding").returns('bar') do @instance.content_encoding = 'bar' @instance.save @instance.content_encoding end tests("#content_encoding= should not blow up on nil") do @instance.content_encoding = nil @instance.save end end end @directory.destroy end fog-rackspace-0.1.6/tests/rackspace/models/storage/directories_tests.rb0000644000004100000410000000146013411315054026361 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Storage | directories', ['rackspace']) do @service = Fog::Storage[:rackspace] begin @name = "fog-directories-test-#{Time.now.to_i.to_s}" @filename = 'lorem.txt' @dir = @service.directories.create :key => @name, :metadata => {:fog_test => true} @file = @dir.files.create :key => @filename, :body => lorem_file tests('#get').succeeds do instance = @service.directories.get @name returns(false) { instance.nil? } returns('true') { instance.metadata[:fog_test] } returns(@name) { instance.key } returns(1) { instance.count } returns( Fog::Storage.get_body_size(lorem_file)) {instance.bytes } returns(@filename) { instance.files.first.key } end ensure @file.destroy if @file @dir.destroy if @dir end end fog-rackspace-0.1.6/tests/rackspace/models/storage/files_tests.rb0000644000004100000410000000213713411315054025151 0ustar www-datawww-dataShindo.tests("Fog::Rackspace::Storage | files", ['rackspace', 'storage']) do file_attributes = { :key => 'fog_files_tests', :body => lorem_file } directory_attributes = { :key => 'fogfilestests', :public => true } tests('success') do collection_tests(Fog::Storage[:rackspace].directories.create(directory_attributes).files, file_attributes, Fog.mocking?) @service = Fog::Storage.new :provider => 'rackspace', :rackspace_temp_url_key => "my_secret" @directory = @service.directories.create(directory_attributes) @file = @directory.files.create(file_attributes) tests("#get_url('#{@directory.key}')").succeeds do @directory.files.get_url(@directory.key) end tests("#get_http_url('#{@directory.key}')").succeeds do expire_time = Time.now + 3600 @directory.files.get_http_url(@file.key, expire_time) end tests("#get_https_url('#{@directory.key}', '#{@file.key}')").succeeds do expire_time = Time.now + 3600 @directory.files.get_https_url(@file.key, expire_time) end @file.destroy @directory.destroy end end fog-rackspace-0.1.6/tests/rackspace/models/storage/directory_tests.rb0000644000004100000410000001007213411315054026050 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Storage | directory', ['rackspace']) do @service = Fog::Storage[:rackspace] def container_meta_attributes @service.head_container(@instance.key).headers.reject {|k, v| !(k =~ /X-Container-Meta-/)} end directory_attributes = { # Add a random suffix to prevent collision :key => "fog-directory-tests-#{rand(65536)}" } model_tests(@service.directories, directory_attributes, Fog.mocking?) do tests('#public?').returns(false) do @instance.public? end tests('#public_url') do tests('http').returns(nil) do @instance.public_url end @instance.cdn_cname = "my_cname.com" tests('cdn_cname').returns(nil) do @instance.public_url end @instance.cdn_cname = nil @service.instance_variable_set "@rackspace_cdn_ssl", true tests('ssl').returns(nil) do @instance.public_url end @service.instance_variable_set "@rackspace_cdn_ssl", nil end tests('#ios_url').returns(nil) do @instance.ios_url end tests('#streaming_url').returns(nil) do @instance.streaming_url end tests('cdn') do @instance.public = true @instance.save tests('#public?').returns(true) do @instance.public? end tests('#public_url') do tests('http').returns(0) do @instance.public_url =~ /http:\/\// end @instance.cdn_cname = "my_cname.com" tests('cdn_cname').returns(0) do @instance.public_url =~ /my_cname\.com/ end @instance.cdn_cname = nil @service.instance_variable_set "@rackspace_cdn_ssl", true tests('ssl').returns(0) do @instance.public_url =~ /https:\/\/.+\.ssl\./ end @service.instance_variable_set "@rackspace_cdn_ssl", nil end tests('#ios_url').returns(0) do @instance.ios_url =~ /http:\/\/.+\.iosr\./ end tests('#streaming_url').returns(0) do @instance.streaming_url =~ /http:\/\/.+\.stream\./ end end tests("reload") do @instance.reload returns(nil) { @instance.instance_variable_get("@urls") } returns(nil) { @instance.instance_variable_get("@files") } returns(nil) { @instance.instance_variable_get("@public") } end end directory_attributes[:metadata] = {:draft => 'true'} tests('metadata') do model_tests(@service.directories, directory_attributes, Fog.mocking?) do tests('sets metadata on create').returns('true') do @instance.metadata.data container_meta_attributes["X-Container-Meta-Draft"] end tests('update metadata').returns({"X-Container-Meta-Draft"=>"true", "X-Container-Meta-Color"=>"green"}) do @instance.metadata[:color] = 'green' @instance.save container_meta_attributes end tests('set metadata to nil').returns({"X-Container-Meta-Draft"=>"true"}) do @instance.metadata[:color] = nil @instance.save container_meta_attributes end tests('delete metadata').returns({}) do @instance.metadata.delete(:draft) @instance.save container_meta_attributes end tests('should retrieve metadata when necessary') do @service.put_container(@instance.key, {"X-Container-Meta-List-Test"=>"true"} ) dir = @service.directories.find {|d| d.key == @instance.key } returns(nil) { dir.instance_variable_get("@metadata") } returns('true') { dir.metadata[:list_test] } end tests("should reload metadata after calling reload").returns("42") do @service.put_container @instance.key, "X-Container-Meta-Answer" => 42 @instance.reload @instance.metadata[:answer] end tests("should reload metadata after calling reload").returns("42") do @service.put_container @instance.key, "X-Container-Meta-Answer" => 42 @instance.reload @instance.metadata[:answer] end end end end fog-rackspace-0.1.6/tests/rackspace/models/storage/metadata_tests.rb0000644000004100000410000001614613411315054025634 0ustar www-datawww-datarequire 'fog/rackspace/models/storage/metadata' require 'fog/rackspace/models/storage/directory' require 'fog/rackspace/models/storage/directories' require 'fog/rackspace/models/storage/file' Shindo.tests('Fog::Rackspace::Storage | metadata', ['rackspace']) do def assert_directory(obj, assert_value) metadata = Fog::Storage::Rackspace::Metadata.new obj returns(assert_value) { metadata.send :directory? } end def assert_file(obj, assert_value) metadata = Fog::Storage::Rackspace::Metadata.new obj returns(assert_value) { metadata.send :file? } end tests('Directory') do @directory = Fog::Storage::Rackspace::Directory.new tests('#to_key') do tests('valid key').returns(:image_size) do metadata = Fog::Storage::Rackspace::Metadata.new @directory metadata.send(:to_key, "X-Container-Meta-Image-Size") end tests('invalid key').returns(nil) do metadata = Fog::Storage::Rackspace::Metadata.new @directory metadata.send(:to_key, "bad-key") end end tests('#[]') do tests('[:symbol_test]=42') do metadata = Fog::Storage::Rackspace::Metadata.new @directory metadata[:symbol_test] = 42 returns(42) { metadata[:symbol_test] } returns(42) { metadata['symbol_test'] } returns(nil) { metadata[:nil_test] } end tests('[\'string_test\']=55') do metadata = Fog::Storage::Rackspace::Metadata.new @directory metadata['string_test'] = 55 returns(55) { metadata[:string_test] } returns(55) { metadata['string_test'] } returns(nil) { metadata['nil_test'] } end tests('set string and symbol') do metadata = Fog::Storage::Rackspace::Metadata.new @directory metadata[:key_test] = 55 metadata['key_test'] = 55 returns(1) { metadata.size } end tests('key to remove').returns("X-Remove-Container-Meta-Thumbnail-Image") do metadata = Fog::Storage::Rackspace::Metadata.new @directory metadata.send(:to_header_key, :thumbnail_image, nil) end end tests('#to_header_key') do metadata = Fog::Storage::Rackspace::Metadata.new @directory tests('key to add').returns("X-Container-Meta-Thumbnail-Image") do metadata.send(:to_header_key, :thumbnail_image, true) end tests('key to remove').returns("X-Remove-Container-Meta-Thumbnail-Image") do metadata.send(:to_header_key, :thumbnail_image, nil) end end tests('#to_headers').returns({"X-Container-Meta-Preview"=>true, "X-Remove-Container-Meta-Delete-Me"=>1}) do metadata = Fog::Storage::Rackspace::Metadata.new @directory metadata[:preview] = true metadata[:delete_me] = nil metadata.to_headers end tests("#from_headers").returns({:my_boolean=>"true", :my_integer=>"42", :my_string=>"I am a string"}) do headers = { "X-Container-Meta-My-Integer"=> "42", "X-Container-Meta-My-Boolean"=> "true", "X-Container-Meta-My-String"=> "I am a string" } metadata = Fog::Storage::Rackspace::Metadata.from_headers @directory, headers metadata.data end tests("#delete").returns({"X-Remove-Container-Meta-Delete-Me"=>1}) do metadata = Fog::Storage::Rackspace::Metadata.new @directory metadata.delete(:delete_me) metadata.to_headers end end tests('File') do @file = Fog::Storage::Rackspace::File.new tests('#to_key') do tests('valid key').returns(:image_size) do metadata = Fog::Storage::Rackspace::Metadata.new @file metadata.send(:to_key, "X-Object-Meta-Image-Size") end tests('invalid key').returns(nil) do metadata = Fog::Storage::Rackspace::Metadata.new @file metadata.send(:to_key, "bad-key") end end tests('#to_header_key') do metadata = Fog::Storage::Rackspace::Metadata.new @file tests('key to add').returns("X-Object-Meta-Thumbnail-Image") do metadata.send(:to_header_key, :thumbnail_image, true) end tests('key to remove').returns("X-Remove-Object-Meta-Thumbnail-Image") do metadata.send(:to_header_key, :thumbnail_image, nil) end end tests('#to_headers').returns({"X-Object-Meta-Preview"=>true, "X-Remove-Object-Meta-Delete-Me"=>1}) do metadata = Fog::Storage::Rackspace::Metadata.new @file metadata[:preview] = true metadata[:delete_me] = nil metadata.to_headers end tests("#from_headers").returns({:my_boolean=>"true", :my_integer=>"42", :my_string=>"I am a string"}) do headers = { "X-Object-Meta-My-Integer"=> "42", "X-Object-Meta-My-Boolean"=> "true", "X-Object-Meta-My-String"=> "I am a string" } metadata = Fog::Storage::Rackspace::Metadata.from_headers @file, headers metadata.data end tests("#delete").returns({"X-Remove-Object-Meta-Delete-Me"=>1}) do metadata = Fog::Storage::Rackspace::Metadata.new @file metadata.delete(:delete_me) metadata.to_headers end end tests("#respond_to?") do tests('Should respond to all of the methods in Hash class').returns(true) do metadata = Fog::Storage::Rackspace::Metadata.new @file Hash.instance_methods.all? {|method| metadata.respond_to?(method)} end tests('Should respond to all of the methods in the Metadata class').returns(true) do metadata = Fog::Storage::Rackspace::Metadata.new @file metadata.methods.all? {|method| metadata.respond_to?(method)} end end tests("#method_missing").returns(true) do metadata = Fog::Storage::Rackspace::Metadata.new @file metadata[:test] = true metadata[:test] end tests('#directory?') do assert_directory Fog::Storage::Rackspace::Directories, true assert_directory Fog::Storage::Rackspace::Directory, true assert_directory Fog::Storage::Rackspace::Directory.new, true assert_directory nil, false assert_directory Fog::Storage::Rackspace::Files, false assert_directory Fog::Storage::Rackspace::File, false assert_directory Fog::Storage::Rackspace::File.new, false assert_directory "I am a string!", false end tests('#file?') do assert_file Fog::Storage::Rackspace::Directories, false assert_file Fog::Storage::Rackspace::Directory, false assert_file Fog::Storage::Rackspace::Directory.new, false assert_file nil, false assert_file Fog::Storage::Rackspace::Files, true assert_file Fog::Storage::Rackspace::File, true assert_file Fog::Storage::Rackspace::File.new, true assert_file "I am a string!", false end tests('#parent_class') do tests('Fog::Storage::Rackspace::Directory object') do metadata = Fog::Storage::Rackspace::Metadata.new Fog::Storage::Rackspace::Directory.new returns(Fog::Storage::Rackspace::Directory) { metadata.send :parent_class } end tests('Fog::Storage::Rackspace::Directory class') do metadata = Fog::Storage::Rackspace::Metadata.new Fog::Storage::Rackspace::Directory returns(Fog::Storage::Rackspace::Directory) { metadata.send :parent_class } end end end fog-rackspace-0.1.6/tests/rackspace/models/queues/0000755000004100000410000000000013411315054022140 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/queues/queue_tests.rb0000644000004100000410000000170013411315054025031 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | queue', ['rackspace']) do service = Fog::Rackspace::Queues.new options = { :name => "fog_instance_#{Time.now.to_i.to_s}", } model_tests(service.queues, options) do tests('#stats').formats(QUEUE_STATS_FORMAT['messages']) do @instance.stats end tests('#enqueue("msg", 60)') do @instance.enqueue("msg", 60) end tests('#dequeue(60, 60)').returns(true) do @instance.dequeue(60, 60) do |message| returns("msg") { message.body } end end tests('#dequeue(60, 60) => with not messages').returns(false) do @instance.dequeue(60, 60) do |message| end end tests('#dequeue(60, 60) => not passing block').returns(true) do @instance.enqueue("msg", 60) @instance.dequeue(60, 60) end tests('#dequeue(60, 60) => with not messages and not passing block').returns(false) do @instance.dequeue(60, 60) end end end fog-rackspace-0.1.6/tests/rackspace/models/queues/claim_tests.rb0000644000004100000410000000165313411315054025001 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | claim', ['rackspace']) do service = Fog::Rackspace::Queues.new queue = service.queues.create({ :name => "fog_queue_#{Time.now.to_i.to_s}", }) queue.messages.create({ :ttl => VALID_TTL, :body => { :random => :body } }) params = { :ttl => VALID_TTL, :grace => VALID_GRACE } begin model_tests(queue.claims, params) do tests('#messages') do returns(1) { @instance.messages.length } returns('body') { @instance.messages.first.body['random'] } end tests('#update').succeeds do @instance.ttl = VALID_TTL + 5 @instance.save end end queue.messages.create({ :ttl => VALID_TTL, :body => { :random => :body } }) tests('destroying claimed messages').succeeds do claim = queue.claims.create(params) claim.messages.first.destroy end ensure queue.destroy end end fog-rackspace-0.1.6/tests/rackspace/models/queues/claims_tests.rb0000644000004100000410000000245713411315054025167 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | claims', ['rackspace']) do service = Fog::Rackspace::Queues.new queue = service.queues.create({ :name => "fog_queue_#{Time.now.to_i.to_s}", }) queue.messages.create({ :ttl => VALID_TTL, :body => { :random => :body } }) params = { :ttl => VALID_TTL, :grace => VALID_GRACE } begin collection_tests(queue.claims, params) tests('creating claims when there are no messages') do before do #clear all message from queue queue.messages.all.each do |message| message.destroy end end tests("#create(#{params.inspect}) => with no messages does not show up in claim list") do returns(false) { queue.claims.create(params) } returns(true) { queue.claims.empty? } end end tests('create claims when there are messages') do before do queue.messages.create({ :ttl => VALID_TTL, :body => { :random => :body } }) end tests("#create(#{params.inspect}) => with messages does show up in claim list") do returns(true) do queue.claims.create(params).instance_of? Fog::Rackspace::Queues::Claim end returns(false) { queue.claims.empty? } end end ensure queue.destroy end end fog-rackspace-0.1.6/tests/rackspace/models/queues/message_tests.rb0000644000004100000410000000277613411315054025347 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | message', ['rackspace']) do service = Fog::Rackspace::Queues.new queue = service.queues.create({ :name => "fog_instance_#{Time.now.to_i.to_s}", }) options = { :ttl => VALID_TTL, :body => { :key => 'value' } } begin model_tests(queue.messages, options) do tests('#href').returns(true) do !@instance.href.nil? end tests('#identity').returns(true) do !@instance.identity.nil? end tests('#save => Fails to update').raises(StandardError) do @instance.save end end message = queue.messages.create(options.merge({:claim_id => '10'})) tests('#destroy => fails if claim is not valid').raises(Fog::Rackspace::Queues::ServiceError) do #API team should be fixing this so that it errors in this scenario pending message.destroy end ensure queue.destroy end tests('identity') do tests('nil') do message = Fog::Rackspace::Queues::Message.new :href => nil returns(nil) { message.id } end tests('with claim id') do message = Fog::Rackspace::Queues::Message.new :href => '/v1/queues/queue1/messages/528b7e4bb04a584f2eb805a3?claim_id=528b7e6aef913e6d2977ee6d' returns('528b7e4bb04a584f2eb805a3') { message.id } end tests('without claim id') do message = Fog::Rackspace::Queues::Message.new :href => '/v1/queues/queue1/messages/528b7e4bb04a584f2eb805a3' returns('528b7e4bb04a584f2eb805a3') { message.id } end end end fog-rackspace-0.1.6/tests/rackspace/models/queues/queues_tests.rb0000644000004100000410000000033713411315054025221 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | queues', ['rackspace']) do service = Fog::Rackspace::Queues.new options = { :name => "fog_instance_#{Time.now.to_i.to_s}", } collection_tests(service.queues, options) end fog-rackspace-0.1.6/tests/rackspace/models/queues/messages_tests.rb0000644000004100000410000000047513411315054025524 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues | messages', ['rackspace']) do service = Fog::Rackspace::Queues.new queue = service.queues.create({ :name => "fog_queue_#{Time.now.to_i.to_s}", }) options = { :ttl => 300, :body => "blah" } collection_tests(queue.messages, options) queue.destroy end fog-rackspace-0.1.6/tests/rackspace/models/auto_scale/0000755000004100000410000000000013411315054022750 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/auto_scale/policies_tests.rb0000644000004100000410000000116013411315054026324 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | policies', ['rackspace', 'rackspace_autoscale']) do pending if Fog.mocking? service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord begin group = service.groups.create({ :policies => POLICIES_OPTIONS, :group_config => GROUP_CONFIG_OPTIONS, :launch_config => LAUNCH_CONFIG_OPTIONS }) options = { :name => "policy 2", :change => 5, :cooldown => 100, :type => 'webhook' } collection_tests(group.policies, options, false) ensure deactive_auto_scale_group(group) group.destroy if group end end fog-rackspace-0.1.6/tests/rackspace/models/auto_scale/webhooks_tests.rb0000644000004100000410000000141013411315054026334 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | webhooks', ['rackspace', 'rackspace_autoscale']) do pending if Fog.mocking? service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord begin group = service.groups.create({ :policies => POLICIES_OPTIONS, :group_config => GROUP_CONFIG_OPTIONS, :launch_config => LAUNCH_CONFIG_OPTIONS }) policy = group.policies.create({ :name => "policy 2", :change => 5, :cooldown => 100, :type => 'webhook', :group => group }) options = {:name => 'New webhook', :group => group, :policy => policy } collection_tests(policy.webhooks, options, false) ensure policy.destroy if policy deactive_auto_scale_group(group) group.destroy if group end end fog-rackspace-0.1.6/tests/rackspace/models/auto_scale/group_builder_tests.rb0000644000004100000410000001172313411315054027365 0ustar www-datawww-datarequire 'fog/rackspace/models/auto_scale/group_builder' require 'fog/rackspace/models/auto_scale/group' require 'fog/rackspace/models/compute_v2/flavor' require 'fog/rackspace/models/load_balancers/load_balancer' Shindo.tests('Fog::Rackspace::AutoScale | group builder', ['rackspace', 'rackspace_autoscale']) do builder = Fog::Rackspace::AutoScale::GroupBuilder tests('#get_id') do tests('widget_id').returns(5) do builder.send(:get_id, 'widget', {:widget_id => 5, :noise => 3}) end tests('widget').returns(5) do Fog::Rackspace::AutoScale::GroupBuilder.send(:get_id, 'widget', {:widget => 5, :noise => 3}) end tests('Flavor object').returns(2) do flavor = Fog::Compute::RackspaceV2::Flavor.new(:id => 2) builder.send(:get_id, 'flavor', {:flavor => flavor, :noise => 3}) end end tests('networks_to_hash').returns([{"uuid" => '00000000-0000-0000-0000-000000000000'}]) do builder.send(:networks_to_hash, ['00000000-0000-0000-0000-000000000000']) end tests('#build_server_template').returns(LAUNCH_CONFIG_OPTIONS["args"]["server"]) do attributes = { :server_name => "autoscale_server", :image => "0d589460-f177-4b0f-81c1-8ab8903ac7d8", :flavor => "2", :disk_config => "AUTO", :server_metadata => { "build_config" => "core", "meta_key_1" => "meta_value_1", "meta_key_2" => "meta_value_2" }, :networks => ["11111111-1111-1111-1111-111111111111", "00000000-0000-0000-0000-000000000000"], :personality => [ { "path" => "/root/.csivh", "contents" => "VGhpcyBpcyBhIHRlc3QgZmlsZS4=" } ] } builder.send(:build_server_template, attributes) end tests('#load_balancer_to_hash') do lb_test_hash = { "port" => 80, "loadBalancerId" => 1234 } tests('hash').raises(ArgumentError, "Expected LoadBalancer") do builder.send(:load_balancer_to_hash, lb_test_hash) end tests('LoadBalancer').returns(lb_test_hash) do lb = Fog::Rackspace::LoadBalancers::LoadBalancer.new :port => 80, :id => 1234 builder.send(:load_balancer_to_hash, lb) end end tests('build_load_balancers') do lb_test_hash = { "port" => 80, "loadBalancerId" => 1234 } tests('nil').returns(nil) do builder.send(:build_load_balancers, {}) end tests('hash').returns([lb_test_hash]) do builder.send(:build_load_balancers, :load_balancers => [lb_test_hash]) end tests('LoadBalancer').returns([lb_test_hash]) do lb = Fog::Rackspace::LoadBalancers::LoadBalancer.new :port => 80, :id => 1234 builder.send(:build_load_balancers, :load_balancers => [lb]) end tests('multiple lbs').returns([lb_test_hash, lb_test_hash]) do lb = Fog::Rackspace::LoadBalancers::LoadBalancer.new :port => 80, :id => 1234 builder.send(:build_load_balancers, :load_balancers => [lb, lb]) end end tests('build_server_launch_config') do tests('no launch_config_type').returns(nil) do builder.build_server_launch_config({:pancakes => true}) end tests('wrong launch_config_type').returns(nil) do builder.build_server_launch_config({:launch_config_type => :something_else}) end tests('valid launch config').returns(LAUNCH_CONFIG_OPTIONS["args"]) do attributes = { :server_name => "autoscale_server", :image => "0d589460-f177-4b0f-81c1-8ab8903ac7d8", :flavor => "2", :disk_config => "AUTO", :server_metadata => { "build_config" => "core", "meta_key_1" => "meta_value_1", "meta_key_2" => "meta_value_2" }, :networks => ["11111111-1111-1111-1111-111111111111", "00000000-0000-0000-0000-000000000000"], :personality => [ { "path" => "/root/.csivh", "contents" => "VGhpcyBpcyBhIHRlc3QgZmlsZS4=" } ], :launch_config_type => :launch_server, :load_balancers => { "port" => 8080, "loadBalancerId" => 9099} } builder.build_server_launch_config(attributes).args end end tests('#build_group_config') do attributes = { :max_entities => 3, :min_entities => 0, :cooldown => 360, :name => "testscalinggroup198547", :metadata => { "gc_meta_key_2" => "gc_meta_value_2", "gc_meta_key_1" => "gc_meta_value_1" } } config = builder.build_group_config(attributes) returns(3) { config.max_entities } returns(0) { config.min_entities } returns(360) { config.cooldown } returns("testscalinggroup198547") { config.name } returns(attributes[:metadata]) { config.metadata } end tests('build') do pending if Fog.mocking? service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord group = builder.build(service, :launch_config_type => :launch_server, :server_name => 'test', :cooldown => 500) returns(500) { group.group_config.cooldown } returns('test') { group.launch_config.args["server"]["name"]} end end fog-rackspace-0.1.6/tests/rackspace/models/auto_scale/webhook_tests.rb0000644000004100000410000000171313411315054026157 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | webhook', ['rackspace', 'rackspace_autoscale']) do service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord pending if Fog.mocking? begin group = service.groups.create({ :policies => POLICIES_OPTIONS, :group_config => GROUP_CONFIG_OPTIONS, :launch_config => LAUNCH_CONFIG_OPTIONS }) policy = group.policies.create({ :name => "set group to 5 servers", :desired_capacity => 5, :cooldown => 1800, :type => "webhook", :group => group }) options = { :name => 'webhook name', :metadata => { 'owner' => 'me' }, :group => group, :policy => policy } model_tests(policy.webhooks, options, false) do tests('#execution_url').succeeds do @instance.execution_url end end ensure policy.destroy if policy deactive_auto_scale_group(group) group.destroy if group end end fog-rackspace-0.1.6/tests/rackspace/models/auto_scale/groups_tests.rb0000644000004100000410000000075413411315054026044 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | groups', ['rackspace', 'rackspace_autoscale']) do pending if Fog.mocking? service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord options = { :policies => POLICIES_OPTIONS, :group_config => GROUP_CONFIG_OPTIONS, :launch_config => LAUNCH_CONFIG_OPTIONS } collection_tests(service.groups, options, false) do tests('deactive scaling group').succeeds do deactive_auto_scale_group(@instance) end end end fog-rackspace-0.1.6/tests/rackspace/models/auto_scale/policy_tests.rb0000644000004100000410000000144013411315054026015 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | policy', ['rackspace', 'rackspace_autoscale']) do service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord pending if Fog.mocking? begin group = service.groups.create({ :policies => POLICIES_OPTIONS, :group_config => GROUP_CONFIG_OPTIONS, :launch_config => LAUNCH_CONFIG_OPTIONS }) options = { :name => "policy 2", :change => 1, :cooldown => 100, :type => 'webhook', :group => group } model_tests(group.policies, options, false) do tests('#execute').succeeds do @instance.execute end tests('#webhooks').succeeds do @instance.webhooks end end ensure deactive_auto_scale_group(group) group.destroy if group end end fog-rackspace-0.1.6/tests/rackspace/models/auto_scale/group_tests.rb0000644000004100000410000000143313411315054025654 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::AutoScale | group', ['rackspace', 'rackspace_autoscale']) do service = Fog::Rackspace::AutoScale.new :rackspace_region => :ord options = { :name => "fog_#{Time.now.to_i.to_s}", :policies => POLICIES_OPTIONS, :launch_config => LAUNCH_CONFIG_OPTIONS, :group_config => GROUP_CONFIG_OPTIONS } model_tests(service.groups, options, false) do pending if Fog.mocking? tests('#policies').succeeds do @instance.policies end tests('#launch_config').succeeds do @instance.launch_config end tests('#group_config').succeeds do @instance.group_config end tests('#state').succeeds do @instance.state end tests('deactive scaling group').succeeds do deactive_auto_scale_group(@instance) end end end fog-rackspace-0.1.6/tests/rackspace/models/networking/0000755000004100000410000000000013411315054023020 5ustar www-datawww-datafog-rackspace-0.1.6/tests/rackspace/models/networking/networks_tests.rb0000644000004100000410000000042013411315054026437 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Networking | networks', ['rackspace']) do service = Fog::Rackspace::Networking.new options = { :label => "fog_network_#{Time.now.to_i.to_s}", :cidr => '192.168.0.0/24' } collection_tests(service.networks, options, true) end fog-rackspace-0.1.6/tests/rackspace/models/networking/network_tests.rb0000644000004100000410000000041213411315054026255 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Networking | network', ['rackspace']) do service = Fog::Rackspace::Networking.new options = { :label => "fog_network_#{Time.now.to_i.to_s}", :cidr => '192.168.0.0/24' } model_tests(service.networks, options, true) end fog-rackspace-0.1.6/tests/rackspace/models/networking/virtual_interface_tests.rb0000644000004100000410000000156313411315054030302 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Networking | virtual_interface', ['rackspace']) do service = Fog::Rackspace::Networking.new net_options = { :label => "fog_network_#{Time.now.to_i.to_s}", :cidr => '192.168.0.0/24' } server_options = { :name => "fog_server_#{Time.now.to_i.to_s}", :flavor_id => rackspace_test_flavor_id(service), :image_id => rackspace_test_image_id(service) } tests('virtual_interface') do pending if Fog.mocking? begin @server = service.servers.create server_options @network = service.networks.create net_options @server.wait_for { ready? } model_tests(@server.virtual_interfaces, {:network => @network}, false) ensure if @server @server.destroy # wait_for_server_deletion(@server) if @server delete_test_network(@network) if @network end end end end fog-rackspace-0.1.6/tests/rackspace/models/networking/virtual_interfaces_tests.rb0000644000004100000410000000114113411315054030455 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Networking | virtual_interfaces', ['rackspace']) do service = Fog::Rackspace::Networking.new options = { :name => "fog_server_#{Time.now.to_i.to_s}", :flavor_id => rackspace_test_flavor_id(service), :image_id => rackspace_test_image_id(service) } tests('virtual_interfaces') do pending if Fog.mocking? begin @server = service.servers.create options @server.wait_for { ready? } tests('#virtual_interfaces').succeeds do @server.virtual_interfaces.all end ensure @server.destroy if @server end end end fog-rackspace-0.1.6/tests/rackspace/identity_tests.rb0000644000004100000410000000223213411315054022745 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Identity', ['rackspace']) do tests('current authentication') do tests('variables populated').returns(200) do @service = Fog::Rackspace::Identity.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => {:ssl_verify_peer => true} returns(true, "auth token populated") { !@service.auth_token.nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").host.nil? } returns(false, "service catalog populated") { @service.service_catalog.nil? } @service.list_tenants.status end end tests('reauthentication') do tests('should reauth with valid credentials') do @service = Fog::Rackspace::Identity.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.auth_token.nil? } @service.instance_variable_set("@auth_token", "bad-token") returns(true) { [200, 203].include? @service.list_tenants.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::Rackspace::Identity.new :rackspace_api_key => 'bad_key' } end end end fog-rackspace-0.1.6/tests/rackspace/queues_tests.rb0000644000004100000410000001115713411315054022431 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Queues', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Rackspace::Queues.new assert_method nil, :authenticate_v2 assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('authentication v1') do raises(Fog::Errors::NotImplemented) do @service = Fog::Rackspace::Queues.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' end end tests('authentication v2') do tests('variables populated').succeeds do @service = Fog::Rackspace::Queues.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => { :ssl_verify_peer => true } returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.queues end tests('dfw region').succeeds do #We consistently use DFW as our default but queues doesn't have a DFW default region yet. # We can enable this test once they have a DFW region (which they will) pending @service = Fog::Rackspace::Queues.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.queues end tests('ord region').succeeds do @service = Fog::Rackspace::Queues.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/) != nil } @service.queues end end tests('default auth') do tests('no params').succeeds do #We consistently use DFW as our default but queues doesn't have a DFW default region yet. # We can enable this test once they have a DFW region (which they will) pending @service = Fog::Rackspace::Queues.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.queues end tests('specify region').succeeds do @service = Fog::Rackspace::Queues.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/ ) != nil } @service.queues end end tests('reauthentication') do @service = Fog::Rackspace::Queues.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad_token") returns(true, 'list queues call succeeds') { [200, 204].include?(@service.list_queues.status) } end @service = Fog::Rackspace::Queues.new tests('#queues').succeeds do data = @service.queues returns(true) { data.is_a? Array } end tests('client_id') do tests('should generate uuid if a client id is not provided').succeeds do pending unless Fog::UUID.supported? service = Fog::Rackspace::Queues.new service.client_id =~ /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ end tests('should use specified uuid').succeeds do pending unless Fog::UUID.supported? my_uuid = Fog::UUID.uuid service = Fog::Rackspace::Queues.new :rackspace_queues_client_id => my_uuid service.client_id == my_uuid end end end fog-rackspace-0.1.6/tests/rackspace/load_balancer_tests.rb0000644000004100000410000001467713411315054023702 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::LoadBalancers', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Rackspace::LoadBalancers.new assert_method nil, :authenticate_v2 assert_method 'auth.api.rackspacecloud.com', :authenticate_v1 # chef's default auth endpoint assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('legacy authentication') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Rackspace::LoadBalancers.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").path.nil? } returns(true, "identity_service was not used") { @service.instance_variable_get("@identity_service").nil? } @service.list_load_balancers end tests('custom endpoint') do @service = Fog::Rackspace::LoadBalancers.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0', :rackspace_load_balancers_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('current authentation') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Rackspace::LoadBalancers.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => { :ssl_verify_peer => true } returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").host.nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.list_load_balancers end tests('dfw region').succeeds do @service = Fog::Rackspace::LoadBalancers.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.list_load_balancers end tests('ord region').succeeds do @service = Fog::Rackspace::LoadBalancers.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/) != nil } @service.list_load_balancers end tests('custom endpoint') do @service = Fog::Rackspace::LoadBalancers.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_load_balancers_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('no params').succeeds do @service = Fog::Rackspace::LoadBalancers.new :rackspace_region => nil returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.list_load_balancers end tests('specify old contstant style service endoint').succeeds do @service = Fog::Rackspace::LoadBalancers.new :rackspace_lb_endpoint => Fog::Rackspace::LoadBalancers::ORD_ENDPOINT returns(true) { (@service.instance_variable_get("@uri").to_s =~ /#{Fog::Rackspace::LoadBalancers::ORD_ENDPOINT}/ ) != nil } @service.list_load_balancers end tests('specify region').succeeds do @service = Fog::Rackspace::LoadBalancers.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/ ) != nil } @service.list_load_balancers end tests('custom endpoint') do @service = Fog::Rackspace::LoadBalancers.new :rackspace_load_balancers_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? tests('should reauth with valid credentials') do @service = Fog::Rackspace::LoadBalancers.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad-token") returns(200) { @service.list_load_balancers.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::Rackspace::LoadBalancers.new:rackspace_api_key => 'bad_key' } end end pending if Fog.mocking? @service = Fog::Rackspace::LoadBalancers.new tests('#algorithms').succeeds do data = @service.algorithms returns(true) { data.is_a? Array } returns(true) { data.first.is_a? String } end tests('#protocols').succeeds do data = @service.protocols returns(true) { data.is_a? Array } end tests('#usage').succeeds do @service.usage end end fog-rackspace-0.1.6/tests/rackspace/rackspace_tests.rb0000644000004100000410000000417613411315054023061 0ustar www-datawww-dataShindo.tests('Fog::Rackspace', ['rackspace']) do tests('normalize_url') do tests('should return nil if endpoint is nil').returns(nil) do Fog::Rackspace.normalize_url nil end tests('should remove trailing spaces').returns("https://dfw.blockstorage.api.rackspacecloud.com/v1") do Fog::Rackspace.normalize_url "https://dfw.blockstorage.api.rackspacecloud.com/v1 " end tests('should remove trailing /').returns("https://dfw.blockstorage.api.rackspacecloud.com/v1") do Fog::Rackspace.normalize_url "https://dfw.blockstorage.api.rackspacecloud.com/v1/" end tests('should downcase url').returns("https://dfw.blockstorage.api.rackspacecloud.com/v1") do Fog::Rackspace.normalize_url "HTTPS://DFW.BLOCKSTORAGE.API.RACKSPACECLOUD.COM/V1" end tests('show do all three').returns("https://dfw.blockstorage.api.rackspacecloud.com/v1") do Fog::Rackspace.normalize_url "HTTPS://DFW.BLOCKSTORAGE.API.RACKSPACECLOUD.COM/V1/ " end end tests('json_response?') do returns(false, "nil") { Fog::Rackspace.json_response?(nil) } tests('missing header').returns(false) do response = Excon::Response.new response.headers = nil #maybe this is a forced case returns(true) { response.headers.nil? } Fog::Rackspace.json_response?(response) end tests('nil Content-Type header').returns(false) do response = Excon::Response.new response.headers['Content-Type'] = nil Fog::Rackspace.json_response?(response) end tests('text/html Content-Type header').returns(false) do response = Excon::Response.new response.headers['Content-Type'] = 'text/html' Fog::Rackspace.json_response?(response) end tests('application/json Content-Type header').returns(true) do response = Excon::Response.new response.headers['Content-Type'] = 'application/json' Fog::Rackspace.json_response?(response) end tests('APPLICATION/JSON Content-Type header').returns(true) do response = Excon::Response.new response.headers['Content-Type'] = 'APPLICATION/JSON' Fog::Rackspace.json_response?(response) end end end fog-rackspace-0.1.6/tests/rackspace/networking_tests.rb0000644000004100000410000001371213411315054023310 0ustar www-datawww-dataShindo.tests('Fog::Rackspace::Networking', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::Rackspace::Networking.new assert_method nil, :authenticate_v2 assert_method 'auth.api.rackspacecloud.com', :authenticate_v1 # chef's default auth endpoint assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('legacy authentication') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Rackspace::Networking.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").path.nil? } returns(true, "identity_service was not used") { @service.instance_variable_get("@identity_service").nil? } @service.list_flavors end tests('custom endpoint') do @service = Fog::Rackspace::Networking.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0', :rackspace_compute_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('current authentation') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::Rackspace::Networking.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => {:ssl_verify_peer => true} returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").host.nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.list_flavors end tests('dfw region').succeeds do @service = Fog::Rackspace::Networking.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.list_flavors end tests('ord region').succeeds do @service = Fog::Rackspace::Networking.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/) != nil } @service.list_flavors end tests('custom endpoint') do @service = Fog::Rackspace::Networking.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_compute_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('no params').succeeds do @service = Fog::Rackspace::Networking.new :rackspace_region => nil returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /dfw/) != nil } @service.list_flavors end tests('specify old contstant style service endoint').succeeds do @service = Fog::Rackspace::Networking.new :rackspace_endpoint => Fog::Rackspace::Networking::ORD_ENDPOINT returns(true) { (@service.instance_variable_get("@uri").to_s =~ /#{Fog::Rackspace::Networking::ORD_ENDPOINT}/ ) != nil } @service.list_flavors end tests('specify region').succeeds do @service = Fog::Rackspace::Networking.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /ord/ ) != nil } @service.list_flavors end tests('custom endpoint') do @service = Fog::Rackspace::Networking.new :rackspace_compute_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? tests('should reauth with valid credentials') do @service = Fog::Rackspace::Networking.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad_token") returns(true) { [200, 203].include? @service.list_flavors.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::Rackspace::Networking.new :rackspace_api_key => 'bad_key' } end end end fog-rackspace-0.1.6/tests/rackspace/dns_tests.rb0000644000004100000410000001272713411315054021712 0ustar www-datawww-dataShindo.tests('Fog::DNS::Rackspace', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::DNS::Rackspace.new assert_method nil, :authenticate_v2 assert_method 'auth.api.rackspacecloud.com', :authenticate_v1 # chef's default auth endpoint assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('legacy authentication') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::DNS::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "contains tenant id") { (@service.instance_variable_get("@uri").path =~ /\/v1\.0\/\d+$/) != nil} #dns does not error if tenant id is missing returns(false, "path populated") { @service.instance_variable_get("@uri").path.nil? } returns(true, "identity_service was not used") { @service.instance_variable_get("@identity_service").nil? } @service.list_domains end tests('custom endpoint') do @service = Fog::DNS::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0', :rackspace_dns_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('current authentication') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::DNS::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => { :ssl_verify_peer => true } returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").host.nil? } returns(true, "contains tenant id") { (@service.instance_variable_get("@uri").path =~ /\/v1\.0\/\d+$/) != nil} #dns does not error if tenant id is missing identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.list_domains end tests('custom endpoint') do @service = Fog::DNS::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_dns_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('no params').succeeds do @service = Fog::DNS::Rackspace.new :rackspace_region => nil returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").host.nil? } returns(true, "contains tenant id") { (@service.instance_variable_get("@uri").path =~ /\/v1\.0\/\d+$/) != nil} #dns does not error if tenant id is missing @service.list_domains end tests('custom endpoint') do @service = Fog::DNS::Rackspace.new :rackspace_dns_url => 'https://my-custom-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? tests('should reauth with valid credentials') do @service = Fog::DNS::Rackspace.new returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad_token") returns(200) { @service.list_domains.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::DNS::Rackspace.new :rackspace_api_key => 'bad_key' } end end tests('array_to_query_string') do pending if Fog.mocking? @service = Fog::DNS::Rackspace.new returns("") { @service.send(:array_to_query_string, nil) } returns("param1=1") { @service.send(:array_to_query_string, {:param1 => [1]}) } returns("param1=1") { @service.send(:array_to_query_string, {:param1 => 1}) } returns("param1=1,2") { @service.send(:array_to_query_string, {:param1 => [1,2]}) } returns("param1=1¶m2=2") { @service.send(:array_to_query_string, {:param1 => [1], :param2 => [2]}) } end end fog-rackspace-0.1.6/tests/rackspace/cdn_tests.rb0000644000004100000410000002052613411315054021666 0ustar www-datawww-dataShindo.tests('Fog::CDN::Rackspace', ['rackspace']) do def assert_method(url, method) @service.instance_variable_set "@rackspace_auth_url", url returns(method) { @service.send :authentication_method } end tests('#authentication_method') do @service = Fog::CDN::Rackspace.new assert_method nil, :authenticate_v2 assert_method 'https://identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://identity.api.rackspacecloud.com/v2.0', :authenticate_v2 assert_method 'https://lon.identity.api.rackspacecloud.com', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v1.1', :authenticate_v1 assert_method 'https://lon.identity.api.rackspacecloud.com/v2.0', :authenticate_v2 end tests('authentication v1') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::CDN::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").path.nil? } returns(true, "identity_service was not used") { @service.instance_variable_get("@identity_service").nil? } @service.get_containers end tests('custom endpoint') do @service = Fog::CDN::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v1.0', :rackspace_cdn_url => 'https://my-custom-cdn-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-cdn-endpoint\.com/) != nil } end end tests('authentication v2') do pending if Fog.mocking? tests('variables populated').succeeds do @service = Fog::CDN::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :connection_options => { :ssl_verify_peer => true } returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(false, "path populated") { @service.instance_variable_get("@uri").path.nil? } identity_service = @service.instance_variable_get("@identity_service") returns(false, "identity service was used") { identity_service.nil? } returns(true, "connection_options are passed") { identity_service.instance_variable_get("@connection_options").key?(:ssl_verify_peer) } @service.get_containers end tests('dfw region').succeeds do @service = Fog::CDN::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :dfw returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /cdn1/) != nil } @service.get_containers end tests('ord region').succeeds do @service = Fog::CDN::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /cdn2/) != nil } @service.get_containers end tests('custom endpoint') do @service = Fog::CDN::Rackspace.new :rackspace_auth_url => 'https://identity.api.rackspacecloud.com/v2.0', :rackspace_cdn_url => 'https://my-custom-cdn-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-cdn-endpoint\.com/) != nil } end end tests('default auth') do pending if Fog.mocking? tests('no params').succeeds do @service = Fog::CDN::Rackspace.new :rackspace_region => nil returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses DFW") { (@service.instance_variable_get("@uri").host =~ /cdn1/) != nil } @service.get_containers end tests('specify region').succeeds do @service = Fog::CDN::Rackspace.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true) { (@service.instance_variable_get("@uri").host =~ /cdn2/) != nil } @service.get_containers end tests('custom endpoint') do @service = Fog::CDN::Rackspace.new :rackspace_cdn_url => 'https://my-custom-cdn-endpoint.com' returns(true, "auth token populated") { !@service.send(:auth_token).nil? } returns(true, "uses custom endpoint") { (@service.instance_variable_get("@uri").host =~ /my-custom-cdn-endpoint\.com/) != nil } end end tests('reauthentication') do pending if Fog.mocking? tests('should reauth with valid credentials') do @service = Fog::CDN::Rackspace.new :rackspace_region => :ord returns(true, "auth token populated") { !@service.send(:auth_token).nil? } @service.instance_variable_set("@auth_token", "bad-token") returns(true) { [200, 204].include? @service.get_containers.status } end tests('should terminate with incorrect credentials') do raises(Excon::Errors::Unauthorized) { Fog::CDN::Rackspace.new :rackspace_api_key => 'bad_key' } end end pending if Fog.mocking? def container_meta_attributes @cdn.head_container(@directory.key).headers end def clear_metadata @instance.metadata.tap do |metadata| metadata.each_pair {|k, v| metadata[k] = nil } end end directory_attributes = { # Add a random suffix to prevent collision :key => "fogfilestests-#{rand(65536)}" } @directory = Fog::Storage[:rackspace].directories.create(directory_attributes) @cdn = @directory.service.cdn begin tests('publish_container').succeeds do returns("False", "CDN is not enabled") { container_meta_attributes['X-CDN-Enabled'] } urls = @cdn.publish_container @directory returns(true, "hash contains expected urls") { Fog::CDN::Rackspace::Base::URI_HEADERS.values.all? { |url_type| urls[url_type] } } returns("True", "CDN is enabled") { container_meta_attributes['X-Cdn-Enabled'] } end tests('urls') do tests('CDN enabled container').returns(false) do @cdn.publish_container @directory @cdn.urls(@directory).empty? end tests('Non-CDN enabled container').returns(true) do @cdn.publish_container @directory, false @cdn.urls(@directory).empty? end tests('Non-existent container').returns(true) do non_existent_container = Fog::Storage::Rackspace::Directory.new :key => "non-existent" @cdn.urls(non_existent_container).empty? end end tests('urls_from_headers') do headers = { "X-Cdn-Streaming-Uri"=>"http://168e307d41afe64f1a62-d1e9259b2132e81da48ed3e1e802ef22.r2.stream.cf1.rackcdn.com", "X-Cdn-Uri"=>"http://6e8f4bf5125c9c2e4e3a-d1e9259b2132e81da48ed3e1e802ef22.r2.cf1.rackcdn.com", "Date"=>"Fri, 15 Feb 2013 18:36:41 GMT", "Content-Length"=>"0", "X-Trans-Id"=>"tx424df53b79bc43fe994d3cec0c4d2d8a", "X-Ttl"=>"3600", "X-Cdn-Ssl-Uri"=>"https://f83cb7d39e0b9ff9581b-d1e9259b2132e81da48ed3e1e802ef22.ssl.cf1.rackcdn.com", "X-Cdn-Ios-Uri"=>"http://a590286a323fec6aed22-d1e9259b2132e81da48ed3e1e802ef22.iosr.cf1.rackcdn.com", "X-Cdn-Enabled"=>"True", "Content-Type"=>"text/html; charset=UTF-8", "X-Log-Retention"=>"False" } urls = @cdn.send(:urls_from_headers, headers) returns(4) { urls.size } returns("http://168e307d41afe64f1a62-d1e9259b2132e81da48ed3e1e802ef22.r2.stream.cf1.rackcdn.com") { urls[:streaming_uri] } returns("http://6e8f4bf5125c9c2e4e3a-d1e9259b2132e81da48ed3e1e802ef22.r2.cf1.rackcdn.com") { urls[:uri] } returns("https://f83cb7d39e0b9ff9581b-d1e9259b2132e81da48ed3e1e802ef22.ssl.cf1.rackcdn.com") { urls[:ssl_uri] } returns("http://a590286a323fec6aed22-d1e9259b2132e81da48ed3e1e802ef22.iosr.cf1.rackcdn.com") { urls[:ios_uri] } end tests('purge') do pending end ensure @directory.destroy if @directory end end fog-rackspace-0.1.6/tests/rackspace/url_encoding_tests.rb0000644000004100000410000000043313411315054023565 0ustar www-datawww-dataShindo.tests('Rackspace | url_encoding', ['rackspace']) do returns("is%20this%20my%20file%3F.jpg") { Fog::Rackspace.escape("is this my file?.jpg") } returns("foo/bar") { Fog::Rackspace.escape("foo/bar", "/") } returns("foo%2Fbar") { Fog::Rackspace.escape("foo/bar", "0") } end fog-rackspace-0.1.6/tests/lorem.txt0000644000004100000410000000067713411315054017303 0ustar www-datawww-dataLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. fog-rackspace-0.1.6/bin/0000755000004100000410000000000013411315054015020 5ustar www-datawww-datafog-rackspace-0.1.6/bin/console0000755000004100000410000000052213411315054016407 0ustar www-datawww-data#!/usr/bin/env ruby require "bundler/setup" require "fog/rackspace" # You can add fixtures and/or initialization code here to make experimenting # with your gem easier. You can also use a different console, if you like. # (If you use this, don't forget to add pry to your Gemfile!) # require "pry" # Pry.start require "irb" IRB.start fog-rackspace-0.1.6/bin/setup0000755000004100000410000000020313411315054016101 0ustar www-datawww-data#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' set -vx bundle install # Do any other automated setup that you need to do here fog-rackspace-0.1.6/LICENSE.md0000644000004100000410000000220313411315054015651 0ustar www-datawww-dataThe MIT License (MIT) Copyright (c) 2014-2015 [CONTRIBUTORS.md](https://github.com/fog/fog-rackspace/blob/master/CONTRIBUTORS.md) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fog-rackspace-0.1.6/CONTRIBUTORS.md0000644000004100000410000001252213411315054016531 0ustar www-datawww-data 359 Kyle Rames 102 geemus 67 Ash Wilson 63 Wesley Beary 32 Brian Hartsock 26 Brad Gignac 24 Brian Hartsock 23 Ryan Richard 20 Evan Light 17 Thomas Cate 17 Ash Wilson 16 geemus (Wesley Beary) 15 Paul Thornthwaite 14 Bart Vercammen 14 Wesley Beary 12 Brian D. Burns 8 Brad Gignac 8 Matt Darby 8 Daniel Reichert 8 kfafel 6 Tom Noonan II 6 H. Wade Minter 6 dJason 6 jamiehannaford 5 Julio Feijo 5 Paul Thornthwaite 5 Jamie H 4 Jesse Scott 4 Matt Darby 4 Lance Ivy 4 Evan Smith 4 James Healy 4 Dusty Jones 3 Eugene Howe 3 Jay Faulkner 3 Josh Lane & Jason Hansen 3 Tony Ta 3 Chris Wuest 3 Sammy Larbi 3 Dejan Menges 3 Oleg Vivtash 3 Juris Galang 3 Kyle Rames 2 Decklin Foster 2 Alex Dunn 2 Andreas Gerauer 2 Ben Hundley 2 Benjamin Manns 2 Brendan Fosberry 2 Chris McClimans 2 Jason Faulkner 2 Jeffrey C. Ollie 2 Joseph Anthony Pasquale Holsten 2 Joshua Schairbaum 2 Kieran Pilkington 2 Matthias Gröbner 2 Max Lincoln 2 Mike Dillon 2 Wesley Beary 2 Zachary Danger Campbell 2 irdan 2 sashap 1 James Belchamber 1 Kevin Menard 1 stephen charles baldwin 1 Grégory Karékinian 1 Geoff Pado 1 Erik Michaels-Ober 1 Luiz Ribeiro 1 Mark Turner 1 Marshall Yount 1 Martin Smith 1 Eric Hodel 1 Eric Hankins 1 Andrew Langhorn 1 jimworm 1 Max Stepanov 1 Michael Jackson 1 kbockmanrs 1 Nathan Sutton 1 Nik Wakelin 1 Dmitry Gutov 1 Pablo Porto 1 Paul 1 Alain De Carolis 1 David Wittman 1 Paul Vudmaska 1 Phil Kates 1 Pierre Massat 1 Rick Bradley 1 Ryan King 1 Dan Prince 1 Sam Kottler 1 Sami Samhuri 1 Christopher Snell 1 Steve Agalloco 1 Steve Smith 1 Thom May 1 Christian Berendt 1 Thomas Cate 1 Chris Wuest 1 Chris Roberts 1 Tõnis Simo 1 Alex Tambellini 1 Cezar Sa Espinola 1 Carlos Sanchez 1 William Lawson 1 Yann Hamon 1 Yauheni Kryudziuk 1 rebelagentm 1 Caleb Tennis 1 deepj 1 Ben Sandberg 1 Andrew Taylor 1 gilles 1 Jon Crosby 1 Jon Holt 1 Jonathon Scanes 1 Joonas Reynders 1 heyryanw 1 Jim Salinas 1 howete 1 Josué Lima 1 James Herdman 1 Justin Barry âžœ fog git:(master) fog-rackspace-0.1.6/.gitignore0000644000004100000410000000014313411315054016236 0ustar www-datawww-data/.bundle/ /.yardoc /Gemfile.lock /_yardoc/ /coverage/ /doc/ /pkg/ /spec/reports/ /tmp/ *.gem .tags fog-rackspace-0.1.6/CODE_OF_CONDUCT.md0000644000004100000410000000453013411315054017051 0ustar www-datawww-data# Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at matt.darby@rackspace.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/3/0/fog-rackspace-0.1.6/Rakefile0000644000004100000410000000025613411315054015720 0ustar www-datawww-datarequire "bundler/gem_tasks" task :default => :test mock = ENV['FOG_MOCK'] || 'true' task :test do sh("export FOG_MOCK=#{mock} && bundle exec shindont") sh("rspec") end fog-rackspace-0.1.6/lib/0000755000004100000410000000000013411315054015016 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/0000755000004100000410000000000013411315054015571 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/0000755000004100000410000000000013411315054017525 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/docs/0000755000004100000410000000000013411315054020455 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/docs/getting_started.md0000644000004100000410000000716013411315054024172 0ustar www-datawww-data# Getting Started with Fog and the Rackspace Cloud This document explains how to get started using Fog with the [Rackspace Cloud](http://www.rackspace.com/cloud/). ## Requirements ### Ruby Fog officially supports Ruby 2.1.1, 2.1.0, 2.0.0, 1.9.3, 1.9.2, and 1.8.7 (also known as Matz Ruby Interpreter or MRI). While not officially supported, fog has been known to work with Rubinus and JRuby. Ruby 1.9.3 is suggested for new projects. For information on installing Ruby please refer to the [Ruby download page](http://www.ruby-lang.org/en/downloads/). ### RubyGems RubyGems is required to access the Fog gem. For information on installing RubyGems, please refer to [RubyGems download page](http://rubygems.org/pages/download). ### Bundler (optional) Bundler helps manage gem dependencies and is recommended for new projects. For more information about bundler, please refer to the [bundler documentation](http://gembundler.com/). ## Credentials To obtain credentials for the US Rackspace Cloud, please sign up for an account at [US Rackspace Open Cloud](https://cart.rackspace.com/cloud/). Once an account is created, you can login to the [Cloud Control Panel (US)](https://mycloud.rackspace.com/), find your credentials by clicking on your username in the top right corner, and then select API keys. Likewise, you can create an account on our UK Rackspace Open Cloud by signing up at [UK Rackspace Open Cloud](https://buyonline.rackspace.co.uk/cloud/userinfo?type=normal) and then logging into [Cloud Control Panel (UK)](https://mycloud.rackspace.co.uk/). You will use the credentials when you explore fog services in the [Next Steps](#next-steps) section. ## Installation To install Fog via RubyGems run the following command: $ gem install fog To install Fog via Bundler add `gem 'fog'` to your `Gemfile`. This is a sample `Gemfile` to install Fog: source 'https://rubygems.org' gem 'fog' After creating your `Gemfile` execute the following command to install the libraries: bundle install ## Next Steps Now that you have installed Fog and obtained your credentials, you are ready to begin exploring the capabilities of the Rackspace Open Cloud and Fog using `irb`. Start by executing the following command: irb Once `irb` has launched you will need to require the Fog library. If using Ruby 1.8.x execute the following command: require 'rubygems' require 'fog' If using Ruby 1.9.x execute the following command: require 'fog' You should now be able to execute the following command to see a list of services Fog provides for the Rackspace Open Cloud: Fog::Rackspace.services These services can be explored in further depth in the following documents: * [Next Generation Cloud Serversâ„¢ (compute_v2)](compute_v2.md) * [Cloud Filesâ„¢ (storage)](storage.md) * [Cloud Block Storage (block_storage)](block_storage.md) * [Auto Scale (auto_scale)](auto_scale.md) * [Queues](queues.md) **Note**: The compute service provides an interface to the First Geneneration Cloud Serversâ„¢ (compute). This service is deprecated. Users are encouraged to use Next Geneneration Cloud Serversâ„¢ (compute_v2). ## Additional Resources * [fog.io](http://fog.io) * [Fog rdoc](http://rubydoc.info/gems/fog) * [Fog Github repo](https://github.com/fog/fog) * [Release Notes](https://github.com/fog/fog/blob/master/changelog.txt) * [developer.rackspace.com](http://developer.rackspace.com/) ## Support and Feedback Your feedback is appreciated! If you have specific issues with the **fog** SDK, you should file an [issue via Github](https://github.com/fog/fog/issues). For general feedback and support requests, please visit: https://developer.rackspace.com/support. fog-rackspace-0.1.6/lib/fog/rackspace/docs/cdn_v2.md0000644000004100000410000002450013411315054022153 0ustar www-datawww-data#Rackspace CDNV2 This document explains how to get started using CDNV2 with Fog. It assumes you have read the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. ## Starting irb console Start by executing the following command: irb Once `irb` has launched you need to require the Fog library. If using Ruby 1.8.x execute: require 'rubygems' require 'fog' If using Ruby 1.9.x execute: require 'fog' ## Create Service Next, create a connection to Rackspace's CDNV2 API: Using a US-based account: service = Fog::Rackspace::CDNV2.new({ :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_region => :ord, # Defaults to :dfw }) Using a UK-based account: service = Fog::Compute.new({ :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT, :rackspace_region => :lon, }) To learn more about obtaining cloud credentials refer to the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. By default `Fog::Rackspace::CDNV2` will authenticate against the US authentication endpoint and connect to the DFW region. You can specify alternative authentication endpoints using the key `:rackspace_auth_url`. Please refer to [Alternate Authentication Endpoints](http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Endpoints-d1e180.html) for a list of alternative Rackspace authentication endpoints. Alternative regions are specified using the key `:rackspace_region `. A list of regions available for Cloud Servers can be found by executing the following: identity_service = Fog::Identity({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT # Not specified for US Cloud }) identity_service.service_catalog.display_service_regions :cloudServersOpenStack ### Optional Connection Parameters Fog supports passing additional connection parameters to its underlying HTTP library (Excon) using the `:connection_options` parameter.
Key Description
:connect_timeout Connection timeout (default: 60 seconds)
:read_timeout Read timeout for connection (default: 60 seconds)
:write_timeout Write timeout for connection (default: 60 seconds)
:proxy Proxy for HTTP and HTTPS connections
:ssl_ca_path Path to SSL certificate authorities
:ssl_ca_file SSL certificate authority file
:ssl_verify_peer SSL verify peer (default: true)
## Fog Abstractions Fog provides both a **model** and **request** abstraction. The request abstraction provides the most efficient interface and the model abstraction wraps the request abstraction to provide a convenient `ActiveModel` like interface. ### Request Layer The request abstraction maps directly to the [CDNV2 API](http://docs.rackspace.com/networks/api/v2/cn-devguide/content/ch_overview.html). It provides the most efficient interface to the Rackspace CDNV2 To see a list of requests supported by the service: service.requests This returns: [:create_service, :delete_assets, :delete_service, :get_flavor, :get_home_document, :get_ping, :get_service, :list_flavors, :list_services, :update_service] #### Example Request To request a list of services: response = service.list_services This returns in the following `Excon::Response`: #{"services"=>[{"name"=>"SomethingDifferent.net", "domains"=>[{"domain"=>"google.com", "protocol"=>"http"}], "origins"=>[{"origin"=>"google.com", "port"=>80, "ssl"=>false, "rules"=>[]}], "restrictions"=>[], "caching"=>[], "status"=>"create_in_progress", "flavor_id"=>"cdn", "errors"=>[] To view the status of the response: response.status **Note**: Fog is aware of valid HTTP response statuses for each request type. If an unexpected HTTP response status occurs, Fog will raise an exception. To view response body: response.body This will return: {"services"=>[{"name"=>"SomethingDifferent.net", "domains"=>[{"domain"=>"google.com",... To learn more about CDNV2 request methods refer to [rdoc](http://www.rubydoc.info/gems/fog/Fog/Rackspace/CDNV2/Real). To learn more about Excon refer to [Excon GitHub repo](https://github.com/geemus/excon). ### Model Layer Fog models behave in a manner similar to `ActiveModel`. Models will generally respond to `create`, `save`, `persisted?`, `destroy`, `reload` and `attributes` methods. Additionally, fog will automatically create attribute accessors. Here is a summary of common model methods:
Method Description
create Accepts hash of attributes and creates object.
Note: creation is a non-blocking call and you will be required to wait for a valid state before using resulting object.
save Saves object.
Note: not all objects support updating object.
persisted? Returns true if the object has been persisted.
destroy Destroys object.
Note: this is a non-blocking call and object deletion might not be instantaneous.
reload Updates object with latest state from service.
ready? Returns true if object is in a ready state and able to perform actions. This method will raise an exception if object is in an error state.
attributes Returns a hash containing the list of model attributes and values.
identity Returns the identity of the object.
Note: This might not always be equal to object.id.
wait_for This method periodically reloads model and then yields to specified block until block returns true or a timeout occurs.
The remainder of this document details the model abstraction. ## List Services To retrieve a list of available services: service.services This returns a collection of `Fog::Rackspace::CDNV2::Service` models: "google.com", "protocol"=>"http"}], origins=[{"origin"=>"google.com", "port"=>80, "ssl"=>false, "rules"=>[]}], caching=[], restrictions=[], flavor_id="cdn", status="create_in_progress", links=[{"href"=>"", "rel"=>"self"}, {"href"=>"...", "rel"=>"flavor"}] ... ## Create Service Create a service: s = service.services.new s.name = "work.com" s.flavor_id = "cdn" s.add_domain "google.com" s.add_origin "google.com" s.save ## Update Service You may add, remove, or update. -- **DOCS NEEDED** -- s = service.services.first s.add_operation({ op: "add", path: "/domains/0", value: { origin: "cdn.somewhere.org", port: 80, ssl: false, rules: [ { name: "Something", request_url: "google.com" } ] } }) s.save ## Get Service To retrieve individual service: service.services.get "087ffeb0-462d-4f44-b24a-2914fbfb1d42" This returns an `Fog::Rackspace::CDNV2::Service` instance: "google.com", "protocol"=>"http"}], origins=[{"origin"=>"google.com", "port"=>80, "ssl"=>false, "rules"=>[]}], caching=[], restrictions=[], flavor_id="cdn", status="create_in_progress", links=[{"href"=>"", "rel"=>"self"}, {"href"=>"...", "rel"=>"flavor"}] ## Delete Service To delete a service: service.destroy **Note**: The service is not immediately destroyed, but it does occur shortly there after. ## Delete Service Assets To delete a service's assets (or any owned asset via url): service.destroy_assets(url: "/") **Note**: The service's asset is not immediately destroyed, but it does occur shortly there after. ## List Flavors To retrieve a list of available flavors: service.flavors This returns a collection of `Fog::Rackspace::CDNV2::Flavor` models: "akamai", "links"=>[{"href"=>"http://www.akamai.com", "rel"=>"provider_url"}]}], links=[{"href"=>"...", "rel"=>"self"}] > ] > ## Get Flavor To retrieve individual flavor: service.flavors.get "cdn" This returns an `Fog::Rackspace::CDNV2::Flavor` instance: "akamai", "links"=>[{"href"=>"http://www.akamai.com", "rel"=>"provider_url"}]}], links=[{"href"=>"...", "rel"=>"self"}] > ## Ping To ping the CDN: service.ping This returns an boolean based on successful ping. ## Get Home Document To retrieve the home document: service.home_document This returns a JSON blob that describes the home document. ## Additional Resources * [fog.io](http://fog.io/) * [Fog rdoc](http://rubydoc.info/gems/fog/) * [Fog Github repo](https://github.com/fog/fog) * [Fog Github Issues](https://github.com/fog/fog/issues) * [Excon Github repo](https://github.com/geemus/excon) * [Rackspace Networking API](http://docs.rackspace.com/networking/api/v2/cs-devguide/content/ch_preface.html) ## Support and Feedback Your feedback is appreciated! If you have specific issues with the **fog** SDK, you should file an [issue via Github](https://github.com/fog/fog/issues). For general feedback and support requests, please visit: https://developer.rackspace.com/support. fog-rackspace-0.1.6/lib/fog/rackspace/docs/queues.md0000644000004100000410000003316113411315054022312 0ustar www-datawww-data#Cloud Queues (queues) This document explains how to get started using queues with Fog. It assumes you have read the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. ## Basic Concepts Cloud Queues is an open source, scalable, and highly available message and notifications service, based on the OpenStack Marconi project. Users of this service can create and manage a producer-consumer or a publisher-subscriber model. Unlimited queues and messages give users the flexibility they need to create powerful web applications in the cloud. It consists of a few basic components: queues, messages, claims, and statistics. In the producer-consumer model, users create queues in which producers, or servers, can post messages. Workers, or consumers, can then claim those messages and delete them after they complete the actions associated with the messages. A single claim can contain multiple messages, and administrators can query claims for status. In the publisher-subscriber model, messages are posted to a queue as in the producer-consumer model, but messages are never claimed. Instead, subscribers, or watchers, send GET requests to pull all messages that have been posted since their last request. In this model, a message remains in the queue, unclaimed, until the message's time to live (TTL) has expired. In both of these models, administrators can get queue statistics that display the most recent and oldest messages, the number of unclaimed messages, and more. ## Starting irb console Start by executing the following command: irb Once `irb` has launched you need to require the Fog library as follows: require 'fog' ## Create Service Next, create a connection to queue service: Using a US-based account: service = Fog::Rackspace::Queues.new( :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_region => :ord, # Your desired region :rackspace_queues_client_id => CLIENT_ID, # Your client ID :connection_options => {} # Optional connection options ) Using a UK-based account: service = Fog::Rackspace::Queues.new( :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT, :rackspace_region => :lon, # Your desired region :rackspace_queues_client_id => CLIENT_ID', # Your client ID :connection_options => {} # Optional connection options ) To learn more about obtaining cloud credentials refer to the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. ### Authentication Endpoint By default `Fog::Rackspace::Queues` will authenticate against the US authentication endpoint. You can specify alternative authentication endpoints using the key `:rackspace_auth_url`. Please refer to [Alternate Authentication Endpoints](http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Endpoints-d1e180.html) for a list of alternative Rackspace authentication endpoints. ### Regions Alternative regions are specified using the key `:rackspace_region `. A list of regions available for cloud queues can be found by executing the following: identity_service = Fog::Identity({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT # Not specified for US Cloud }) identity_service.service_catalog.display_service_regions :queues ### Private Cloud Rackspace Private Cloud installations can skip specifying a region and directly specify their custom service endpoints using the key `:rackspace_queues_url`. **Note**: A`Fog::Rackspace::Queues` instance is needed for the desired region. ### Client ID The Rackspace Queue service requires that every client define a client id to help identify messages and claims specific to the client. This client id should take the form of a UUID and can be generated using fog as follows: Fog::UUID.uuid If the client id is omitted fog will generate one for you. ### Optional Connection Parameters Fog supports passing additional connection parameters to its underlying HTTP library (Excon) using the `:connection_options` parameter.
Key Description
:connect_timeout Connection timeout (default: 60 seconds)
:read_timeout Read timeout for connection (default: 60 seconds)
:write_timeout Write timeout for connection (default: 60 seconds)
:proxy Proxy for HTTP and HTTPS connections
:ssl_ca_path Path to SSL certificate authorities
:ssl_ca_file SSL certificate authority file
:ssl_verify_peer SSL verify peer (default: true)
## Fog Abstractions Fog provides both a **model** and **request** abstraction. The request abstraction provides the most efficient interface and the model abstraction wraps the request abstraction to provide a convenient `ActiveModel`-like interface. ### Request Layer The request abstraction maps directly to the [Queue API](http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/overview.html). It provides the most efficient interface to the Rackspace Open Cloud. To see a list of requests supported by the service: service.requests This returns: :list_queues, :get_queue, :create_queue, :delete_queue, :get_queue_stats, :list_messages, :get_message, :create_message, :delete_message, :create_claim, :get_claim, :update_claim, :delete_claim #### Example Request To request a list of queues: response = service.list_queues This returns in the following `Excon::Response`: #{"queues"=>[{"href"=>"/v1/queues/demo-queue", "name"=>"demo-queue"}], "links"=>[{"href"=>"/v1/queues?marker=demo-queue", "rel"=>"next"}]}, :headers=>{"Content-Length"=>"119", "Content-Type"=>"application/json; charset=utf-8", "Content-Location"=>"/v1/queues", "X-Project-ID"=>"5551212"}, :status=>200, :remote_ip=>"10.10.0.1"}, @body="{\"queues\": [{\"href\": \"/v1/queues/demo-queue\", \"name\": \"demo-queue\"}], \"links\": [{\"href\": \"/v1/queues?marker=demo-queue\", \"rel\": \"next\"}]}", @headers={"Content-Length"=>"119", "Content-Type"=>"application/json; charset=utf-8", "Content-Location"=>"/v1/queues", "X-Project-ID"=>"5551212"}, @status=200, @remote_ip="10.10.0.1"> To view the status of the response: response.status **Note**: Fog is aware of valid HTTP response statuses for each request type. If an unexpected HTTP response status occurs, Fog will raise an exception. To view response body: response.body This returns: {"queues"=>[{"href"=>"/v1/queues/demo-queue", "name"=>"demo-queue"}], "links"=>[{"href"=>"/v1/queues?marker=demo-queue", "rel"=>"next"}]} To learn more about queue request methods refer to [rdoc](http://rubydoc.info/gems/fog/Fog/Rackspace/Queues/Real). To learn more about Excon refer to [Excon GitHub repo](https://github.com/geemus/excon). ### Model Layer Fog models behave in a manner similar to `ActiveModel`. Models will generally respond to `create`, `save`, `persisted?`, `destroy`, `reload` and `attributes` methods. Additionally, fog will automatically create attribute accessors. Here is a summary of common model methods:
Method Description
create Accepts hash of attributes and creates object.
Note: creation is a non-blocking call and you will be required to wait for a valid state before using resulting object.
save Saves object.
Note: not all objects support updating object.
persisted? Returns true if the object has been persisted.
destroy Destroys object.
Note: this is a non-blocking call and object deletion might not be instantaneous.
reload Updates object with latest state from service.
ready? Returns true if object is in a ready state and able to perform actions. This method will raise an exception if object is in an error state.
attributes Returns a hash containing the list of model attributes and values.
identity Returns the identity of the object.
Note: This might not always be equal to object.id.
wait_for This method periodically reloads model and then yields to specified block until block returns true or a timeout occurs.
The remainder of this document details the model abstraction. ## Create Queue Queues require a unique name. If you try to create a queue with a name that already exists, fog will throw a `Fog::Rackspace::Queues::ServiceError` exception with a 204 status code. To create a queue named demo-queue begin queue = service.queues.create :name => 'demo-queue' rescue Fog::Rackspace::Queues::ServiceError => e if e.status_code == 204 # duplicate queue exists end end ## Posting a Message to a Queue Messages can be any type of data, as long as they do not exceed 256 KB in length. Typical message bodies range from simple values, to a chunk of XML, or a list of JSON values. Fog handles the JSON-encoding required to post the message. You can post a message a message to your queue as follows: queue.messages.create :body => 'The laces were out!', :ttl => 360 You must supply both a body and a value for `ttl`. The value of `ttl` must be between 60 and 1209600 seconds (one minute to 14 days). ## Listing Messages in a Queue To list messages: queue.messages You can change the behavior by setting the follow attributes on the messages collection: Parameter | Default | Effect ---- | ---- | ---- **echo** | `true` | When `true`, your own messages are included. **include_claimed** | `false` | By default, only unclaimed messages are returned. Pass this as `true` to get all messages, claimed or not. **marker** | `nil` | Used for pagination. **limit** | `10` | The maximum number of messages to return. Note that you may receive fewer than the specified limit if there aren't that many available messages in the queue. For example, to include claimed messages: queue.messages.include_claimed = true queue.messages ## Claiming Messages in a Queue Claiming messages is how workers processing a queue mark messages as being handled by that worker, avoiding having two workers process the same message. Messages can be claimed and processed as follows: claims = queue.claims.create :ttl => 300, :grace => 100, :limit => 10 The parameters for this call are described in the following table: Parameter | Default | Notes ---- | ---- | ---- **ttl** | | The ttl attribute specifies how long the server waits before releasing the claim. The ttl value must be between 60 and 43200 seconds (12 hours). **grace** | | The grace attribute specifies the message grace period in seconds. The value of the grace period must be between 60 and 43200 seconds (12 hours). To deal with workers that have stopped responding (for up to 1209600 seconds or 14 days, including claim lifetime), the server extends the lifetime of claimed messages to be at least as long as the lifetime of the claim itself, plus the specified grace period. If a claimed message would normally live longer than the grace period, its expiration is not adjusted. **limit** | 10 | The number of messages to claim. The maximum number of messages you may claim at once is 20. If the claim is successful it will return a `Fog::Rackspace::Queues::Claims` object; if there are not any available messages it will return `false`. To iterate through the claimed messages: claim.messages.each do |message| # process message here message.destroy end **Note:** You will want to call the `destroy` method on the message after processing to insure it is not processed more than once. ## Renewing a Claim Once a claim has been made, if the TTL and grace period expire, the claim is automatically released and the messages are made available for others to claim. If you have a long-running process and want to ensure that this does not happen in the middle of the process, you should update the claim with one or both of a TTL or grace period. Updating resets the age of the claim, restarting the TTL for the claim. To update a claim, call: claim.ttl = 360 claim.grace = 360 claim.save ## Refreshing a Claim If you have a `Fog::Rackspace::Queues::claims` object, keep in mind that it is not a live window into the status of the claim; rather, it is a snapshot of the claim at the time the object was created. To refresh it with the latest information, call its `reload` method. This refreshes all of its attributes with the most current status of the claim. ## Releasing a Claim If you have a claim on several messages and must abandon processing of those messages for any reason, you should release the claim so that those messages can be processed by other workers as soon as possible, instead of waiting for the claim's TTL to expire. When you release a claim, the claimed messages are immediately made available in the queue for other workers to claim. To release a claim, call: claim.destroy fog-rackspace-0.1.6/lib/fog/rackspace/docs/storage.md0000644000004100000410000004246013411315054022451 0ustar www-datawww-data#Cloud Filesâ„¢ (storage) This document explains how to get started using Cloud Files with Fog. It assumes you have read the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. ## Starting irb console Start by executing the following command: irb Once `irb` has launched you need to require the Fog library. If using Ruby 1.8.x execute: require 'rubygems' require 'fog' If using Ruby 1.9.x execute: require 'fog' ## Create Service Next, create a connection to Cloud Files. Using a US-based account: service = Fog::Storage.new({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_region => :ord, # Defaults to :dfw :connection_options => {} # Optional }) Using a UK-based account: service = Fog::Storage.new({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT, :rackspace_region => :lon, :connection_options => {} # Optional }) To learn more about obtaining cloud credentials refer to the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. By default `Fog::Storage` will authenticate against the US authentication endpoint and connect to the DFW region. You can specify alternative authentication endpoints using the key `:rackspace_auth_url`. Please refer to [Alternate Authentication Endpoints](http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Endpoints-d1e180.html) for a list of alternative Rackspace authentication endpoints. Alternative regions are specified using the key `:rackspace_region `. A list of regions available for Cloud Files can be found by executing the following: identity_service = Fog::Identity({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT # Not specified for US Cloud }) identity_service.service_catalog.display_service_regions :cloudFiles Rackspace Private Cloud installations can skip specifying a region and directly specify their custom service endpoints using the keys `:rackspace_storage_url` and `:rackspace_cdn_url`. **Note**: A`Fog::Storage` instance is needed for the desired region. ### Optional Service Parameters The Storage service supports the following additional parameters:
Key Description
:rackspace_servicenet If set to true, the service will access Cloud Files using the internal Rackspace ServiceNet. This option should only be used for internal network connections.
:rackspace_cdn_ssl If set to true, the public_url method will return the SSL based URLs.
:persistent If set to true, the service will use a persistent connection.
:rackspace_storage_url The endpoint for the Cloud Files service. By default, Fog::Storage will pick the appropriate endpoint for region. This option will typically only be used for Rackspace Private Cloud Access.
:rackspace_cdn_url The endpoint for the CDN service. By default, Fog::Storage pick the appropriate endpoint for region. This option will typically only be used for Rackspace Private Cloud Access.
### Optional Connection Parameters Fog supports passing additional connection parameters to its underlying HTTP library (Excon) using the `:connection_options` parameter.
Key Description
:connect_timeout Connection timeout (default: 60 seconds)
:read_timeout Read timeout for connection (default: 60 seconds)
:write_timeout Write timeout for connection (default: 60 seconds)
:proxy Proxy for HTTP and HTTPS connections
:ssl_ca_path Path to SSL certificate authorities
:ssl_ca_file SSL certificate authority file
:ssl_verify_peer SSL verify peer (default: true)
:chunk_size The chunk size in bytes used for block transfers. By default, Fog uses 1 MB chunks.
## Fog Abstractions Fog provides both a **model** and **request** abstraction. The request abstraction provides the most efficient interface and the model abstraction wraps the request abstraction to provide a convenient `ActiveModel` like interface. ### Request Layer The request abstraction maps directly to the [Cloud Files API](http://docs.rackspace.com/files/api/v1/cf-devguide/content/Overview-d1e70.html). It provides the most efficient interface to the Rackspace Open Cloud. To see a list of requests supported by the storage service: service.requests This returns: :copy_object, :delete_container, :delete_object, :get_container, :get_containers, :get_object, :get_object_https_url, :head_container, :head_containers, :head_object, :put_container, :put_object, :put_object_manifest, :post_set_meta_temp_url_key To see a list of requests supported by the CDN service: service.cdn.requests This returns: :get_containers, :head_container, :post_container, :put_container, :delete_object #### Example Request To request a view account details: response = service.head_containers This returns in the following `Excon::Response`: #"2563554", "Date"=>"Thu, 21 Feb 2013 21:57:02 GMT", "X-Account-Meta-Temp-Url-Key"=>"super_secret_key", "X-Timestamp"=>"1354552916.82056", "Content-Length"=>"0", "Content-Type"=>"application/json; charset=utf-8", "X-Trans-Id"=>"txe934924374a744c8a6c40dd8f29ab94a", "Accept-Ranges"=>"bytes", "X-Account-Container-Count"=>"7", "X-Account-Object-Count"=>"5"}, @status=204, @body=""> To view the status of the response: response.status **Note**: Fog is aware of the valid HTTP response statuses for each request type. If an unexpected HTTP response status occurs, Fog will raise an exception. To view response headers: response.headers This will return: {"X-Account-Bytes-Used"=>"2563554", "Date"=>"Thu, 21 Feb 2013 21:57:02 GMT", "X-Account-Meta-Temp-Url-Key"=>"super_secret_key", "X-Timestamp"=>"1354552916.82056", "Content-Length"=>"0", "Content-Type"=>"application/json; charset=utf-8", "X-Trans-Id"=>"txe934924374a744c8a6c40dd8f29ab94a", "Accept-Ranges"=>"bytes", "X-Account-Container-Count"=>"7", "X-Account-Object-Count"=>"5"} To learn more about `Fog::Storage` request methods refer to [rdoc](http://rubydoc.info/gems/fog/Fog/Storage/Rackspace/Real). To learn more about Excon refer to [Excon GitHub repo](https://github.com/geemus/excon). ### Model Layer Fog models behave in a manner similar to `ActiveModel`. Models will generally respond to `create`, `save`, `destroy`, `reload` and `attributes` methods. Additionally, fog will automatically create attribute accessors. Here is a summary of common model methods:
Method Description
create Accepts hash of attributes and creates object.
Note: creation is a non-blocking call and you will be required to wait for a valid state before using resulting object.
save Saves object.
Note: not all objects support updating object.
destroy Destroys object.
Note: this is a non-blocking call and object deletion might not be instantaneous.
reload Updates object with latest state from service.
attributes Returns a hash containing the list of model attributes and values.
identity Returns the identity of the object.
Note: This might not always be equal to object.id.
The remainder of this document details the model abstraction. **Note:** Fog refers to Rackspace Cloud containers as directories. ## List Directories To retrieve a list of directories: service.directories This returns a collection of `Fog::Storage::Rackspace::Directory` models: , , ... ## Get Directory To retrieve a specific directory: service.directories.get "blue" **Note** As a general rule, only use `get` when you want to iterate over the contents of a `Directory` This call is similar to... service.directories.new :key => "blue" ... except the `get` method makes an HTTP call that returns metadata for up to the first 10,000 files. **This can be slow!** This returns a `Fog::Storage::Rackspace::Directory` instance: ## Create Directory To create a directory: service.directories.create :key => 'backups' To create a directory utilizing CDN: service.directories.create :key => 'web-assets', :public => true ### Additional Parameters The `create` method also supports the following key values:
Key Description
:metadata Hash containing directory metadata.
## Update Directory Cloud Files supports updating the `public` attribute to enable/disable CDN. To update this attribute: directory.public = false directory.save ## Delete Directory To delete a directory: directory.destroy **Note**: Directory must be empty before it can be deleted. ## List Files To list files in a directory: directory.files **Note**: File contents is not downloaded until `body` attribute is called. ## Upload Files To upload a file into a directory: file = directory.files.create :key => 'space.jpg', :body => File.open "space.jpg" **Note**: For files larger than 5 GB please refer to the [Upload Large Files](#upload_large_files) section. If you only need a `Directory` so that you can create a file (as above), you can accomplish this without an HTTP call as below: dir = service.directories.new :key => "blue" file = dir.files.new(...) file.save This will **not** retrieve the metadata for files in the `Directory`. However, if the `Directory` does not already exist in Cloud Files, the `save` call will return with a 404. In this case, you will need to `save` the `Directory` first... dir.save ... before you can... file.save ### Additional Parameters The `create` method also supports the following key values:
Key Description
:content_type The content type of the object. Cloud Files will attempt to auto detect this value if omitted.
:access_control_allow_origin URLs can make Cross Origin Requests. Format is http://www.example.com. Separate URLs with a space. An asterisk (*) allows all. Please refer to CORS Container Headers for more information.
:origin The origin is the URI of the object's host.
:etag The MD5 checksum of your object's data. If specified, Cloud Files will validate the integrity of the uploaded object.
:metadata Hash containing file metadata.
## Upload Large Files Cloud Files requires files larger than 5 GB to be uploaded into segments along with an accompanying manifest file. All of the segments must be uploaded to the same container. SEGMENT_LIMIT = 5368709119.0 # 5GB -1 BUFFER_SIZE = 1024 * 1024 # 1MB File.open(file_name) do |f| segment = 0 until file.eof? segment += 1 offset = 0 # upload segment to cloud files segment_suffix = segment.to_s.rjust(10, '0') service.put_object("my_container", "large_file/#{segment_suffix}", nil) do if offset <= SEGMENT_LIMIT - BUFFER_SIZE buf = file.read(BUFFER_SIZE).to_s offset += buf.size buf else '' end end end end # write manifest file service.put_object_manifest("my_container", "large_file", 'X-Object-Manifest' => "my_container/large_file/") Segmented files are downloaded like ordinary files. See [Download Files](#download-files) section for more information. ## Download Files The most efficient way to download files from a private or public directory is as follows: File.open('downloaded-file.jpg', 'w') do | f | directory.files.get("my_big_file.jpg") do | data, remaining, content_length | f.syswrite data end end This will download and save the file in 1 MB chunks. The chunk size can be changed by passing the parameter `:chunk_size` into the `:connection_options` hash in the service constructor. **Note**: The `body` attribute of file will be empty if a file has been downloaded using this method. If a file object has already been loaded into memory, you can save it as follows: File.open('germany.jpg', 'w') {|f| f.write(file_object.body) } **Note**: This method is more memory intensive as the entire object is loaded into memory before saving the file as in the example above. ## Accessing Files Through CDN The CDN service offers several different URLs to access your files. The simplest is with the default container URL. This can be accessed as follows: file.public_url For a more user-friendly URL, you can create a CNAME DNS record pointing to the URL generated by the `public_url` method. Then set the CNAME on the `Directory` object using the attribute `cdn_cname`. Note, that the `cdn_cname` attribute does not persist and will need to be specified every time a directory object is retrieved. To access the file using SSL, you need to specify the option `:rackspace_cdn_ssl => true` when creating `Fog::Storage` service. This will cause the `public_url` method to return the SSL-secured URL. To stream content use the following: file.streaming_url To stream video for iOS devices without needing to convert your video use the following: file.ios_url ## Metadata You can access metadata as an attribute on both `Fog::Storage::Rackspace::Directory` and `Fog::Storage::Rackspace::File`. This example demonstrates how to iterate through a directory's metadata: directory.metadata.each_pair {|metadatum| puts "#{metadatum.key}: #{metadatum.value}" } You can update and retrieve metadata in a manner similar to a hash: directory.metadata[:thumbnails] file.metadata[:environment] = "development" Directory metadata is saved when the directory is saved and file metadata is set when the file is saved: directory.save file.save Metadata is reloaded when directory or file is reloaded: directory.reload file.reload ## Copy File Cloud Files supports copying files. To copy files into a container named "trip" with a name of "europe.jpg" do the following: file.copy("trip", "europe.jpg") To move or rename a file, perform a copy operation and then delete the old file: file.copy("trip", "germany.jpg") file.destroy ## Delete File To delete a file: file.destroy ## CDN Purge To immediately remove a file from the CDN network use the following: file.purge_from_cdn You may only purge up to 25 objects per day and thus this should only be used in situations where there could be serious personal, business, or security consequences if the object remained in the CDN. To purge a directory, please contact Rackspace support. **Note**: You may only **PURGE** up to 25 objects per day. Any attempt to purge more than this will result in a 498 status code error (Rate Limited). ## Account Information To view Cloud Files usage execute the following: service.account This returns a `Fog::Storage::Rackspace::Account` instance: ## Examples Example code using Cloud Files can be found [here](https://github.com/fog/fog/tree/master/lib/fog/rackspace/examples). ## Additional Resources * [fog.io](http://fog.io/) * [Fog rdoc](http://rubydoc.info/gems/fog/) * [Fog Github repo](https://github.com/fog/fog) * [Fog Github Issues](https://github.com/fog/fog/issues) * [Excon Github repo](https://github.com/geemus/excon) * [Cloud Files API](http://docs.rackspace.com/files/api/v1/cf-devguide/content/Overview-d1e70.html) ## Support and Feedback Your feedback is appreciated! If you have specific issues with the **fog** SDK, you should file an [issue via Github](https://github.com/fog/fog/issues). For general feedback and support requests, please visit: https://developer.rackspace.com/support. fog-rackspace-0.1.6/lib/fog/rackspace/docs/auto_scale.md0000644000004100000410000005532213411315054023125 0ustar www-datawww-data#Auto Scale (AutoScale) This document explains how to get started using Auto Scale with Fog. It assumes you have read the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. ## Basic Concepts Auto Scale is a service that enables you to scale your application by adding or removing servers based on monitoring events, a schedule, or arbitrary webhooks. Auto Scale functions by linking three services: * Monitoring (such as Monitoring as a Service) * Auto Scale * Servers and Load Balancers ## Workflow A scaling group is monitored by Rackspace Cloud Monitoring. When Monitoring triggers an alarm for high utilization within the Autoscaling group, a webhook is triggered. The webhook calls the Auto Scale service, which consults a policy in accordance with the webhook. The policy determines how many additional Cloud Servers should be added or removed in accordance with the alarm. Alarms may trigger scaling up or scaling down. Scale-down events always remove the oldest server in the group. Cooldowns allow you to ensure that you don't scale up or down too fast. When a scaling policy runs, both the scaling policy cooldown and the group cooldown start. Any additional requests to the group are discarded while the group cooldown is active. Any additional requests to the specific policy are discarded when the policy cooldown is active. It is important to remember that Auto Scale does not configure anything within a server. This means that all images should be self-provisioning. It is up to you to make sure that your services are configured to function properly when the server is started. We recommend using something like Chef, Salt, or Puppet. ## Starting irb console Start by executing the following command: irb Once `irb` has launched you need to require the Fog library. If using Ruby 1.8.x execute: require 'rubygems' require 'fog' If using Ruby 1.9.x execute: require 'fog' ## Create Service Next, create a connection to Auto Scale: Using a US-based account: service = Fog::Rackspace::AutoScale.new ( :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_region => :ord, :connection_options => {} # Optional ) Using a UK-based account: service = Fog::Rackspace::AutoScale.new ( :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT, :rackspace_region => :lon, :connection_options => {} # Optional ) To learn more about obtaining cloud credentials refer to the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. By default `Fog::Rackspace::AutoScale` will authenticate against the US authentication endpoint. You can specify alternative authentication endpoints using the key `:rackspace_auth_url`. Please refer to [Alternate Authentication Endpoints](http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Endpoints-d1e180.html) for a list of alternative Rackspace authentication endpoints. Alternative regions are specified using the key `:rackspace_region `. A list of regions available for Auto Scale can be found by executing the following: identity_service = Fog::Identity.new({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT # Not specified for US Cloud }) identity_service.service_catalog.display_service_regions :autoscale Rackspace Private Cloud installations can skip specifying a region and directly specify their custom service endpoints using the key `:rackspace_auto_scale_url`. **Note**: A`Fog::Rackspace::AutoScale` instance is needed for the desired region. ### Optional Connection Parameters Fog supports passing additional connection parameters to its underlying HTTP library (Excon) using the `:connection_options` parameter.
Key Description
:connect_timeout Connection timeout (default: 60 seconds)
:read_timeout Read timeout for connection (default: 60 seconds)
:write_timeout Write timeout for connection (default: 60 seconds)
:proxy Proxy for HTTP and HTTPS connections
:ssl_ca_path Path to SSL certificate authorities
:ssl_ca_file SSL certificate authority file
:ssl_verify_peer SSL verify peer (default: true)
## Fog Abstractions Fog provides both a **model** and **request** abstraction. The request abstraction provides the most efficient interface and the model abstraction wraps the request abstraction to provide a convenient `ActiveModel`-like interface. ### Request Layer The request abstraction maps directly to the [Auto Scale API](http://docs.rackspace.com//cas/api/v1.0/autoscale-devguide/content/API_Operations.html). It provides the most efficient interface to the Rackspace Open Cloud. To see a list of requests supported by the service: service.requests This returns: :list_groups, :create_group, :get_group, :delete_group, :get_group_state, :pause_group_state, :resume_group_state, :get_group_config, :update_group_config, :get_launch_config, :update_launch_config, :list_policies, :create_policy, :get_policy, :update_policy, :delete_policy, :execute_policy, :execute_anonymous_webhook, :get_webhook, :list_webhooks, :create_webhook, :update_webhook, :delete_webhook #### Example Request To request a list of Auto Scale groups: response = service.list_groups This returns in the following `Excon::Response`: #{"groups_links"=>[], "groups"=>[{"paused"=>false, "desiredCapacity"=>0, "links"=>[{"href"=>"https://ord.autoscale.api.rackspacecloud.com/v1.0/555/groups/b45e6107-26ca-4a93-869d-46bf20005df3/", "rel"=>"self"}], "active"=>[], "pendingCapacity"=>0, "activeCapacity"=>0, "id"=>"b45e6107-26ca-4a93-869d-46bf20005df3", "name"=>"fog-scailing-group"}]}, :headers=>{"Content-Type"=>"application/json", "Via"=>"1.1 Repose (Repose/2.8.2)", "x-response-id"=>"4c2a8f70-a7da-479a-bf69-6882b5b6346e", "Date"=>"Fri, 27 Sep 2013 15:38:10 GMT", "Transfer-Encoding"=>"chunked", "Server"=>"Jetty(8.0.y.z-SNAPSHOT)"}, :status=>200, :remote_ip=>"162.209.41.103"}, @body="{\"groups_links\": [], \"groups\": [{\"paused\": false, \"desiredCapacity\": 0, \"links\": [{\"href\": \"https://ord.autoscale.api.rackspacecloud.com/v1.0/555/groups/b45e6107-26ca-4a93-869d-46bf20005df3/\", \"rel\": \"self\"}], \"active\": [], \"pendingCapacity\": 0, \"activeCapacity\": 0, \"id\": \"b45e6107-26ca-4a93-869d-46bf20005df3\", \"name\": \"fog-scailing-group\"}]}", @headers={"Content-Type"=>"application/json", "Via"=>"1.1 Repose (Repose/2.8.2)", "x-response-id"=>"4c2a8f70-a7da-479a-bf69-6882b5b6346e", "Date"=>"Fri, 27 Sep 2013 15:38:10 GMT", "Transfer-Encoding"=>"chunked", "Server"=>"Jetty(8.0.y.z-SNAPSHOT)"}, @status=200, @remote_ip="162.209.41.103"> To view the status of the response: response.status **Note**: Fog is aware of valid HTTP response statuses for each request type. If an unexpected HTTP response status occurs, Fog will raise an exception. To view response body: response.body returns: {"groups_links"=>[], "groups"=>[{"paused"=>false, "desiredCapacity"=>0, "links"=>[{"href"=>"https://ord.autoscale.api.rackspacecloud.com/v1.0/555/groups/b45e6107-26ca-4a93-869d-46bf20005df3/", "rel"=>"self"}], "active"=>[], "pendingCapacity"=>0, "activeCapacity"=>0, "id"=>"b45e6107-26ca-4a93-869d-46bf20005df3", "name"=>"fog-scailing-group"}]} To learn more about Auto Scale request methods refer to [rdoc](http://rubydoc.info/gems/fog/Fog/Rackspace/AutoScale/Real). To learn more about Excon refer to [Excon GitHub repo](https://github.com/geemus/excon). ### Model Layer Fog models behave in a manner similar to `ActiveModel`. Models will generally respond to `create`, `save`, `persisted?`, `destroy`, `reload` and `attributes` methods. Additionally, fog will automatically create attribute accessors. Here is a summary of common model methods:
Method Description
create Accepts hash of attributes and creates object.
Note: creation is a non-blocking call and you will be required to wait for a valid state before using resulting object.
save Saves object.
Note: not all objects support updating object.
persisted? Returns true if the object has been persisted.
destroy Destroys object.
Note: this is a non-blocking call and object deletion might not be instantaneous.
reload Updates object with latest state from service.
ready? Returns true if object is in a ready state and able to perform actions. This method will raise an exception if object is in an error state.
attributes Returns a hash containing the list of model attributes and values.
identity Returns the identity of the object.
Note: This might not always be equal to object.id.
wait_for This method periodically reloads model and then yields to specified block until block returns true or a timeout occurs.
The remainder of this document details the model abstraction. ## The Scaling Group * The **Scaling Group** is the basic unit of automatic scaling. It determines the minimum and maximum number of servers that exist at any time for the group, the cooldown period between scaling events, the configuration for each new server, the load balancer to add these servers to (optional), and any policies that are used for this group. ### List Scaling Groups To retrieve the list of your scaling groups: service.groups This returns a collection of `Fog::Rackspace::AutoScale::Group` objects: "https://ord.autoscale.api.rackspacecloud.com/v1.0/555/groups/b45e6107-26ca-4a93-869d-46bf20005df3/", "rel"=>"self"}] > ] > To view the [launch configuration](#launch-configurations) for a group execute the following: groups = service.groups group = group.first group.launch_config This returns a `Fog::Rackspace::AutoScale::LaunchConfig`: "https://ord.autoscale.api.rackspacecloud.com/v1.0/5555/groups/b45e6107-26ca-4a93-869d-46bf20005df3/", "rel"=>"self"}] >, type="launch_server", args={"loadBalancers"=>[{"port"=>8080, "loadBalancerId"=>9099}], "server"=>{"name"=>"autoscale_server", "imageRef"=>"0d589460-f177-4b0f-81c1-8ab8903ac7d8", "flavorRef"=>"2", "OS-DCF =>diskConfig"=>"AUTO", "metadata"=>{"build_config"=>"core", "meta_key_1"=>"meta_value_1", "meta_key_2"=>"meta_value_2"}, "networks"=>[{"uuid"=>"11111111-1111-1111-1111-111111111111"}, {"uuid"=>"00000000-0000-0000-0000-000000000000"}], "personality"=>[{"path"=>"/root/.csivh", "contents"=>"VGhpcyBpcyBhIHRlc3QgZmlsZS4="}]}} > ### Getting the Current State of a Scaling Group It is sometimes helpful to determine what the current state of a scaling group is in terms of whether it is scaling up, scaling down, or stable. To see your group's current state execute the following: group.state This returns the following: {"paused"=>false, "desiredCapacity"=>0, "links"=>[{"href"=>"https://ord.autoscale.api.rackspacecloud.com/v1.0/555/groups/b45e6107-26ca-4a93-869d-46bf20005df3/", "rel"=>"self"}], "active"=>[], "pendingCapacity"=>0, "activeCapacity"=>0, "id"=>"b45e6107-26ca-4a93-869d-46bf20005df3", "name"=>"fog-scailing-group"} The `active` key holds a list of the IDs of the servers created as part of this scaling group. The `paused` key shows whether or not the scaling group's response to alarms is active or not. There are 3 'capacity'-related keys: `activeCapacity`, `desiredCapacity`, and `pendingCapacity`: Key | Represents ---- | ---- **activeCapacity** | The number of active servers that are part of this scaling group **desiredCapacity** | The target number of servers for this scaling group, based on the combination of configuration settings and monitoring alarm responses **pendingCapacity** | The number of servers which are in the process of being created (when positive) or destroyed (when negative). ### Pausing a Scaling Group's Policies To pause a scaling group's execution: group.pause There is a corresponding `resume` method to resume execution: group.resume ### Creating a Scaling Group There are many options available to you when creating a scaling group. In order to ease the burden, a builder is provided. To create a scaling group with the builder you first include the builder in your script: require 'fog/rackspace/models/auto_scale/group_builder' And then use the builder as follows: INTERNET = '00000000-0000-0000-0000-000000000000' SERVICE_NET = '11111111-1111-1111-1111-111111111111' attributes = { :server_name => "testgroup", :image => my_image, :flavor => 3, :networks => [INTERNET, SERVICE_NET], :personality => [ { "path" => "/root/.csivh", "contents" => "VGhpcyBpcyBhIHRlc3QgZmlsZS4=" } ], :max_entities => 3, :min_entities => 2, :cooldown => 600, :name => "MyScalingGroup", :metadata => { "created_by" => "autoscale sample script" }, :load_balancers => { :port => 80, :loadBalancerId => 1234 } :launch_config_type => :launch_server } group = Fog::Rackspace::AutoScale::GroupBuilder.build(service, attributes) group.save This creates the scaling group with the name `MyScalingGroup`, and returns a `Fog::Rackspace::AutoScale::Group` object representing the new group. Since the `:min_entities` is 2, it immediately creates 2 servers for the group, based on the image whose ID is in the variable `my_image`. When they are created, they are then added to the load balancer whose ID is `1234`, and receive requests on port 80. Note that the `:server_name` parameter represents a base string to which Autoscale prepends a 10-character prefix to create a unique name for each server. The prefix always begins with 'as' and is followed by 8 random hex digits and a dash (-). For example, if you set the server_name to 'testgroup', and the scaling group creates 3 servers, their names would look like these: as5defddd4-testgroup as92e512fe-testgroup asedcf7587-testgroup **Note**: You will see need to add policies to trigger auto scaling operations. See [Policies Section](#policies) for more information. #### Parameters Parameter | Required | Default | Notes ---- | ---- | ---- | ---- **:name** | yes | | **:cooldown** | yes | | Period in seconds after a scaling event in which further events are ignored **:min_entities** | yes | | **:max_entities** | yes | | **:launch_config_type** | yes | | Only option currently is`:launch_server` **:flavor** | yes | | Flavor to use for each server that is launched. This can be a `Fog::Compute::RackspaceV2::Flavor` or an ID. **:server_name** | yes | | The base name for servers created by Autoscale. **:image** | yes | | This can be a `Fog::Compute::RackspaceV2::Image` or an id. This is the image that all new servers are created from. **:disk_config** | no | MANUAL | Determines if the server's disk is partitioned to the full size of the flavor ('AUTO') or just to the size of the image ('MANUAL'). **:server_metadata** | no | | Arbitrary key-value pairs you want to associate with your servers. **:personality** | no | | Small text files that are created on the new servers. _Personality_ is discussed in the [Rackspace Cloud Servers documentation](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Personality-d1e2543.html) **:networks** | no | | Any array of networks to which you want to attach new servers. See the [Create Servers documentation](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/CreateServers.html) for standard network IDs. **:load_balancers** | no | | Either a hash of {:port, :loadBalancerId} or a `Fog::Rackspace::LoadBalancers::LoadBalancer` object. ### Updating a Scaling Configuration Group A group's scaling configuration can be updated via the `Fog::Rackspace::AutoScale::GroupConfig` object. You can retrieve this object by executing the following: group_config = group.group_config Available options on `group_config` include `:max_entities`, `:name`, `:cooldown`, `:min_entities`, `:metadata`. To update a scaling group, pass one or more of these as keyword arguments. For example, to change the cooldown period to 2 minutes and increase the maximum entities to 16, you call: group_config.cooldown = 120 group_config.max_entities = 16 group_config.save **Note**: If you pass any metadata values in this call, it must be the full set of metadata for the scaling group, since the underlying API call **overwrites** any existing metadata. ### Deleting a Scaling Group To remove a scaling group, call its `destroy` method: group.destroy Note: you cannot delete a scaling group that has active servers in it. You must first delete the servers by setting the `min_entities` and `max_entities` to zero: group_config = group.group_config group_config.min_entities = 0 group_config.max_entities = 0 group_config.save Once the servers are deleted you can then delete the scaling group. ## Launch Configurations Each scaling group has an associated **launch configuration**. This determines the properties of servers that are created in response to a scaling event. The `:server_name` represents a base string to which Autoscale prepends a 10-character prefix. The prefix always begins with 'as' and is followed by 8 random hex digits and a dash (-). For example, if you set the `server_name` to 'testgroup', and the scaling group creates 3 servers, their names would look like these: as5defddd4-testgroup as92e512fe-testgroup asedcf7587-testgroup To retrieve the launch config: launch_config = group.launch_config The launch configuration contains two attributes `:type` and `:args`. The only launch type currently available for Auto Scale is `:launch_server`. The `args` attribute contains a hash with the launch server configuration options as follows: {"server"=>{ "name"=>"autoscale_server", "imageRef"=>"66448837-1a58-4bd2-a647-9f3272f36263", "flavorRef"=>"2", "networks"=>[{"uuid"=>"00000000-0000-0000-0000-000000000000"}, {"uuid"=>"11111111-1111-1111-1111-111111111111"}], "personality"=>[{"path"=>"/root/.csivh", "contents"=>"VGhpcyBpcyBhIHRlc3QgZmlsZS4="}], "OS-DCF =>diskConfig"=>"MANUAL", "metadata"=>{}}} Changes to the args attribute can be saved by executing the `save` method on the `launch_config`. For example if you wanted to change the disk configuration to `AUTO`, you would do the following: launch_config.args["server"]["OS-DCF =>diskConfig"] = "AUTO" launch_config.save **Note**: If you pass any metadata values in this call, it must be the full set of metadata for the launch configuration, since the underlying API call **overwrites** any existing metadata. ## Policies When an alarm is triggered in Cloud Monitoring, it calls the webhook associated with a particular policy. The policy is designed to update the scaling group to increase or decrease the number of servers in response to the particular alarm. To list the policies for a given scaling group use the following: policies = group.policies ### Creating a Policy To add a policy to a scaling group use the following: group.policies.create :name => 'Scale by one server', :cooldown => 360, :type => 'webhook', :change => 1 #### Parameters Parameter | Required | Default | Notes ---- | ---- | ---- | ---- **:name** | yes | | **:type** | yes | | This can be "webhook", "schedule" or "cloud monitoring" **:cooldown** | yes | | Period in seconds after a policy execution in which further events are ignored. This is separate from the overall cooldown for the scaling group. **:change** | no | | Can be positive or negative, which makes this a scale-up or scale-down policy, respectively. If this value is specified you can not specify `:change_percent`. **:change_percent** | no | | The percentage change to the autoscale group's number of units. If this value is specified you can not specify `:change`. **:args** | no | | This is used to specify schedule parameters. Please refer to [Policy documentation](http://docs-internal-staging.rackspace.com/cas/api/v1.0/autoscale-devguide/content/POST_createPolicies_v1.0__tenantId__groups__groupId__policies_Policies.html) for more information. ### Updating a Policy You may update a policy at any time, passing in any or all of the above parameters to change that value. For example, to change the cooldown to 60 seconds, and the number of servers to remove to 3, call: policy.cooldown = 60 policy.change = 3 policy.save ### Executing a Policy You don't need to wait for an alarm to be triggered in Cloud Monitoring in order to execute a particular policy. If desired, you may do so manually by calling the policy's `execute` method: policy.execute ### Deleting a Policy To remove a policy, call its `destroy` method: policy.destroy ## Webhooks When an alarm is triggered in Cloud Monitoring, it calls the associated webhook, which in turn causes the policy for that webhook to be executed. To list the webhooks for a given policy: webhooks = policy.webhooks ### Creating a Webhook To add a webhook to a policy: webhook = policy.webhooks.create :name => 'my-webhook' The `:name` parameter is required; the `:metadata` parameter is optional. You can retrieve the webhook by executing: webhook.execution_url ### Updating a Webhook You may update a webhook at any time to change either its name or its metadata: webhook.name = 'webhook1' webhook.metadata = { :owner => 'webteam' } webhook.save **Note**: If you pass any metadata values in this call, it must be the full set of metadata for the Webhook, since the underlying API call **overwrites** any existing metadata. ### Deleting a webhook When you wish to remove a webhook, call its `destroy` method: webhook.destroy fog-rackspace-0.1.6/lib/fog/rackspace/docs/networking_v2.md0000644000004100000410000003215613411315054023604 0ustar www-datawww-data#NetworkingV2 (neutron) This document explains how to get started using NetworkingV2 with Fog. It assumes you have read the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. ## Starting irb console Start by executing the following command: irb Once `irb` has launched you need to require the Fog library. If using Ruby 1.8.x execute: require 'rubygems' require 'fog' If using Ruby 1.9.x execute: require 'fog' ## Create Service Next, create a connection to Rackspace's NetworkingV2 API: Using a US-based account: service = Fog::Rackspace::NetworkingV2.new({ :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_region => :ord, # Defaults to :dfw }) Using a UK-based account: service = Fog::Compute.new({ :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT, :rackspace_region => :lon, }) To learn more about obtaining cloud credentials refer to the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. By default `Fog::Rackspace::NetworkingV2` will authenticate against the US authentication endpoint and connect to the DFW region. You can specify alternative authentication endpoints using the key `:rackspace_auth_url`. Please refer to [Alternate Authentication Endpoints](http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Endpoints-d1e180.html) for a list of alternative Rackspace authentication endpoints. Alternative regions are specified using the key `:rackspace_region `. A list of regions available for Cloud Servers can be found by executing the following: identity_service = Fog::Identity({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT # Not specified for US Cloud }) identity_service.service_catalog.display_service_regions :cloudServersOpenStack ### Optional Connection Parameters Fog supports passing additional connection parameters to its underlying HTTP library (Excon) using the `:connection_options` parameter.
Key Description
:connect_timeout Connection timeout (default: 60 seconds)
:read_timeout Read timeout for connection (default: 60 seconds)
:write_timeout Write timeout for connection (default: 60 seconds)
:proxy Proxy for HTTP and HTTPS connections
:ssl_ca_path Path to SSL certificate authorities
:ssl_ca_file SSL certificate authority file
:ssl_verify_peer SSL verify peer (default: true)
## Fog Abstractions Fog provides both a **model** and **request** abstraction. The request abstraction provides the most efficient interface and the model abstraction wraps the request abstraction to provide a convenient `ActiveModel` like interface. ### Request Layer The request abstraction maps directly to the [NetworkingV2 API](http://docs.rackspace.com/networks/api/v2/cn-devguide/content/ch_overview.html). It provides the most efficient interface to the Rackspace NetworkingV2 To see a list of requests supported by the service: service.requests This returns: [:list_networks, :create_network, :show_network, :update_network, :delete_network, :list_subnets, :create_subnet, :show_subnet, :update_subnet, :delete_subnet, :list_ports, :create_port, :show_port, :update_port, :delete_port] #### Example Request To request a list of flavors: response = service.list_networks This returns in the following `Excon::Response`: #{"networks"=>[{"status"=>"ACTIVE", "subnets"=>["79a2a078-84bd-4ffd-8e68-67f7854bb772"], "name"=>"Testing", "admin_state_up"=>true, "tenant_id"=>"000000", "shared"=>false, "id"=>"eff4da21-e006-4468-b9ce-798eb2fed3e8"}]}, :headers=>{"Content-Type"=>"application/json; charset=UTF-8", "Via"=>"1.1 Repose (Repose/2.12)", "Content-Length"=>"218", "Date"=>"Wed, 17 Dec 2014 19:37:49 GMT", "Server"=>"Jetty(8.0.y.z-SNAPSHOT)"}, :status=>200, :reason_phrase=>"OK", :remote_ip=>"69.20.65.143", :local_port=>63382, :local_address=>"192.168.1.80"}, @body="{\"networks\": [{\"status\": \"ACTIVE\", \"subnets\": [\"79a2a078-84bd-4ffd-8e68-67f7854bb772\"], \"name\": \"Testing\", \"admin_state_up\": true, \"tenant_id\": \"000000\", \"shared\": false, \"id\": \"eff4da21-e006-4468-b9ce-798eb2fed3e8\"}]}", @headers={"Content-Type"=>"application/json; charset=UTF-8", "Via"=>"1.1 Repose (Repose/2.12)", "Content-Length"=>"218", "Date"=>"Wed, 17 Dec 2014 19:37:49 GMT", "Server"=>"Jetty(8.0.y.z-SNAPSHOT)"}, @status=200, @remote_ip="69.20.0.0", @local_port=63382, @local_address="192.168.1.80"> To view the status of the response: response.status **Note**: Fog is aware of valid HTTP response statuses for each request type. If an unexpected HTTP response status occurs, Fog will raise an exception. To view response body: response.body This will return: {"networks"=>[{"status"=>"ACTIVE", "subnets"=>["79a2a078-84bd-4ffd-8e68-67f7854bb772"], "name"=>"Testing", "admin_state_up"=>true, "tenant_id"=>"000000", "shared"=>false, "id"=>"eff4da21-e006-4468-b9ce-798eb2fed3e8"}]} To learn more about NetworkingV2 request methods refer to [rdoc](http://www.rubydoc.info/gems/fog/Fog/Rackspace/NetworkingV2/Real). To learn more about Excon refer to [Excon GitHub repo](https://github.com/geemus/excon). ### Model Layer Fog models behave in a manner similar to `ActiveModel`. Models will generally respond to `create`, `save`, `persisted?`, `destroy`, `reload` and `attributes` methods. Additionally, fog will automatically create attribute accessors. Here is a summary of common model methods:
Method Description
create Accepts hash of attributes and creates object.
Note: creation is a non-blocking call and you will be required to wait for a valid state before using resulting object.
save Saves object.
Note: not all objects support updating object.
persisted? Returns true if the object has been persisted.
destroy Destroys object.
Note: this is a non-blocking call and object deletion might not be instantaneous.
reload Updates object with latest state from service.
ready? Returns true if object is in a ready state and able to perform actions. This method will raise an exception if object is in an error state.
attributes Returns a hash containing the list of model attributes and values.
identity Returns the identity of the object.
Note: This might not always be equal to object.id.
wait_for This method periodically reloads model and then yields to specified block until block returns true or a timeout occurs.
The remainder of this document details the model abstraction. ## List Networks To retrieve a list of available networks: service.networks This returns a collection of `Fog::Rackspace::NetworkingV2::Network` models: ] > ## Create Network Create a network: service.networks.create(label: "new_network", cidr: "192.168.0.0/24") ## Get Network To retrieve individual network: service.networks.get "eff4da21-e006-4468-b9ce-798eb2fed3e8" This returns an `Fog::Rackspace::NetworkingV2::Network` instance: ## Delete Network To delete a network: network.destroy **Note**: The network is not immediately destroyed, but it does occur shortly there after. ## List Subnets To retrieve a list of available subnets: service.subnets This returns a collection of `Fog::Rackspace::NetworkingV2::Subnet` models: "192.168.3.1", "end"=>"192.168.3.254"}], host_routes=[], ip_version=4, gateway_ip=nil, cidr="192.168.3.0/24" > ] > ## Create Subnet Create a subnet: subnet = service.subnets.new({ :name => "ANewsubnet", :cidr => "192.168.101.1/24", :network_id => "79a2a078-84bd-4ffd-8e68-67f7854bb772", :ip_version => "4" }).save ## Get Subnet To retrieve individual subnet: service.subnets.get "79a2a078-84bd-4ffd-8e68-67f7854bb772" This returns an `Fog::Rackspace::NetworkingV2::Subnet` instance: "192.168.3.1", "end"=>"192.168.3.254"}], host_routes=[], ip_version=4, gateway_ip=nil, cidr="192.168.3.0/24" > ## Delete Subnet To delete a subnet: subnet.destroy **Note**: The subnet is not immediately destroyed, but it does occur shortly there after. ## List Ports To retrieve a list of available ports: service.ports This returns a collection of `Fog::Rackspace::NetworkingV2::Port` models: "192.168.3.1", "end"=>"192.168.3.254"}], host_routes=[], ip_version=4, gateway_ip=nil, cidr="192.168.3.0/24" > ] > ## Create Port Create a port: s.ports.new({name: "something", network_id: network.id}).save "79a2a078-84bd-4ffd-8e68-67f7854bb772", "ip_address"=>"192.168.3.1"}], mac_address="BC:76:4E:20:CB:0D", name="something", network_id="eff4da21-e006-4468-b9ce-798eb2fed3e8", security_groups=[], status="ACTIVE", tenant_id="000000" > ] > ## Get Port To retrieve individual port: service.ports.get "f90c5970-1bce-4403-82ee-7713854de7c7" This returns an `Fog::Rackspace::NetworkingV2::Port` instance: "79a2a078-84bd-4ffd-8e68-67f7854bb772", "ip_address"=>"192.168.3.1"}], mac_address="BC:76:4E:20:CB:0D", name="something", network_id="eff4da21-e006-4468-b9ce-798eb2fed3e8", security_groups=[], status="ACTIVE", tenant_id="000000" > ## Delete Port To delete a port: port.destroy **Note**: The port is not immediately destroyed, but it does occur shortly there after. ## Examples Example code using Networking can be found [here](https://github.com/fog/fog/tree/master/lib/fog/rackspace/examples). ## Additional Resources * [fog.io](http://fog.io/) * [Fog rdoc](http://rubydoc.info/gems/fog/) * [Fog Github repo](https://github.com/fog/fog) * [Fog Github Issues](https://github.com/fog/fog/issues) * [Excon Github repo](https://github.com/geemus/excon) * [Rackspace Networking API](http://docs.rackspace.com/networking/api/v2/cs-devguide/content/ch_preface.html) ## Support and Feedback Your feedback is appreciated! If you have specific issues with the **fog** SDK, you should file an [issue via Github](https://github.com/fog/fog/issues). For general feedback and support requests, please visit: https://developer.rackspace.com/support. fog-rackspace-0.1.6/lib/fog/rackspace/docs/block_storage.md0000644000004100000410000003125013411315054023616 0ustar www-datawww-data#Cloud Block Storage (BlockStorage) This document explains how to get started using Cloud Block Storage with Fog. It assumes you have read the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. ## Starting irb console Start by executing the following command: irb Once `irb` has launched you need to require the Fog library. If using Ruby 1.8.x execute: require 'rubygems' require 'fog' If using Ruby 1.9.x execute: require 'fog' ## Create Service Next, create a connection to Cloud Block Storage: Using a US-based account: service = Fog::Rackspace::BlockStorage.new({ :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_region => :ord, # Defaults to :dfw :connection_options => {} # Optional }) Using a UK-based account: service = Fog::Rackspace::BlockStorage.new({ :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT, :rackspace_region => :lon, :connection_options => {} # Optional }) To learn more about obtaining cloud credentials refer to the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. By default `Fog::Rackspace::BlockStorage` will authenticate against the US authentication endpoint and connect to the DFW region. You can specify alternative authentication endpoints using the key `:rackspace_auth_url`. Please refer to [Alternate Authentication Endpoints](http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Endpoints-d1e180.html) for a list of alternative Rackspace authentication endpoints. Alternative regions are specified using the key `:rackspace_region `. A list of regions available for Cloud Block Storage can be found by executing the following: identity_service = Fog::Identity({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT # Not specified for US Cloud }) identity_service.service_catalog.display_service_regions :cloudBlockStorage Rackspace Private Cloud installations can skip specifying a region and directly specify their custom service endpoints using the key `:rackspace_block_storage_url`. **Note**: A`Fog::Rackspace::BlockStorage` instance is needed for the desired region. ### Optional Connection Parameters Fog supports passing additional connection parameters to its underlying HTTP library (Excon) using the `:connection_options` parameter.
Key Description
:connect_timeout Connection timeout (default: 60 seconds)
:read_timeout Read timeout for connection (default: 60 seconds)
:write_timeout Write timeout for connection (default: 60 seconds)
:proxy Proxy for HTTP and HTTPS connections
:ssl_ca_path Path to SSL certificate authorities
:ssl_ca_file SSL certificate authority file
:ssl_verify_peer SSL verify peer (default: true)
## Fog Abstractions Fog provides both a **model** and **request** abstraction. The request abstraction provides the most efficient interface and the model abstraction wraps the request abstraction to provide a convenient `ActiveModel` like interface. ### Request Layer The request abstraction maps directly to the [Cloud Block Storage API](http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/overview.html). It provides the most efficient interface to the Rackspace Open Cloud. To see a list of requests supported by the service: service.requests This returns: :create_volume, :delete_volume, :get_volume, :list_volumes, :get_volume_type, :list_volume_types, :create_snapshot, :delete_snapshot, :get_snapshot, :list_snapshots #### Example Request To request a list of volume types: response = service.list_volume_types This returns in the following `Excon::Response`: "Mon, 18 Mar 2013 20:26:03 GMT", "Content-Length"=>"109", "Content-Type"=>"application/json", "X-Compute-Request-Id"=>"req-9c2093d4-8a41-4d8b-a069-114470d1a0dd"}, @data={:status=>200, :headers=>{"Date"=>"Mon, 18 Mar 2013 20:26:03 GMT", "Content-Length"=>"109", "Content-Type"=>"application/json", "X-Compute-Request-Id"=>"req-9c2093d4-8a41-4d8b-a069-114470d1a0dd"}, :remote_ip=>"72.32.164.210", :body=>{"volume_types"=>[{"name"=>"SATA", "id"=>1, "extra_specs"=>{}}, {"name"=>"SSD", "id"=>2, "extra_specs"=>{}}]}}> To view the status of the response: response.status **Note**: Fog is aware of valid HTTP response statuses for each request type. If an unexpected HTTP response status occurs, Fog will raise an exception. To view response body: response.body This will return: {"volume_types"=>[{"name"=>"SATA", "id"=>1, "extra_specs"=>{}}, {"name"=>"SSD", "id"=>2, "extra_specs"=>{}}]} To learn more about Cloud Block Storage request methods refer to [rdoc](http://rubydoc.info/gems/fog/Fog/Rackspace/BlockStorage/Real). To learn more about Excon refer to [Excon GitHub repo](https://github.com/geemus/excon). ### Model Layer Fog models behave in a manner similar to `ActiveModel`. Models will generally respond to `create`, `save`, `persisted?`, `destroy`, `reload` and `attributes` methods. Additionally, fog will automatically create attribute accessors. Here is a summary of common model methods:
Method Description
create Accepts hash of attributes and creates object.
Note: creation is a non-blocking call and you will be required to wait for a valid state before using resulting object.
save Saves object.
Note: not all objects support updating object.
persisted? Returns true if the object has been persisted.
destroy Destroys object.
Note: this is a non-blocking call and object deletion might not be instantaneous.
reload Updates object with latest state from service.
ready? Returns true if object is in a ready state and able to perform actions. This method will raise an exception if object is in an error state.
attributes Returns a hash containing the list of model attributes and values.
identity Returns the identity of the object.
Note: This might not always be equal to object.id.
wait_for This method periodically reloads model and then yields to specified block until block returns true or a timeout occurs.
The remainder of this document details the model abstraction. ## List Volume Types To retrieve a list of volume types: service.volume_types This returns a collection of `Fog::Rackspace::BlockStorage::VolumeType` models: , ] > ## List Volumes To retrieve a list of volumes: service.volumes This returns a collection of `Fog::Rackspace::BlockStorage::Volume` models: , ] > ## Get Volume To retrieve an individual volume: service.volume.get "fog-example" This returns a `Fog::Rackspace::BlockStorage::Volume`: ## Create Volume To create a volume: volume = service.volumes.create(:size => 100, :display_name => 'fog-ssd', :volume_type => 'SSD') This will return a `Fog::Rackspace::BlockStorage::Volume`: **Note**: The `:size` parameter is the only required parameter and is in gigabytes. Volumes must be a minimum of 100 GB. ### Additional Parameters The `create` method also supports the following key values:
Key Description
:display_name The name of the volume.
:display_description A description of the volume.
:snapshot_id The optional snapshot from which to create a volume.
:volume_type The type of volume to create. Refer to List Volume Types section for valid types. SATA is the default volume type.
## Attach Volume Please refer to the [Attach Volume](compute_v2.md#attach-volume) section in the [Next Generation Cloud Serversâ„¢ (compute_v2)](compute_v2.md) documentation. ## Detach Volume Please refer to the [Detach Volume](compute_v2.md#detach-volume) section in the [Next Generation Cloud Serversâ„¢ (compute_v2)](compute_v2.md) documentation. ## Delete Volume To delete a volume: volume.destroy **Note**: You cannot delete a volume until all of its dependent snapshots have been deleted. ## List Snapshots To retrieve a list of snapshots: service.snapshots To retrieve a list of snapshots for a given volume: volume.snapshots ## Create Snapshot A snapshot is a point-in-time copy of a volume. Each subsequent snapshot will be the difference between the previous snapshot and the current volume. To create a snapshot of a given volume: volume.create_snapshot :display_name => 'initial-snapshot' **Note**: All writes to the volume should be flushed before creating the snapshot, either by unmounting any file systems on the volume or by detaching the volume. ### Additional Parameters The `create_snapshot` method also supports the following key values:
Key Description
:display_name The name of the snapshot.
:display_description A description of the snapshot.
:force If set to true, snapshot will be taken even if volume is still mounted.
## Delete Snapshot To delete a snapshot: snapshot.destroy ## Examples Example code using Cloud Block Storage can be found [here](https://github.com/fog/fog/tree/master/lib/fog/rackspace/examples). ## Additional Resources * [fog.io](http://fog.io/) * [Fog rdoc](http://rubydoc.info/gems/fog/) * [Fog Github repo](https://github.com/fog/fog) * [Fog Github Issues](https://github.com/fog/fog/issues) * [Excon Github repo](https://github.com/geemus/excon) * [Cloud Block Storage API](http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/index.html) ## Support and Feedback Your feedback is appreciated! If you have specific issues with the **fog** SDK, you should file an [issue via Github](https://github.com/fog/fog/issues). For general feedback and support requests, please visit: https://developer.rackspace.com/support. fog-rackspace-0.1.6/lib/fog/rackspace/docs/compute_v2.md0000644000004100000410000007446513411315054023102 0ustar www-datawww-data#Next Generation Cloud Serversâ„¢ (compute_v2) This document explains how to get started using Next Generation Cloud Servers with Fog. It assumes you have read the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. **Note**: Fog also provides an interface to First Gen Cloud Serversâ„¢ (compute). The compute interface is deprecated and should only be used if you need to interact with our first generation cloud. Fog determines the appropriate interface based on the `:version` parameter. See [Create Service](#create-service) section for more information. ## Starting irb console Start by executing the following command: irb Once `irb` has launched you need to require the Fog library. If using Ruby 1.8.x execute: require 'rubygems' require 'fog' If using Ruby 1.9.x execute: require 'fog' ## Create Service Next, create a connection to the Next Gen Cloud Servers: Using a US-based account: service = Fog::Compute.new({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :version => :v2, # Use Next Gen Cloud Servers :rackspace_region => :ord, # Defaults to :dfw :connection_options => {} # Optional }) Using a UK-based account: service = Fog::Compute.new({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :version => :v2, # Use Next Gen Cloud Servers :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT, :rackspace_region => :lon, :connection_options => {} # Optional }) To learn more about obtaining cloud credentials refer to the [Getting Started with Fog and the Rackspace Open Cloud](getting_started.md) document. By default `Fog::Compute` will authenticate against the US authentication endpoint and connect to the DFW region. You can specify alternative authentication endpoints using the key `:rackspace_auth_url`. Please refer to [Alternate Authentication Endpoints](http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Endpoints-d1e180.html) for a list of alternative Rackspace authentication endpoints. Alternative regions are specified using the key `:rackspace_region `. A list of regions available for Cloud Servers can be found by executing the following: identity_service = Fog::Identity({ :provider => 'Rackspace', # Rackspace Fog provider :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API, # Your Rackspace API key :rackspace_auth_url => Fog::Rackspace::UK_AUTH_ENDPOINT # Not specified for US Cloud }) identity_service.service_catalog.display_service_regions :cloudServersOpenStack Rackspace Private Cloud installations can skip specifying a region and directly specify their custom service endpoints using the key `:rackspace_compute_url`. **Note**: A`Fog::Compute` instance is needed for the desired region. ### Optional Connection Parameters Fog supports passing additional connection parameters to its underlying HTTP library (Excon) using the `:connection_options` parameter.
Key Description
:connect_timeout Connection timeout (default: 60 seconds)
:read_timeout Read timeout for connection (default: 60 seconds)
:write_timeout Write timeout for connection (default: 60 seconds)
:proxy Proxy for HTTP and HTTPS connections
:ssl_ca_path Path to SSL certificate authorities
:ssl_ca_file SSL certificate authority file
:ssl_verify_peer SSL verify peer (default: true)
## Fog Abstractions Fog provides both a **model** and **request** abstraction. The request abstraction provides the most efficient interface and the model abstraction wraps the request abstraction to provide a convenient `ActiveModel` like interface. ### Request Layer The request abstraction maps directly to the [Next Gen Cloud Servers API](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_preface.html). It provides the most efficient interface to the Rackspace Open Cloud. To see a list of requests supported by the service: service.requests This returns: :list_servers, :get_server, :create_server, :update_server, :delete_server, :change_server_password, :reboot_server, :rebuild_server, :resize_server, :confirm_resize_server, :revert_resize_server, :list_images, :get_image, :list_flavors, :get_flavor, :attach_volume, :get_attachment, :list_attachments, :delete_attachment, :get_vnc_console #### Example Request To request a list of flavors: response = service.list_flavors This returns in the following `Excon::Response`: [{"id"=>"2", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/2", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/2", "rel"=>"bookmark"}], "name"=>"512MB Standard Instance"}, {"id"=>"3", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/3", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/3", "rel"=>"bookmark"}], "name"=>"1GB Standard Instance"}, {"id"=>"4", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/4", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/4", "rel"=>"bookmark"}], "name"=>"2GB Standard Instance"}, {"id"=>"5", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/5", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/5", "rel"=>"bookmark"}], "name"=>"4GB Standard Instance"}, {"id"=>"6", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/6", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/6", "rel"=>"bookmark"}], "name"=>"8GB Standard Instance"}, {"id"=>"7", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/7", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/7", "rel"=>"bookmark"}], "name"=>"15GB Standard Instance"}, {"id"=>"8", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/8", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/8", "rel"=>"bookmark"}], "name"=>"30GB Standard Instance"}]}, @headers={"Date"=>"Mon, 21 Jan 2013 16:14:45 GMT", "Content-Length"=>"1697", "Content-Type"=>"application/json", "X-Compute-Request-Id"=>"req-0a1e8532-19b3-4993-8b48-cf2d9efe078c", "Server"=>"Jetty(8.0.y.z-SNAPSHOT)"}, @status=200> To view the status of the response: response.status **Note**: Fog is aware of valid HTTP response statuses for each request type. If an unexpected HTTP response status occurs, Fog will raise an exception. To view response body: response.body This will return: {"flavors"=>[{"id"=>"2", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/2", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/2", "rel"=>"bookmark"}], "name"=>"512MB Standard Instance"}, {"id"=>"3", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/3", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/3", "rel"=>"bookmark"}], "name"=>"1GB Standard Instance"}, {"id"=>"4", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/4", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/4", "rel"=>"bookmark"}], "name"=>"2GB Standard Instance"}, {"id"=>"5", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/5", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/5", "rel"=>"bookmark"}], "name"=>"4GB Standard Instance"}, {"id"=>"6", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/6", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/6", "rel"=>"bookmark"}], "name"=>"8GB Standard Instance"}, {"id"=>"7", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/7", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/7", "rel"=>"bookmark"}], "name"=>"15GB Standard Instance"}, {"id"=>"8", "links"=>[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/flavors/8", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/flavors/8", "rel"=>"bookmark"}], "name"=>"30GB Standard Instance"}]} To learn more about Compute request methods refer to [rdoc](http://rubydoc.info/gems/fog/Fog/Compute/Rackspace/Real). To learn more about Excon refer to [Excon GitHub repo](https://github.com/geemus/excon). ### Model Layer Fog models behave in a manner similar to `ActiveModel`. Models will generally respond to `create`, `save`, `persisted?`, `destroy`, `reload` and `attributes` methods. Additionally, fog will automatically create attribute accessors. Here is a summary of common model methods:
Method Description
create Accepts hash of attributes and creates object.
Note: creation is a non-blocking call and you will be required to wait for a valid state before using resulting object.
save Saves object.
Note: not all objects support updating object.
persisted? Returns true if the object has been persisted.
destroy Destroys object.
Note: this is a non-blocking call and object deletion might not be instantaneous.
reload Updates object with latest state from service.
ready? Returns true if object is in a ready state and able to perform actions. This method will raise an exception if object is in an error state.
attributes Returns a hash containing the list of model attributes and values.
identity Returns the identity of the object.
Note: This might not always be equal to object.id.
wait_for This method periodically reloads model and then yields to specified block until block returns true or a timeout occurs.
The remainder of this document details the model abstraction. ## List Images To retrieve a list of available images: service.images This returns a collection of `Fog::Compute::RackspaceV2::Image` models: "https://ord.servers.api.rackspacecloud.com/v2/772045/images/8a3a9f96-b997-46fd-b7a8-a9e740796ffd", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/images/8a3a9f96-b997-46fd-b7a8-a9e740796ffd", "rel"=>"bookmark"}, {"href"=>"https://ord.images.api.rackspacecloud.com/772045/images/8a3a9f96-b997-46fd-b7a8-a9e740796ffd", "type"=>"application/vnd.openstack.image", "rel"=>"alternate"}] >, "https://ord.servers.api.rackspacecloud.com/v2/772045/images/992ba82c-083b-4eed-9c26-c54473686466", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/images/992ba82c-083b-4eed-9c26-c54473686466", "rel"=>"bookmark"}, {"href"=>"https://ord.images.api.rackspacecloud.com/772045/images/992ba82c-083b-4eed-9c26-c54473686466", "type"=>"application/vnd.openstack.image", "rel"=>"alternate"}] >, … ## Get Image To retrieve individual image: service.images.get "8a3a9f96-b997-46fd-b7a8-a9e740796ffd" This returns an `Fog::Compute::RackspaceV2::Image` instance: "ubuntu", "com.rackspace__1__visible_core"=>"1", "com.rackspace__1__build_rackconnect"=>"1", "auto_disk_config"=>"True", "com.rackspace__1__options"=>"0", "image_type"=>"base", "org.openstack__1__os_version"=>"12.10", "os_version"=>"12.10", "rax_options"=>"0", "com.rackspace__1__visible_rackconnect"=>"1", "org.openstack__1__os_distro"=>"org.ubuntu", "com.rackspace__1__visible_managed"=>"1", "com.rackspace__1__build_core"=>"1", "arch"=>"x86-64", "os_type"=>"linux", "org.openstack__1__architecture"=>"x64", "com.rackspace__1__build_managed"=>"1"}, disk_config="AUTO", links=[{"href"=>"https://ord.servers.api.rackspacecloud.com/v2/772045/images/8a3a9f96-b997-46fd-b7a8-a9e740796ffd", "rel"=>"self"}, {"href"=>"https://ord.servers.api.rackspacecloud.com/772045/images/8a3a9f96-b997-46fd-b7a8-a9e740796ffd", "rel"=>"bookmark"}, {"href"=>"https://ord.images.api.rackspacecloud.com/772045/images/8a3a9f96-b997-46fd-b7a8-a9e740796ffd", "type"=>"application/vnd.openstack.image", "rel"=>"alternate"}] > ## List Flavors To retrieve a list of available flavors: service.flavors This returns a collection of `Fog::Compute::RackspaceV2::Flavor` models: "https://dfw.servers.api.rackspacecloud.com/v2/772045/flavors/2", "rel"=>"self"}, {"href"=>"https://dfw.servers.api.rackspacecloud.com/772045/flavors/2", "rel"=>"bookmark"}] >, "https://dfw.servers.api.rackspacecloud.com/v2/772045/flavors/3", "rel"=>"self"}, {"href"=>"https://dfw.servers.api.rackspacecloud.com/772045/flavors/3", "rel"=>"bookmark"}] >, … ## Get Flavor To retrieve individual flavor: service.flavor.get 2 This returns a `Fog::Compute::RackspaceV2::Flavor` instance: "https://dfw.servers.api.rackspacecloud.com/v2/772045/flavors/2", "rel"=>"self"}, {"href"=>"https://dfw.servers.api.rackspacecloud.com/772045/flavors/2", "rel"=>"bookmark"}] > ## List Servers To retrieve a list of available servers: service.servers This returns a collection of `Fog::Compute::RackspaceV2::Servers` models: "https://dfw.servers.api.rackspacecloud.com/v2/772045/servers/6a273531-8ee4-4bef-ad1a-baca963f8bbb", "rel"=>"self"}, {"href"=>"https://dfw.servers.api.rackspacecloud.com/772045/servers/6a273531-8ee4-4bef-ad1a-baca963f8bbb", "rel"=>"bookmark"}], metadata={}, personality=nil, ipv4_address="198.101.255.186", ipv6_address="2001:4800:780e:0510:0fe1:75e8:ff04:c4a0", disk_config="AUTO", bandwidth=[], addresses={"public"=>[{"version"=>4, "addr"=>"198.101.255.186"}, {"version"=>6, "addr"=>"2001:4800:780e:0510:0fe1:75e8:ff04:c4a0"}], "private"=>[{"version"=>4, "addr"=>"10.180.22.165"}]}, flavor_id="2", image_id="33e21646-43ed-407e-9dbf-7c7873fccd9a" >, … ## Get Server To return an individual server: service.servers.get "6a273531-8ee4-4bef-ad1a-baca963f8bbb" This returns a `Fog::Compute::RackspaceV2::Server` instance: "https://dfw.servers.api.rackspacecloud.com/v2/772045/servers/6a273531-8ee4-4bef-ad1a-baca963f8bbb", "rel"=>"self"}, {"href"=>"https://dfw.servers.api.rackspacecloud.com/772045/servers/6a273531-8ee4-4bef-ad1a-baca963f8bbb", "rel"=>"bookmark"}], metadata={}, personality=nil, ipv4_address="198.101.255.186", ipv6_address="2001:4800:780e:0510:0fe1:75e8:ff04:c4a0", disk_config="AUTO", bandwidth=[], addresses={"public"=>[{"version"=>4, "addr"=>"198.101.255.186"}, {"version"=>6, "addr"=>"2001:4800:780e:0510:0fe1:75e8:ff04:c4a0"}], "private"=>[{"version"=>4, "addr"=>"10.180.22.165"}]}, flavor_id="2", image_id="33e21646-43ed-407e-9dbf-7c7873fccd9a" >, ... ## Create Server If you are interested in creating a server utilizing ssh key authenication, you are recommended to use [bootstrap](#bootstrap) method. To create a server: flavor = service.flavors.first image = service.images.first server = service.servers.create(:name => 'fog-doc', :flavor_id => flavor.id, :image_id => image.id) **Note**: The `:name`, `:flavor_id`, and `image_id` attributes are required for server creation. This will return a `Fog::Compute::RackspaceV2::Server` instance: "https://dfw.servers.api.rackspacecloud.com/v2/772045/servers/8ff308a6-e04a-4602-b991-ed526ab3b6be", "rel"=>"self"}, {"href"=>"https://dfw.servers.api.rackspacecloud.com/772045/servers/8ff308a6-e04a-4602-b991-ed526ab3b6be", "rel"=>"bookmark"}], metadata=nil, personality=nil, ipv4_address=nil, ipv6_address=nil, disk_config="AUTO", bandwidth=nil, addresses=nil, flavor_id=2, image_id="3afe97b2-26dc-49c5-a2cc-a2fc8d80c001" > Notice that your server contains several `nil` attributes. To see the latest status, reload the instance as follows: server.reload You can see that the server is currently 17% built: Fog::Compute::RackspaceV2::Server id="8ff308a6-e04a-4602-b991-ed526ab3b6be", name="fog-server", created="2013-01-18T16:15:41Z", updated="2013-01-18T16:16:14Z", host_id="775837108e45aa3f2a58527c9c3b6160838078e83148f07906c933ca", state="BUILD", progress=17, user_id="296063", tenant_id="772045", links=[{"href"=>"https://dfw.servers.api.rackspacecloud.com/v2/772045/servers/8ff308a6-e04a-4602-b991-ed526ab3b6be", "rel"=>"self"}, {"href"=>"https://dfw.servers.api.rackspacecloud.com/772045/servers/8ff308a6-e04a-4602-b991-ed526ab3b6be", "rel"=>"bookmark"}], metadata={}, personality=nil, ipv4_address="", ipv6_address="", disk_config="AUTO", bandwidth=[], addresses={"public"=>[{"version"=>4, "addr"=>"198.61.209.78"}, {"version"=>6, "addr"=>"2001:4800:7810:0512:0fe1:75e8:ff04:94e4"}], "private"=>[{"version"=>4, "addr"=>"10.181.13.198"}]}, flavor_id="2", image_id="3afe97b2-26dc-49c5-a2cc-a2fc8d80c001" > You will be unable to perform any actions to this server until it reaches an `ACTIVE` state. Since this is true for most server actions, Fog provides the convenience method `wait_for`. Fog can wait for the server to become ready as follows: server.wait_for { ready? } **Note**: The `Fog::Compute::RackspaceV2::Server` instance returned from the create method contains a `password` attribute. The `password` attribute will NOT be present in subsequent retrievals either through `service.servers` or `server.servers.get my_server_id`. ### Additional Parameters The `create` method also supports the following key values:
Key Description
:disk_config The disk configuration value (AUTO or MANUAL). Refer to Next Gen Server API documentation - Disk Configuration Extension.
:metadata Hash containing server metadata.
:personality Array of files to be injected onto the server. Please refer to the Fog personality API documentation for further information.
:config_drive Whether a read-only configuration drive is attached. Refer to Next Gen Server API documentation - Config Drive Extension.
:networks Array of uuids corresponding to cloud networks that should be attached to the server, and defaults to two elements (all-zeros for public internet and all-ones for ServiceNet). Please refer to the Rackspace Create Server API documentation for further information.
## Bootstrap In addition to the `create` method, Fog provides a `bootstrap` method which creates a server and then performs the following actions via ssh: 1. Create `ROOT_USER/.ssh/authorized_keys` file using the ssh key specified in `:public_key_path`. 2. Lock password for root user using `passwd -l root`. 3. Create `ROOT_USER/attributes.json` file with the contents of `server.attributes`. 4. Create `ROOT_USER/metadata.json` file with the contents of `server.metadata`. **Note**: Unlike the `create` method, `bootstrap` is blocking method call. If non-blocking behavior is desired, developers should use the `:personality` parameter on the `create` method. The following example demonstrates bootstraping a server: service.servers.bootstrap :name => 'bootstrap-server', :flavor_id => service.flavors.first.id, :image_id => service.images.find {|img| img.name =~ /Ubuntu/}.id, :public_key_path => '~/.ssh/fog_rsa.pub', :private_key_path => '~/.ssh/fog_rsa' **Note**: The `:name`, `:flavor_id`, `:image_id`, `:public_key_path`, `:private_key_path` are required for the `bootstrap` method. The `bootstrap` method uses the same additional parameters as the `create` method. Refer to the [Additional Parameters](#additional-parameters) section for more information. ## SSH Once a server has been created and set up for ssh key authentication, fog can execute remote commands as follows: result = server.ssh ['pwd'] This will return the following: [#] **Note**: SSH key authentication can be set up using `bootstrap` method or by using the `:personality` attribute on the `:create` method. See [Bootstrap](#bootstrap) or [Create Server](#create-server) for more information. ## Update Server Next Gen Cloud Servers support updating the following attributes `name`, `access_ipv4_address`, and `access_ipv6_address`. To update these attributes: server.name = "batman" server.access_ipv4_address = "10.0.0.1" server.access_ipv6_address = "fdbb:1717:4533:7c89:0:0:0:1" server.save Additional information about server access addresses can be found [here](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Primary_Addresses-d1e2558.html). **Note**: Updating the server name does not change the host name. Names are not guaranteed to be unique. ## Delete Server To delete a server: server.destroy **Note**: The server is not immediately destroyed, but it does occur shortly there after. ## Metadata You can access metadata as an attribute on both `Fog::Compute::RackspaceV2::Server` and `Fog::Compute::RackspaceV2::Metadata::Image`. You can specify metadata during creation of a server or an image. Please refer to [Create Server](#create-server) or [Create Image](#create-image) sections for more information. This example demonstrates how to iterate through a server's metadata: server.metadata.each {|metadatum| puts "#{metadatum.key}: #{metadatum.value}" } You can update and retrieve metadata in a manner similar to a hash: server.metadata["os_type"] server.metadata["installed_ruby"] = "MRI 1.9.3" Metadata also responds to `save` and `reload` as follows: server.metadata.save server.metadata.reload ## Change Admin Password To change the administrator password: server.change_admin_password "superSecure" ## Reboot To perform a soft reboot: server.reboot To perform a hard reboot: server.reboot 'HARD' ## Rebuild Rebuild removes all data on the server and replaces it with the specified image. The id and all IP addresses remain the same. To rebuild a server: image = service.images.first server.rebuild image.id Additionally, the `rebuild` method will take a second parameter containing a hash with the following values:
Key Description
:name Name of Server
:flavorRef Flavor id
:accessIPv4 IPv4 access address
:accessIPv6 IPv6 access address
:metadata Hash containing server metadata
:personality File path and contents. Refer to Next Gen Server API documentation - Server Personality.
:disk_config The disk configuration value (AUTO or MANUAL). Refer to Next Gen Server API documentation - Disk Configuration Extension.
## Resize Resizing a server allows you to change the resources dedicated to the server. To resize a server: flavor_id = service.flavor[2].id server.resize flavor_id #flavor_id should be your desired flavor During the resize process the server will have a state of `RESIZE`. Once a server has completed resizing it will be in a `VERIFY_RESIZE` state. You can use Fog's `wait_for` method to wait for this state as follows: server.wait_for { ready?('VERIFY_RESIZE', ['ACTIVE', 'ERROR']) } In this case, `wait_for` is waiting for the server to become `VERIFY_READY` and will raise an exception if we enter an `ACTIVE` or `ERROR` state. Once a server enters the `VERIFY_RESIZE` we will need to call `confirm_resize` to confirm the server was properly resized or `revert_resize` to rollback to the old size/flavor. **Note:** A server will automatically confirm resize after 24 hours. To confirm resize: server.confirm_resize To revert to previous size/flavor: server.revert_resize ## Create Image To create an image of your server: image = server.create_image "back-image-#{server.name}", :metadata => { :environment => 'development' } You can use the second parameter to specify image metadata. This is an optional parameter. During the imaging process, the image state will be `SAVING`. The image is ready for use when when state `ACTIVE` is reached. Fog can use `wait_for` to wait for an active state as follows: image.wait_for { ready? } ## List Attached Volumes To list Cloud Block Volumes attached to server: server.attachments ## Attach Volume To attach volume using the volume id: server.attach_volume "0e7a706c-340d-48b3-802d-192850387f93" If the volume id is unknown you can look it up using the Cloud Block Storage service. Start by creating a `cbs_service` similar to our Compute Service: cbs_service = Fog::Rackspace::BlockStorage.new({ :rackspace_username => RACKSPACE_USER_NAME, # Your Rackspace Username :rackspace_api_key => RACKSPACE_API # Your Rackspace API key }) volume = cbs_service.volumes.first server.attach_volume volume, "/dev/xvdb" # name of device on server is optional The `attach_volume` method accepts a volume id `String` or `Fog::Rackspace::BlockStorage::Volume` instance. This example also demonstrates passing in the optional device name. Valid device names are `/dev/xvd[a-p]`. ## Detach Volume To detach a volume: server.attachments.first.detach ## Examples Example code using Next Gen Cloud Servers can be found [here](https://github.com/fog/fog/tree/master/lib/fog/rackspace/examples). ## Additional Resources * [fog.io](http://fog.io/) * [Fog rdoc](http://rubydoc.info/gems/fog/) * [Fog Github repo](https://github.com/fog/fog) * [Fog Github Issues](https://github.com/fog/fog/issues) * [Excon Github repo](https://github.com/geemus/excon) * [Next Gen Cloud Servers API](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_preface.html) ## Support and Feedback Your feedback is appreciated! If you have specific issues with the **fog** SDK, you should file an [issue via Github](https://github.com/fog/fog/issues). For general feedback and support requests, please visit: https://developer.rackspace.com/support. fog-rackspace-0.1.6/lib/fog/rackspace/docs/orchestration.md0000644000004100000410000003721613411315054023674 0ustar www-datawww-data# OpenStack Orchestration The mission of the OpenStack Orchestration program is to create a human- and machine-accessible service for managing the entire lifecycle of infrastructure and applications within OpenStack clouds. ## Heat Heat is the main project in the OpenStack Orchestration program. It implements an orchestration engine to launch multiple composite cloud applications based on templates in the form of text files that can be treated like code. A native Heat template format is evolving, but Heat also endeavours to provide compatibility with the AWS CloudFormation template format, so that many existing CloudFormation templates can be launched on OpenStack. Heat provides both an OpenStack-native ReST API and a CloudFormation-compatible Query API. *Why ‘Heat’? It makes the clouds rise!* **How it works** * A Heat template describes the infrastructure for a cloud application in a text file that is readable and writable by humans, and can be checked into version control, diffed, &c. * Infrastructure resources that can be described include: servers, floating ips, volumes, security groups, users, etc. * Heat also provides an autoscaling service that integrates with Ceilometer, so you can include a scaling group as a resource in a template. * Templates can also specify the relationships between resources (e.g. this volume is connected to this server). This enables Heat to call out to the OpenStack APIs to create all of your infrastructure in the correct order to completely launch your application. * Heat manages the whole lifecycle of the application - when you need to change your infrastructure, simply modify the template and use it to update your existing stack. Heat knows how to make the necessary changes. It will delete all of the resources when you are finished with the application, too. * Heat primarily manages infrastructure, but the templates integrate well with software configuration management tools such as Puppet and Chef. The Heat team is working on providing even better integration between infrastructure and software. _Source: [OpenStack Wiki](https://wiki.openstack.org/wiki/Heat)_ # Rackspace Orchestration (Heat) Client [Full Rackspace Orchestration/Heat API Docs](http://docs.rackspace.com/orchestration/api/v1/orchestration-devguide/content/API_Operations_dle7023.html) ## Orchestration Service Get a handle on the Orchestration service: ```ruby irb: service = Fog::Rackspace::Orchestration.new({ :rackspace_username => username, :rackspace_api_key => api_key, :rackspace_region => :iad #:ord, :dfw, :syd }) ===> # ``` Create a new `stack` with a [Heat Template (HOT)](http://docs.openstack.org/developer/heat/template_guide/hot_guide.html). Here we are using Rackspace's HOT for [a single redis server]("https://github.com/rackspace-orchestration-templates/redis-single/blob/master/redis-single.yaml"): ```ruby redis_template = File.read("spec/support/redis_template.yml") ===> "heat_template_version: 2013-05-23\n\ndescription: .... irb: service.stacks.new.save({ :stack_name => "a_redis_stack", :template => redis_template }) ``` We get back a JSON blob filled with info about our new stack: ```ruby ===> {"id"=>"73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "links"=>[{"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"self"}]} ``` Now that we have the `id` of our new stack, we can get a reference to it using the stack's `name` and `id`: ```ruby irb: stack = service.stacks.get("a_redis_stack", "73e0f38a-a9fb-4a4e-8196-2b63039ef31f") ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"self"}], stack_status_reason="Stack CREATE started", stack_name="a_redis_stack", creation_time="2014-11-13T16:21:02Z", updated_time=nil > ``` A stack knows about related `events`: ```ruby irb: stack.events ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f/resources/redis_server_config/events/7b1830a3-5d7b-43b2-bc1b-cffbb25c8b3e", "rel"=>"self"}, {"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f/resources/redis_server_config", "rel"=>"resource"}, {"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"stack"}], logical_resource_id="redis_server_config", resource_status="CREATE_IN_PROGRESS", resource_status_reason="state changed", physical_resource_id=nil >, ``` A stack knows about related `resources`: ```ruby irb: stack.resources ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f/resources/redis_server", "rel"=>"self"}, {"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"stack"}], logical_resource_id="redis_server", resource_status="CREATE_COMPLETE", updated_time="2014-11-13T16:21:04Z", required_by=["redis_server_config"], resource_status_reason="state changed", resource_type="Rackspace::Cloud::Server" >, ``` You can list, limit, sort stacks based on certain keywords: ** Available keywords:** * status * ​name * ​limit * ​marker * ​sort_keys * sort_dir ```ruby irb: stacks = service.stacks.all(sort_key: "stack_name", sort_dir: "asc") ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"self"}], stack_status_reason="Stack CREATE started", stack_name="a_redis_stack", creation_time="2014-11-13T16:21:02Z", updated_time=nil > ] > ``` You can get a stack's `template` ```ruby irb: stack.template ===> #{"status"=>"IN_PROGRESS", "name"=>"a_redis_stack", "stack_user_project_id"=>"TENANT_ID", "environment"=>{"parameters"=>{}, "resource_registry"=>{"resources"=>{}}}, "template"=>{"parameter_groups"=>[{"parameters"=>["flavor", "image"], "label"=>"Server Settings"}, {"parameters"=>["redis_port"], "label"=>"Redis Settings"}, {"parameters"=>["redis_version", "redis_hostname", "kitchen", "chef_version"], "label"=>"rax-dev-params"}], "heat_template_version"=>"2013-05-23", "description"=>"This is a Heat te ``` You can preview a stack: ```ruby irb: service.stacks.preview({ :stack_name => "a_redis_template", :template => redis_template }) ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_template/None", "rel"=>"self"}], stack_status_reason=nil, stack_name="a_redis_template", creation_time="2014-11-13T16:33:50Z", updated_time=nil > ``` Of course, you can just delete a stack. This deletes associated `resources` (as opposed to `abandon`): ```ruby irb: stack.delete ===> #"", :headers=>{"Server"=>"nginx/1.2.1", "Date"=>"Thu, 13 Nov 2014 16:28:38 GMT", "Content-Type"=>"text/html; charset=UTF-8", "Connection"=>"keep-alive", "Via"=>"1.0 Repose (Repose/6.0.2)"}, :status=>204, :reason_phrase=>"No Content", :remote_ip=>"23.253.147.138", :local_port=>54721, :local_address=>"192.168.1.65"}, @body="", @headers={"Server"=>"nginx/1.2.1", "Date"=>"Thu, 13 Nov 2014 16:28:38 GMT", "Content-Type"=>"text/html; charset=UTF-8", "Connection"=>"keep-alive", "Via"=>"1.0 Repose (Repose/6.0.2)"}, @status=204, @remote_ip="23.253.147.138", @local_port=54721, @local_address="192.168.1.65"> ``` Reload any object by calling `reload` on it: ```ruby irb: stacks.reload ===> ``` You can get build information: ```ruby irb: service.stacks.build_info ===> {"engine"=>{"revision"=>"2014.k1-20141027-1178"}, "fusion-api"=>{"revision"=>"j1-20140915-10d9ee4-98"}, "api"=>{"revision"=>"2014.k1-20141027-1178"}} ``` ## Events `Events` are indexable and can be scoped by `stack`: ```ruby irb: event = stack.events.first ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f/resources/redis_server_config/events/7b1830a3-5d7b-43b2-bc1b-cffbb25c8b3e", "rel"=>"self"}, {"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f/resources/redis_server_config", "rel"=>"resource"}, {"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"stack"}], logical_resource_id="redis_server_config", resource_status="CREATE_IN_PROGRESS", resource_status_reason="state changed", physical_resource_id=nil > ``` `Events` can be sorted, limited, etc by passing an hash like so: `service.events.all(stack, limit: 1)` ** Available keys: ** * resource_action * resource_status * resource_name * ​resource_type * ​limit * ​marker * sort_keys * ​sort_dir They are getable: ```ruby irb: event = service.events.get(stack, resource, event_id) ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f/resources/redis_server_config/events/7b1830a3-5d7b-43b2-bc1b-cffbb25c8b3e", "rel"=>"self"}, {"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f/resources/redis_server_config", "rel"=>"resource"}, {"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"stack"}], logical_resource_id="redis_server_config", resource_status="CREATE_IN_PROGRESS", resource_status_reason="state changed", physical_resource_id=nil > ``` An `event` knows about its associated `stack`: ```ruby irb: event.stack ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"self"}], stack_status_reason="Stack CREATE completed successfully", stack_name="a_redis_stack", creation_time="2014-11-13T16:21:02Z", updated_time=nil > ``` You can list, limit, sort events based on certain keywords: ```ruby irb: events = stack.events.all(stack, sort_key: "resource_name", sort_dir: "desc", limit: 3) ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f/resources/redis_server_config", "rel"=>"self"}, {"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"stack"}], logical_resource_id="redis_server_config", resource_status="CREATE_COMPLETE", updated_time="2014-11-13T16:21:45Z", required_by=[], resource_status_reason="state changed", resource_type="OS::Heat::ChefSolo" > ``` ## Resource `resources` are indexable: ```ruby irb: service.resources.all(stack, {nested_depth: 1}) ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/ee648a3b-14a3-4df8-aa58-620a9d67e3e5/resources/redis_server", "rel"=>"self"}, {"href"=>"https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/ee648a3b-14a3-4df8-aa58-620a9d67e3e5", "rel"=>"stack"}], logical_resource_id="redis_server", resource_status="CREATE_COMPLETE", updated_time="2014-11-13T16:32:30Z", required_by=["redis_server_config"], resource_status_reason="state changed", resource_type="Rackspace::Cloud::Server" >, ... ``` A `resource` knows about its associated `stack`: ```ruby irb: resource.stack ===> "https://iad.orchestration.api.rackspacecloud.com/v1/TENANT_ID/stacks/a_redis_stack/73e0f38a-a9fb-4a4e-8196-2b63039ef31f", "rel"=>"self"}], stack_status_reason="Stack CREATE completed successfully", stack_name="a_redis_stack", creation_time="2014-11-13T16:21:02Z", updated_time=nil > ``` Resource metadata is visible: ```ruby irb: resource.metadata ===> {} ``` A `resource's` template is visible (if one exists) ```ruby irb: resource.template ===> nil ``` ## Validation You can validate a Heat template (HOT) before using it: ```ruby irb: service.templates.validate({:template => redis_template}) ===> port.attributes} request( :method => 'POST', :body => Fog::JSON.encode(data), :path => "ports", :expects => 201 ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/list_networks.rb0000644000004100000410000000032213411315054027427 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def list_networks request(:method => 'GET', :path => 'networks', :expects => 200) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/delete_network.rb0000644000004100000410000000034013411315054027533 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def delete_network(id) request(:method => 'DELETE', :path => "networks/#{id}", :expects => 204) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/update_subnet.rb0000644000004100000410000000074413411315054027372 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def update_subnet(subnet) data = { :subnet => { :name => subnet.name, :gateway_ip => subnet.gateway_ip } } request( :method => 'PUT', :body => Fog::JSON.encode(data), :path => "subnets/#{subnet.id}", :expects => 200 ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/create_security_group_rule.rb0000644000004100000410000000050513411315054032160 0ustar www-datawww-dataclass Fog::Rackspace::NetworkingV2::Real def create_security_group_rule(security_group_rule) data = {:security_group_rule => security_group_rule.attributes} request( :method => 'POST', :body => Fog::JSON.encode(data), :path => "security-group-rules", :expects => 201 ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/create_network.rb0000644000004100000410000000056413411315054027544 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def create_network(network) data = {:network => network.attributes} request( :method => 'POST', :body => Fog::JSON.encode(data), :path => "networks", :expects => 201 ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/update_security_group.rb0000644000004100000410000000050513411315054031150 0ustar www-datawww-dataclass Fog::Rackspace::NetworkingV2::Real def update_security_group(security_group) data = {:security_group => {:name => security_group.name}} request( :method => 'PUT', :body => Fog::JSON.encode(data), :path => "security-groups/#{security_group.id}", :expects => 200 ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/list_security_group_rules.rb0000644000004100000410000000024313411315054032052 0ustar www-datawww-dataclass Fog::Rackspace::NetworkingV2::Real def list_security_group_rules request(:method => 'GET', :path => 'security-group-rules', :expects => 200) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/delete_security_group_rule.rb0000644000004100000410000000026113411315054032156 0ustar www-datawww-dataclass Fog::Rackspace::NetworkingV2::Real def delete_security_group_rule(id) request(:method => 'DELETE', :path => "security-group-rules/#{id}", :expects => 204) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/show_security_group.rb0000644000004100000410000000024213411315054030644 0ustar www-datawww-dataclass Fog::Rackspace::NetworkingV2::Real def show_security_group(id) request(:method => 'GET', :path => "security-groups/#{id}", :expects => 200) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/show_port.rb0000644000004100000410000000032513411315054026547 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def show_port(id) request(:method => 'GET', :path => "ports/#{id}", :expects => 200) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/list_subnets.rb0000644000004100000410000000032013411315054027234 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def list_subnets request(:method => 'GET', :path => 'subnets', :expects => 200) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/show_subnet.rb0000644000004100000410000000033113411315054027060 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def show_subnet(id) request(:method => 'GET', :path => "subnets/#{id}", :expects => 200) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/delete_subnet.rb0000644000004100000410000000033613411315054027347 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def delete_subnet(id) request(:method => 'DELETE', :path => "subnets/#{id}", :expects => 204) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/delete_port.rb0000644000004100000410000000033213411315054027027 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def delete_port(id) request(:method => 'DELETE', :path => "ports/#{id}", :expects => 204) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/show_security_group_rule.rb0000644000004100000410000000025413411315054031676 0ustar www-datawww-dataclass Fog::Rackspace::NetworkingV2::Real def show_security_group_rule(id) request(:method => 'GET', :path => "security-group-rules/#{id}", :expects => 200) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/list_ports.rb0000644000004100000410000000031413411315054026723 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def list_ports request(:method => 'GET', :path => 'ports', :expects => 200) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/update_port.rb0000644000004100000410000000056413411315054027056 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def update_port(port) data = {:port => {:name => port.name}} request( :method => 'PUT', :body => Fog::JSON.encode(data), :path => "ports/#{port.id}", :expects => 200 ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/show_network.rb0000644000004100000410000000033313411315054027253 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def show_network(id) request(:method => 'GET', :path => "networks/#{id}", :expects => 200) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/create_subnet.rb0000644000004100000410000000055713411315054027355 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def create_subnet(subnet) data = {:subnet => subnet.attributes} request( :method => 'POST', :body => Fog::JSON.encode(data), :path => "subnets", :expects => 201 ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/update_network.rb0000644000004100000410000000060613411315054027560 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Real def update_network(network) data = {:network => {:name => network.name}} request( :method => 'PUT', :body => Fog::JSON.encode(data), :path => "networks/#{network.id}", :expects => 200 ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/list_security_groups.rb0000644000004100000410000000023113411315054031020 0ustar www-datawww-dataclass Fog::Rackspace::NetworkingV2::Real def list_security_groups request(:method => 'GET', :path => 'security-groups', :expects => 200) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/delete_security_group.rb0000644000004100000410000000024713411315054031133 0ustar www-datawww-dataclass Fog::Rackspace::NetworkingV2::Real def delete_security_group(id) request(:method => 'DELETE', :path => "security-groups/#{id}", :expects => 204) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking_v2/create_security_group.rb0000644000004100000410000000045413411315054031134 0ustar www-datawww-dataclass Fog::Rackspace::NetworkingV2::Real def create_security_group(security_group) data = {:security_group => security_group.attributes} request( :method => 'POST', :body => Fog::JSON.encode(data), :path => "security-groups", :expects => 201 ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/0000755000004100000410000000000013411315054023231 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/get_user_by_id.rb0000644000004100000410000000042713411315054026544 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def get_user_by_id(user_id) request( :expects => [200, 203], :method => 'GET', :path => "users/#{user_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/list_users.rb0000644000004100000410000000071213411315054025752 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def list_users() response = request( :expects => [200, 203], :method => 'GET', :path => 'users' ) unless response.body['users'].is_a?(Array) response.body['users'] = [response.body['user']] response.body.delete('user') end response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/list_user_roles.rb0000644000004100000410000000074713411315054027003 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def list_user_roles(user_id) response = request( :expects => [200, 203], :method => 'GET', :path => "users/#{user_id}/roles" ) unless response.body['roles'].is_a?(Array) response.body['roles'] = [response.body['role']] response.body.delete('role') end response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/list_credentials.rb0000644000004100000410000000101713411315054027105 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def list_credentials(user_id) response = request( :expects => [200, 203], :method => 'GET', :path => "users/#{user_id}/OS-KSADM/credentials" ) unless response.body['credentials'].is_a?(Array) response.body['credentials'] = [response.body['credential']] response.body.delete('credential') end response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/create_token.rb0000644000004100000410000002224513411315054026226 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def create_token(username, api_key) data = { 'auth' => { 'RAX-KSKEY:apiKeyCredentials' => { 'username' => username, 'apiKey' => api_key } } } request_without_retry( :body => Fog::JSON.encode(data), :expects => [200, 203], :method => 'POST', :path => 'tokens' ) end end class Mock def create_token(username, api_key) unless username == 'baduser' || api_key == 'bad_key' compute_tenant = Fog::Mock.random_numbers(6) object_tenant = generate_object_tenant response = Excon::Response.new response.status = 200 response.body = { "access" => { "token"=> { "id" => Fog::Mock.random_hex(32), "expires" => (Time.now.utc + 86400).strftime("%Y-%m-%dT%H:%M:%S.%LZ"), "tenant" => { "id" => compute_tenant, "name" => compute_tenant } }, "user" => { "id" => Fog::Mock.random_numbers(6), "name" => username, "roles" => [ { "id" => Fog::Mock.random_numbers(1), "description" => "Fake Role for an object store", "name" => "object-store:default" }, { "id" => Fog::Mock.random_numbers(1), "description" => "Fake Role for a compute cluster", "name" => "compute:default" } ] }, "serviceCatalog" => build_service_catalog(compute_tenant, object_tenant), } } response else response = Excon::Response.new response.status = 401 response.body = { "unauthorized" => { "code" => 401, "message" => "Username or API key is invalid." } } raise Excon::Errors::Unauthorized.new('Unauthorized', nil, response) end end # Generate a realistic-looking object tenant ID. def generate_object_tenant uuid = [8, 4, 4, 4, 12].map { |n| Fog::Mock.random_hex(n) }.join('_') "FogMockFS_#{uuid}" end # Construct a full, fake service catalog. # # @param compute_tenant [String] Tenant ID to be used in entries for # compute-based services (most of them). # @param object_tenant [String] Tenant ID to be used in object-store # related entries. # # @return [Hash] A fully-populated, valid service catalog. def build_service_catalog(compute_tenant, object_tenant) [ service_catalog_entry("cloudFilesCDN", "rax:object-cdn", object_tenant, :public_url => lambda do |r| "https://cdn#{Fog::Mock.random_numbers(1)}.clouddrive.com/v1/#{object_tenant}" end), service_catalog_entry("cloudFiles", "object-store", object_tenant, :internal_url_snet => true, :public_url => lambda do |r| "https://storage101.#{r}#{Fog::Mock.random_numbers(1)}.clouddrive.com/v1/#{object_tenant}" end), service_catalog_entry("rackCDN", "rax:cdn", compute_tenant, :rackspace_api_version => '1.0'), service_catalog_entry("cloudMonitoring", "rax:monitor", compute_tenant, :single_endpoint => true, :rackspace_api_name => 'monitoring'), service_catalog_entry("cloudServersOpenStack", "compute", compute_tenant, :version_base_url => lambda { |r| "https://#{r}.servers.api.rackspacecloud.com" }, :version_id => "2"), service_catalog_entry("cloudBlockStorage", "volume", compute_tenant, :rackspace_api_name => 'blockstorage', :rackspace_api_version => '1'), service_catalog_entry("cloudDatabases", "rax:database", compute_tenant, :rackspace_api_name => 'databases'), service_catalog_entry("cloudLoadBalancers", "rax:load-balander", compute_tenant, :rackspace_api_name => 'loadbalancers'), service_catalog_entry("cloudDNS", "rax:dns", compute_tenant, :single_endpoint => true, :rackspace_api_name => 'dns'), service_catalog_entry("cloudOrchestration", "orchestration", compute_tenant, :rackspace_api_name => 'orchestration', :rackspace_api_version => '1'), service_catalog_entry("cloudNetworks", "network", compute_tenant, :rackspace_api_name => 'networks', :rackspace_api_version => '2.0'), service_catalog_entry("cloudQueues", "rax:queues", compute_tenant, :internal_url_snet => true, :rackspace_api_name => 'queues', :rackspace_api_version => '1'), service_catalog_entry("cloudBackup", "rax:backup", compute_tenant, :rackspace_api_name => 'backup'), service_catalog_entry("cloudImages", "image", compute_tenant, :rackspace_api_name => 'images', :rackspace_api_version => '2'), service_catalog_entry("autoscale", "rax:autoscale", compute_tenant, :rackspace_api_name => 'autoscale'), service_catalog_entry("cloudServers", "compute", compute_tenant, :single_endpoint => true, :version_base_url => lambda { |r| "https://servers.api.rackspacecloud.com" }, :version_id => '1.0') ] end # Generate an individual service catalog entry for a fake service # catalog. Understands common patterns used within Rackspace # service catalogs. # # @param name [String] The required "name" attribute of the # service catalog entry. # @param type [String] The required "type" attribute. # @param tenant_id [String] Tenant ID to be used for this service. # # @param options [Hash] Control the contents of the generated entry. # @option options [Proc] :public_url Callable invoked with each region # (or `nil`) to generate a `publicURL` for that region. # @option options [Boolean] :single_endpoint If `true`, only a single # endpoint entry will be generated, rather than an endpoint for each # region. # @option options [Boolean] :internal_url_snet If `true`, an internalURL # entry will be generated by prepending "snet-" to the publicURL. # @option options [String] :rackspace_api_name If specified, will generate # publicURL as a Rackspace API URL. # @option options [String] :rackspace_api_version (`"1.0"`) Specify the # version of the Rackspace API URL. # # @return [Hash] A valid service catalog entry. def service_catalog_entry(name, type, tenant_id, options) if options[:rackspace_api_name] api_name = options[:rackspace_api_name] api_version = options[:rackspace_api_version] || "1.0" options[:public_url] = lambda do |r| prefix = r ? "#{r}." : "" "https://#{prefix}#{api_name}.api.rackspacecloud.com/v#{api_version}/#{tenant_id}" end end entry = { "name" => name, "type" => type } if options[:single_endpoint] entry["endpoints"] = [endpoint_entry(tenant_id, nil, options)] else entry["endpoints"] = %w{ORD DFW SYD IAD HKG}.map do |region| endpoint_entry(tenant_id, region, options) end end entry end # Helper method that generates a single endpoint hash within a service # catalog entry. # # @param tenant_id [String] The tenant ID used for this endpoint. # @param region [String, nil] The region to include in this endpoint, if any. # @param options [Hash] Options inherited from {#service_catalog_entry}. # # @return [Hash] A well-formed endpoint hash. def endpoint_entry(tenant_id, region, options) endpoint = { "tenantId" => tenant_id } endpoint["region"] = region if region r = region.downcase if region endpoint["publicURL"] = options[:public_url].call(r) if options[:public_url] if options[:internal_url_snet] endpoint["internalURL"] = endpoint["publicURL"].gsub(%r{^https://}, "https://snet-") end endpoint["internalURL"] = options[:internal_url].call(r) if options[:internal_url] if options[:version_base_url] && options[:version_id] base = options[:version_base_url].call(r) version = options[:version_id] endpoint["publicURL"] = "#{base}/v#{version}/#{tenant_id}" endpoint["versionInfo"] = "#{base}/v#{version}" endpoint["versionList"] = base endpoint["versionId"] = version end endpoint end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/delete_user.rb0000644000004100000410000000042213411315054026054 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def delete_user(user_id) request( :expects => [204], :method => 'DELETE', :path => "users/#{user_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/update_user.rb0000644000004100000410000000103113411315054026071 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def update_user(user_id, username, email, enabled, options = {}) data = { 'user' => { 'username' => username, 'email' => email, 'enabled' => enabled } } request( :body => Fog::JSON.encode(data), :expects => [200, 203], :method => 'POST', :path => "users/#{user_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/list_tenants.rb0000644000004100000410000000210113411315054026257 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def list_tenants() response = request( :expects => [200, 203], :method => 'GET', :path => 'tenants' ) unless response.body['tenants'].is_a?(Array) response.body['tenants'] = [response.body['tenant']] response.body.delete('tenant') end response end end class Mock def list_tenants response = Excon::Response.new response.status = [200, 203][rand(1)] response.body = { "tenants" => [ { "id" => Fog::Mock.random_numbers(6), "name" => "Enabled tenant", "enabled" => true }, { "id" => Fog::Mock.random_numbers(6), "name" => "Disabled tenant", "enabled" => false }, ], "tenants_links" => [] } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/create_user.rb0000644000004100000410000000114013411315054026053 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def create_user(username, email, enabled, options = {}) data = { 'user' => { 'username' => username, 'email' => email, 'enabled' => enabled } } data['user']['OS-KSADM:password'] = options[:password] unless options[:password].nil? request( :body => Fog::JSON.encode(data), :expects => [201], :method => 'POST', :path => 'users' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/identity/get_user_by_name.rb0000644000004100000410000000044013411315054027063 0ustar www-datawww-datamodule Fog module Rackspace class Identity class Real def get_user_by_name(username) request( :expects => [200, 203], :method => 'GET', :path => "users?name=#{username}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn/0000755000004100000410000000000013411315054022144 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn/head_container.rb0000644000004100000410000000447713411315054025450 0ustar www-datawww-datamodule Fog module CDN class Rackspace class Real # List cdn properties for a container # # ==== Parameters # * container<~String> - Name of container to retrieve info for # # ==== Returns # * response<~Excon::Response>: # * headers<~Hash>: # * 'X-CDN-Enabled'<~Boolean> - cdn status for container # * 'X-CDN-URI'<~String> - cdn url for this container # * 'X-TTL'<~String> - integer seconds before data expires, defaults to 86400 (1 day) # * 'X-Log-Retention'<~Boolean> - ? # * 'X-User-Agent-ACL'<~String> - ? # * 'X-Referrer-ACL'<~String> - ? # @return [Excon::Response] response # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def head_container(container) response = request( :expects => 204, :method => 'HEAD', :path => container, :query => {'format' => 'json'} ) response end end class Mock def head_container(container) raise Fog::Storage::Rackspace::NotFound.new "#{container} not found" unless container == 'fogcontainertests' response = Excon::Response.new response.status = 204 response.headers = { "X-Cdn-Uri"=>"http://e4bbc22477d80eaf22bd-ca4e4e61e477bbd430e1f5b9dc9a19f5.r53.cf1.rackcdn.com", "X-Cdn-Ios-Uri"=>"http://3c10ef49037f74416445-ca4e4e61e477bbd430e1f5b9dc9a19f5.iosr.cf1.rackcdn.com", "X-Cdn-Ssl-Uri"=>"https://b722b8ee248259c37901-ca4e4e61e477bbd430e1f5b9dc9a19f5.ssl.cf1.rackcdn.com", "X-Log-Retention"=>"False", "X-Cdn-Enabled"=>"True", "Content-Length"=>"0", "Date"=>"Fri, 01 Feb 2013 21:25:57 GMT", "X-Cdn-Streaming-Uri"=>"http://b82027c64cb4dd03670a-ca4e4e61e477bbd430e1f5b9dc9a19f5.r53.stream.cf1.rackcdn.com", "X-Ttl"=>"259200", "X-Trans-Id"=>"txca40ffd0412943608bb3e9656c8b81ef" } response.body = "" response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn/post_container.rb0000644000004100000410000000443313411315054025524 0ustar www-datawww-datamodule Fog module CDN class Rackspace class Real # modify CDN properties for a container # # ==== Parameters # * name<~String> - Name for container, should be < 256 bytes and must not contain '/' # * options<~Hash>: # * 'X-CDN-Enabled'<~Boolean> - cdn status for container # * 'X-CDN-URI'<~String> - cdn url for this container # * 'X-TTL'<~String> - integer seconds before data expires, defaults to 86400 (1 day), in 3600..259200 # * 'X-Log-Retention'<~Boolean> - ? # * 'X-User-Agent-ACL'<~String> - ? # * 'X-Referrer-ACL'<~String> - ? # @return [Excon::Response] response # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def post_container(name, options = {}) response = request( :expects => [201, 202], :headers => options, :method => 'POST', :path => CGI.escape(name) ) response end end class Mock def post_container(name, options = {}) raise Fog::Storage::Rackspace::NotFound.new "#{name} not found" unless name == 'fogcontainertests' response = Excon::Response.new response.status = 202 response.headers = { "X-Cdn-Uri"=>"http://e4bbc22477d80eaf22bd-ca4e4e61e477bbd430e1f5b9dc9a19f5.r53.cf1.rackcdn.com", "X-Cdn-Ios-Uri"=>"http://3c10ef49037f74416445-ca4e4e61e477bbd430e1f5b9dc9a19f5.iosr.cf1.rackcdn.com", "X-Cdn-Ssl-Uri"=>"https://b722b8ee248259c37901-ca4e4e61e477bbd430e1f5b9dc9a19f5.ssl.cf1.rackcdn.com", "Content-Length"=>"58", "Date"=>"Fri, 01 Feb 2013 21:31:30 GMT", "Content-Type"=>"text/plain; charset=UTF-8", "X-Cdn-Streaming-Uri"=>"http://b82027c64cb4dd03670a-ca4e4e61e477bbd430e1f5b9dc9a19f5.r53.stream.cf1.rackcdn.com", "X-Trans-Id"=>"tx4a3206e63dfc446bb5b60e34a62f749d" } response.body = "202 Accepted\n\nThe request is accepted for processing.\n\n " response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn/put_container.rb0000644000004100000410000000420413411315054025343 0ustar www-datawww-datamodule Fog module CDN class Rackspace class Real # enable CDN for a container # # ==== Parameters # * name<~String> - Name for container, should be < 256 bytes and must not contain '/' # * options<~Hash>: # * 'X-CDN-Enabled'<~Boolean> - cdn status for container # * 'X-CDN-URI'<~String> - cdn url for this container # * 'X-TTL'<~String> - integer seconds before data expires, defaults to 86400 (1 day), in 3600..259200 # * 'X-Log-Retention'<~Boolean> - ? # * 'X-User-Agent-ACL'<~String> - ? # * 'X-Referrer-ACL'<~String> - ? # @return [Excon::Response] response # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def put_container(name, options = {}) response = request( :expects => [201, 202], :headers => options, :method => 'PUT', :path => CGI.escape(name) ) response end end class Mock def put_container(name, options = {}) response = Excon::Response.new response.status = 201 response.headers = { "X-Cdn-Uri"=>"http://e4bbc22477d80eaf22bd-ca4e4e61e477bbd430e1f5b9dc9a19f5.r53.cf1.rackcdn.com", "X-Cdn-Ios-Uri"=>"http://3c10ef49037f74416445-ca4e4e61e477bbd430e1f5b9dc9a19f5.iosr.cf1.rackcdn.com", "X-Cdn-Ssl-Uri"=>"https://b722b8ee248259c37901-ca4e4e61e477bbd430e1f5b9dc9a19f5.ssl.cf1.rackcdn.com", "Content-Length"=>"18", "Date"=>"Fri, 01 Feb 2013 21:21:45 GMT", "Content-Type"=>"text/plain; charset=UTF-8", "X-Cdn-Streaming-Uri"=>"http://b82027c64cb4dd03670a-ca4e4e61e477bbd430e1f5b9dc9a19f5.r53.stream.cf1.rackcdn.com", "X-Trans-Id"=>"tx1b41ec63189f4862baa65e0c08711772" } response.body = "201 Created\n\n\n\n " response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn/delete_object.rb0000644000004100000410000000232113411315054025257 0ustar www-datawww-datamodule Fog module CDN class Rackspace class Real # Delete an existing object # # ==== Parameters # * container<~String> - Name of container to delete # * object<~String> - Name of object to delete # @return [Excon::Response] response # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def delete_object(container, object) request( :expects => 204, :method => 'DELETE', :path => "#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object)}" ) end end class Mock def delete_object(container, object) response = Excon::Response.new response.status = 204 response.headers = { "Content-Length"=>"0", "Date"=>"Fri, 01 Feb 2013 21:34:33 GMT", "X-Trans-Id"=>"tx860f26bd76284a849384c0a467767b57" } response.body = "" response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn/get_containers.rb0000644000004100000410000000545413411315054025505 0ustar www-datawww-datamodule Fog module CDN class Rackspace class Real # List existing cdn-enabled storage containers # # ==== Parameters # * options<~Hash>: # * 'enabled_only'<~Boolean> - Set to true to limit results to cdn enabled containers # * 'limit'<~Integer> - Upper limit to number of results returned # * 'marker'<~String> - Only return objects with name greater than this value # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * container<~String>: Name of container # @return [Excon::Response] response # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def get_containers(options = {}) response = request( :expects => [200, 204], :method => 'GET', :path => '', :query => {'format' => 'json'}.merge!(options) ) response end end class Mock def get_containers(options = {}) response = Excon::Response.new response.status = 200 response.headers = { "Content-Length"=>"4402", "Date"=>"Fri, 01 Feb 2013 21:16:54 GMT", "Content-Type"=>"application/json", "X-Trans-Id"=>"tx6c79ea47300941c49f2291b4d47d4ef5" } response.body = [ { "log_retention"=>false, "cdn_ios_uri"=>"http://a590286a323fec6aed22-d1e9259b2132e81da48ed3e1e802ef22.iosr.cf1.rackcdn.com", "ttl"=>3600, "cdn_enabled"=>true, "cdn_streaming_uri"=>"http://168e307d41afe64f1a62-d1e9259b2132e81da48ed3e1e802ef22.r2.stream.cf1.rackcdn.com", "name"=>"brown", "cdn_uri"=>"http://6e8f4bf5125c9c2e4e3a-d1e9259b2132e81da48ed3e1e802ef22.r2.cf1.rackcdn.com", "cdn_ssl_uri"=>"https://f83cb7d39e0b9ff9581b-d1e9259b2132e81da48ed3e1e802ef22.ssl.cf1.rackcdn.com" }, { "log_retention"=>false, "cdn_ios_uri"=>"http://b141f80caedd02158f10-cf33674d895dc8b8e6e5207fdbd5cae4.iosr.cf1.rackcdn.com", "ttl"=>5000, "cdn_enabled"=>false, "cdn_streaming_uri"=>"http://ea5feee96b8087a3d5e5-cf33674d895dc8b8e6e5207fdbd5cae4.r72.stream.cf1.rackcdn.com", "name"=>"fogcontainertests", "cdn_uri"=>"http://0115a9de56617a5d5473-cf33674d895dc8b8e6e5207fdbd5cae4.r72.cf1.rackcdn.com", "cdn_ssl_uri"=>"https://a5df8bd8a418ca88061e-cf33674d895dc8b8e6e5207fdbd5cae4.ssl.cf1.rackcdn.com" } ] response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/0000755000004100000410000000000013411315054022164 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/list_domains.rb0000644000004100000410000000061013411315054025173 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def list_domains(options={}) path = 'domains' unless options.empty? path += "?#{array_to_query_string(options)}" end request( :expects => 200, :method => 'GET', :path => path ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/remove_records.rb0000644000004100000410000000070313411315054025527 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def remove_records(domain_id, record_ids) validate_path_fragment :domain_id, domain_id path = "domains/#{domain_id}/records?" + record_ids.map { |record_id| "id=#{record_id}" }.join('&') request( :expects => [202, 204], :method => 'DELETE', :path => path ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/list_domain_details.rb0000644000004100000410000000136713411315054026527 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def list_domain_details(domain_id, options={}) validate_path_fragment :domain_id, domain_id path = "domains/#{domain_id}" query_data = {} if options.key? :show_records query_data['showRecords'] = options[:show_records] end if options.key? :show_subdomains query_data['showSubdomains'] = options[:show_subdomains] end if !query_data.empty? path = path + '?' + array_to_query_string(query_data) end request( :expects => 200, :method => 'GET', :path => path ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/callback.rb0000644000004100000410000000062413411315054024247 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def callback(job_id, show_details=true) validate_path_fragment :job_id, job_id request( :expects => [200, 202, 204], :method => 'GET', :path => "status/#{job_id}", :query => "showDetails=#{show_details}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/remove_record.rb0000644000004100000410000000070713411315054025350 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def remove_record(domain_id, record_id) validate_path_fragment :domain_id, domain_id validate_path_fragment :record_id, record_id path = "domains/#{domain_id}/records/#{record_id}" request( :expects => [202, 204], :method => 'DELETE', :path => path ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/remove_domains.rb0000644000004100000410000000120713411315054025520 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def remove_domains(domain_ids, options={}) path = "domains?" + domain_ids.map { |domain_id| "id=#{domain_id}" }.join('&') query_data = {} if options.key? :delete_subdomains query_data['deleteSubdomains'] = options[:delete_subdomains] end if !query_data.empty? path = path + '&' + array_to_query_string(query_data) end request( :expects => [202, 204], :method => 'DELETE', :path => path ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/list_records.rb0000644000004100000410000000074313411315054025211 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def list_records(domain_id, options={}) validate_path_fragment :domain_id, domain_id path = "domains/#{domain_id}/records" if !options.empty? path = path + '?' + array_to_query_string(options) end request( :expects => 200, :method => 'GET', :path => path ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/create_domains.rb0000644000004100000410000000232713411315054025472 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def create_domains(domains) data = { 'domains' => [] } domains.each do |domain| domain_data = { 'name' => domain[:name], 'emailAddress' => domain[:email] } if domain.key? :records domain_data['recordsList'] = { 'records' => domain[:records].map do |record| record_data = { 'ttl' => record[:ttl], 'data' => record[:data], 'name' => record[:name], 'type' => record[:type], } if record.key? :priority record_data.merge!({'priority' => record[:priority]}) else record_data end end } end data['domains'] << domain_data end request( :expects => 202, :method => 'POST', :path => 'domains', :body => Fog::JSON.encode(data) ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/modify_domain.rb0000644000004100000410000000142213411315054025326 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def modify_domain(domain_id, options={}) validate_path_fragment :domain_id, domain_id path = "domains/#{domain_id}" data = {} if options.key? :ttl data['ttl'] = options[:ttl] end if options.key? :comment data['comment'] = options[:comment] end if options.key? :email data['emailAddress'] = options[:email] end if data.empty? return end request( :expects => [202, 204], :method => 'PUT', :path => path, :body => Fog::JSON.encode(data) ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/modify_record.rb0000644000004100000410000000152613411315054025342 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def modify_record(domain_id, record_id, options={}) validate_path_fragment :domain_id, domain_id validate_path_fragment :record_id, record_id path = "domains/#{domain_id}/records/#{record_id}" data = {} if options.key? :ttl data['ttl'] = options[:ttl] end if options.key? :name data['name'] = options[:name] end if options.key? :data data['data'] = options[:data] end if data.empty? return end request( :expects => [202, 204], :method => 'PUT', :path => path, :body => Fog::JSON.encode(data) ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/remove_domain.rb0000644000004100000410000000122113411315054025331 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def remove_domain(domain_id, options={}) validate_path_fragment :domain_id, domain_id path = "domains/#{domain_id}" query_data = {} if options.key? :delete_subdomains query_data['deleteSubdomains'] = options[:delete_subdomains].to_s end if !query_data.empty? path = path + '?' + array_to_query_string(query_data) end request( :expects => [202, 204], :method => 'DELETE', :path => path ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/list_record_details.rb0000644000004100000410000000070313411315054026527 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def list_record_details(domain_id, record_id) validate_path_fragment :domain_id, domain_id validate_path_fragment :record_id, record_id path = "domains/#{domain_id}/records/#{record_id}" request( :expects => 200, :method => 'GET', :path => path ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/list_subdomains.rb0000644000004100000410000000075113411315054025713 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def list_subdomains(domain_id, options={}) validate_path_fragment :domain_id, domain_id path = "domains/#{domain_id}/subdomains" if !options.empty? path = path + '?' + array_to_query_string(options) end request( :expects => 200, :method => 'GET', :path => path ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/dns/add_records.rb0000644000004100000410000000162013411315054024761 0ustar www-datawww-datamodule Fog module DNS class Rackspace class Real def add_records(domain_id, records) validate_path_fragment :domain_id, domain_id data = { 'records' => records.map do |record| record_data = { 'name' => record[:name], 'type' => record[:type], 'data' => record[:data] } if record.key? :ttl record_data['ttl'] = record[:ttl] end if record.key? :priority record_data['priority'] = record[:priority] end record_data end } request( :expects => 202, :method => 'POST', :path => "domains/#{domain_id}/records", :body => Fog::JSON.encode(data) ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/0000755000004100000410000000000013411315054023327 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/delete_database.rb0000644000004100000410000000047113411315054026744 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def delete_database(instance_id, name) request( :expects => 202, :method => 'DELETE', :path => "instances/#{instance_id}/databases/#{name}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/list_users.rb0000644000004100000410000000043713411315054026054 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def list_users(instance_id) request( :expects => 200, :method => 'GET', :path => "instances/#{instance_id}/users" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/get_flavor.rb0000644000004100000410000000042313411315054026003 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def get_flavor(flavor_id) request( :expects => 200, :method => 'GET', :path => "flavors/#{flavor_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/check_root_user.rb0000644000004100000410000000044313411315054027033 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def check_root_user(instance_id) request( :expects => 200, :method => 'GET', :path => "instances/#{instance_id}/root" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/list_databases.rb0000644000004100000410000000044713411315054026643 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def list_databases(instance_id) request( :expects => 200, :method => 'GET', :path => "instances/#{instance_id}/databases" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/revoke_user_access.rb0000644000004100000410000000123513411315054027527 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def revoke_user_access(instance_id, user, database) user = if user.respond_to?(:name) && user.respond_to?(:host) host_str = if user.host && user.host != '' && user.host != '%' "@#{user.host}" end.to_s user.name + host_str else user end request( :expects => 202, :method => 'DELETE', :path => "instances/#{instance_id}/users/#{user}/databases/#{database}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/create_database.rb0000644000004100000410000000113313411315054026741 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def create_database(instance_id, name, options = {}) data = { 'databases' => [{ 'name' => name, 'character_set' => options[:character_set] || 'utf8', 'collate' => options[:collate] || 'utf8_general_ci' }] } request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'POST', :path => "instances/#{instance_id}/databases" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/restart_instance.rb0000644000004100000410000000062013411315054027222 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def restart_instance(instance_id) data = { 'restart' => {} } request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'POST', :path => "instances/#{instance_id}/action" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/grant_user_access.rb0000644000004100000410000000151413411315054027347 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def grant_user_access(instance_id, user, *databases) user = if user.respond_to?(:name) && user.respond_to?(:host) host_str = if user.host && user.host != '' && user.host != '%' "@#{user.host}" end.to_s user.name + host_str else user end data = { :databases => [] } databases.each do |db_name| data[:databases] << { :name => db_name } end request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'PUT', :path => "instances/#{instance_id}/users/#{user}/databases" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/delete_user.rb0000644000004100000410000000046113411315054026155 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def delete_user(instance_id, name) request( :expects => 202, :method => 'DELETE', :path => "instances/#{instance_id}/users/#{name}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/create_instance.rb0000644000004100000410000000115613411315054027006 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def create_instance(name, flavor_id, volume_size, options = {}) data = { 'instance' => { 'name' => name, 'flavorRef' => flavor_id, 'volume' => { 'size' => volume_size }, 'databases' => [ ] } } request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'POST', :path => 'instances' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/resize_instance.rb0000644000004100000410000000071513411315054027044 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def resize_instance(instance_id, flavor_id) data = { 'resize' => { 'flavorRef' => flavor_id } } request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'POST', :path => "instances/#{instance_id}/action" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/list_instances.rb0000644000004100000410000000040313411315054026673 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def list_instances() request( :expects => 200, :method => 'GET', :path => 'instances' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/delete_instance.rb0000644000004100000410000000044113411315054027001 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def delete_instance(instance_id) request( :expects => 202, :method => 'DELETE', :path => "instances/#{instance_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/create_user.rb0000644000004100000410000000113713411315054026157 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def create_user(instance_id, name, password, options = {}) data = { 'users' => [{ 'name' => name, 'password' => password, 'databases' => options[:databases] || [], 'host' => options[:host] || '%' }] } request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'POST', :path => "instances/#{instance_id}/users" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/enable_root_user.rb0000644000004100000410000000044513411315054027206 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def enable_root_user(instance_id) request( :expects => 200, :method => 'POST', :path => "instances/#{instance_id}/root" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/list_flavors.rb0000644000004100000410000000037713411315054026372 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def list_flavors() request( :expects => 200, :method => 'GET', :path => 'flavors' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/resize_instance_volume.rb0000644000004100000410000000100113411315054030420 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def resize_instance_volume(instance_id, volume_size) data = { 'resize' => { 'volume' => { 'size' => volume_size } } } request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'POST', :path => "instances/#{instance_id}/action" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/databases/get_instance.rb0000644000004100000410000000043313411315054026317 0ustar www-datawww-datamodule Fog module Rackspace class Databases class Real def get_instance(instance_id) request( :expects => 200, :method => 'GET', :path => "instances/#{instance_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/0000755000004100000410000000000013411315054023463 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/rescue_server.rb0000644000004100000410000000261613411315054026671 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Puts server into rescue mode # @param [String] server_id id of server to rescue # @return [Excon::Response] response # @raise [Fog::Rackspace::Errors::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Errors::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Errors::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Errors::ServiceError] # @note Rescue mode is only guaranteed to be active for 90 minutes # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/rescue_mode.html # # * Status Transition: # * PREP_RESCUE -> RESCUE # * PREP_RESCUE -> ACTIVE (on error) def rescue_server(server_id) data = { 'rescue' => nil } request( :body => Fog::JSON.encode(data), :expects => [200], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def rescue_server(server_id) server = self.data[:servers][server_id] server["status"] = "RESCUE" admin_pass = Fog::Mock.random_letters(12) server_response = { 'adminPass' => admin_pass } response(:status => 200, :body => server_response) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/unrescue_server.rb0000644000004100000410000000230413411315054027226 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Take server out of rescue mode # @param [String] server_id id of server # @return [Excon::Response] response # @raise [Fog::Rackspace::Errors::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Errors::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Errors::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Errors::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/exit_rescue_mode.html # # * Status Transition: # * RESCUE -> PREP_UNRESCUE -> ACTIVE # * RESCUE -> ERROR (on error) def unrescue_server(server_id) data = { 'unrescue' => nil } request( :body => Fog::JSON.encode(data), :expects => [202], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def unrescue_server(server_id) server = self.data[:servers][server_id] server["status"] = "ACTIVE" response(:status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_addresses_by_network.rb0000644000004100000410000000343013411315054031263 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Lists all addresses associated with a specified server and network # @param [String] server_id # @param [String] network_id # @return [Excon::Response] response: # * body [Hash]: # * network [Hash]: # * id [String] - id of network # * ip [Array]: # * [Hash]: # * version [Fixnum] - version of the address # * addr [String] - ip address # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Addresses_by_Network-d1e3118.html def list_addresses_by_network(server_id, network_id) request( :method => 'GET', :expects => 200, :path => "servers/#{server_id}/ips/#{network_id}" ) end end class Mock RESPONSE_BODY = { "addresses" => { "public"=>[{"version"=>6, "addr"=>"2001:4800:7811:0513:0fe1:75e8:ff04:760b"}, {"version"=>4, "addr"=>"166.78.18.176"}], "private"=>[{"version"=>4, "addr"=>"10.181.129.68"}] } } def list_addresses_by_network(server_id, network_id) raise Fog::Compute::RackspaceV2::NotFound.new if server_id == 0 response = Excon::Response.new response.status = 200 response.body = { network_id => RESPONSE_BODY["addresses"][network_id] } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_networks.rb0000644000004100000410000000057713411315054026730 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real def list_networks request(:method => 'GET', :path => 'os-networksv2', :expects => 200) end end class Mock def list_networks networks = self.data[:networks].values response(:body => { 'networks' => networks }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/resize_server.rb0000644000004100000410000000275213411315054026705 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Reverts server resize operation # @param [String] server_id id of server to resize # @param [String] flavor_id id of the desired flavor # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note All resizes are automatically confirmed after 24 hours if you do not explicitly confirm or revert the resize. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Revert_Resized_Server-d1e4024.html # # * Status Transition: # * VERIFY_RESIZE -> ACTIVE # * VERIFY_RESIZE -> ERROR (on error) def resize_server(server_id, flavor_id) data = { 'resize' => { 'flavorRef' => flavor_id } } request( :body => Fog::JSON.encode(data), :expects => [202], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def resize_server(server_id, flavor_id) server = self.data[:servers][server_id] server["status"] = "VERIFY_RESIZE" response(:status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/create_keypair.rb0000644000004100000410000000452613411315054027006 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Request a new keypair to be created # @param [String] key_name: unique name of the keypair to create # @return [Excon::Response] response : # * body [Hash]: - # * 'keypair' [Hash]: - # * 'fingerprint' [String]: unique fingerprint of the keypair # * 'name' [String]: unique name of the keypair # * 'private_key' [String]: the private key of the keypair (only available here, at creation time) # * 'public_key' [String]: the public key of the keypair # * 'user_id' [String]: the user id # @raise [Fog::Compute::RackspaceV2::NotFound] # @raise [Fog::Compute::RackspaceV2::BadRequest] # @raise [Fog::Compute::RackspaceV2::InternalServerError] # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/CreateKeyPair.html def create_keypair(key_name, attributes = nil) key_data = { 'name' => key_name } if attributes.is_a?(String) Fog::Logger.deprecation "Passing the public key as the 2nd arg is deprecated, please pass a hash of attributes." key_data.merge!("public_key" => attributes) end key_data.merge!(attributes) if attributes.is_a?(Hash) data = { 'keypair' => key_data } request( :method => 'POST', :expects => 200, :path => '/os-keypairs', :body => Fog::JSON.encode(data) ) end end class Mock def create_keypair(key_name, attributes = nil) # 409 response when already existing raise Fog::Compute::RackspaceV2::ServiceError if not self.data[:keypairs].select { |k| key_name.include? k['keypair']['name'] }.first.nil? if attributes.is_a?(String) Fog::Logger.deprecation "Passing the public key as the 2nd arg is deprecated, please pass a hash of attributes." end k = self.data[:keypair] k['name'] = key_name self.data[:keypairs] << { 'keypair' => k } response( :status => 200, :body => { 'keypair' => k } ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/delete_attachment.rb0000644000004100000410000000304213411315054027461 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Deletes a specified volume attachment from a specified server instance. # @param [String] server_id id of server containing volume to delete # @param [String] volume_id id of volume on server to delete # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Delete_Volume_Attachment.html def delete_attachment(server_id, volume_id) request( :expects => [202], :method => 'DELETE', :path => "servers/#{server_id}/os-volume_attachments/#{volume_id}" ) end end class Mock def delete_attachment(server_id, volume_id) volume = self.data[:volumes][volume_id] server = self.data[:servers][server_id] if volume.nil? || server.nil? raise Fog::Compute::RackspaceV2::NotFound else self.data[:volume_attachments].delete_if { |v| v["serverId"] == server_id && v["volumeId"] == volume_id } volume["attachments"].delete_if { |v| v["serverId"] == server_id && v["volumeId"] == volume_id } response(:status => 204) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/get_image.rb0000644000004100000410000000326313411315054025735 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves image detail # @param [String] image_id # @return [Excon::Response] response: # * body [Hash]: # * image [Hash]: # * OS-DCF:diskConfig [String] - The disk configuration value. # * created [String] - created timestamp # * id [String] - id of image # * metadata [Hash] - image metadata # * minDisk [Fixnum] # * minRam [Fixnum] # * name [String] - name of image # * progress [Fixnum] - progress complete. Value is from 0 to 100. # * status [String] - status of current image # * updated [String] - updated timestamp # * links [Array] - links to flavor # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Get_Image_Details-d1e4848.html def get_image(image_id) request( :expects => [200, 203], :method => 'GET', :path => "images/#{Fog::Rackspace.escape(image_id)}" ) end end class Mock def get_image(image_id) image = self.data[:images][image_id] if image.nil? raise Fog::Compute::RackspaceV2::NotFound else response(:body => {"image" => image}) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_flavors_detail.rb0000644000004100000410000000247413411315054030050 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves a list of flavors # @return [Excon::Response] response: # * body [Hash]: # * flavors [Array]: # * [Hash]: # * id [String] - flavor id # * links [Array] - flavor links # * name [String] - flavor name # * ram [Fixnum] - flavor ram # * disk [Fixnum] - flavor disk # * vcpus [Fixnum] - flavor vcpus # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Flavors-d1e4188.html def list_flavors_detail request( :expects => [200, 203], :method => 'GET', :path => 'flavors/detail' ) end end class Mock def list_flavors_detail flavors = self.data[:flavors].values.map { |f| Fog::Rackspace::MockData.keep(f, 'id', 'name', 'links') } response(:body => {"flavors" => flavors}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/rebuild_server.rb0000644000004100000410000000653513411315054027035 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # The rebuild operation removes all data on the server and replaces it with the specified image. # The serverRef and all IP addresses remain the same. If you specify name, metadata, accessIPv4, # or accessIPv6 in the rebuild request, new values replace existing values. Otherwise, these values do not change. # @param [String] server_id id of the server to rebuild # @param [String] image_id id of image used to rebuild the server # @param [Hash] options # @option options [String] accessIPv4 The IP version 4 address. # @option options [String] accessIPv6 The IP version 6 address. # @option options [String] adminPass The administrator password. # @option options [Hash] metadata key value pairs of server metadata # @option options [String] OS-DCF:diskConfig The disk configuration value. (AUTO or MANUAL) # @option options [Hash] personality Hash containing data to inject into the file system of the cloud server instance during server creation. # @return [Excon::Response] response: # * body [Hash]: # * server [Hash]: # * name [String] - name of server # * imageRef [String] - id of image used to create server # * flavorRef [String] - id of flavor used to create server # * OS-DCF:diskConfig [String] - The disk configuration value. # * name [String] - name of server # * metadata [Hash] - Metadata key and value pairs. # * personality [Array]: # * [Hash]: # * path - path of the file created # * contents - Base 64 encoded file contents # * networks [Array]: # * [Hash]: # * uuid [String] - uuid of attached network # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Rebuild_Server-d1e3538.html # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Metadata-d1e2529.html # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Personality-d1e2543.html # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#diskconfig_attribute # # * Status Transition: # * ACTIVE -> REBUILD -> ACTIVE # * ACTIVE -> REBUILD -> ERROR (on error) def rebuild_server(server_id, image_id, options={}) data = { 'rebuild' => options || {} } data['rebuild']['imageRef'] = image_id request( :body => Fog::JSON.encode(data), :expects => [202], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def rebuild_server(server_id, image_id, options={}) server = self.data[:servers][server_id] response( :body => {"server" => server}, :status => 202 ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/get_flavor.rb0000644000004100000410000000273413411315054026146 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves flavor detail # @param [Sring] flavor_id # @return [Excon::Response] response: # * body [Hash]: # * flavor [Hash]: # * disk [Fixnum] - disk size in GB # * id [String] - id of flavor # * name [String] - name of flavor # * ram [Fixnum] - amount of ram in MB # * swap [Fixnum] - amount of swap in GB # * vcpus [Fixnum] - number of virtual CPUs # * links [Array] - links to flavor # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Get_Flavor_Details-d1e4317.html def get_flavor(flavor_id) request( :expects => [200, 203], :method => 'GET', :path => "flavors/#{Fog::Rackspace.escape(flavor_id)}" ) end end class Mock def get_flavor(flavor_id) flavor = self.data[:flavors][flavor_id] if flavor.nil? raise Fog::Compute::RackspaceV2::NotFound else response(:body => {"flavor" => flavor}) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/set_metadata_item.rb0000644000004100000410000000276313411315054027471 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Sets a single metadatum item by key. # @param [String] collection type of metadata # @param [String] obj_id id of the object where the metadata is attached # @param [String] key the key of the metadata to set # @param [String] value the value of the metadata to set # @return [Excon::Response] response: # * body [Hash]: # * meta [Hash]: # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Create_or_Update_a_Metadata_Item-d1e5633.html def set_metadata_item(collection, obj_id, key, value) request( :expects => 200, :method => 'PUT', :path => "#{collection}/#{obj_id}/metadata/#{key}", :body => Fog::JSON.encode('meta' => { key => value }) ) end end class Mock def set_metadata_item(collection, obj_id, key, value) raise Fog::Compute::RackspaceV2::NotFound if obj_id == 0 response = Excon::Response.new response.status = 202 response.body = {"meta" => {key => value}} response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_images.rb0000644000004100000410000000327413411315054026316 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves a list of images # ==== Parameters # * options<~String>: # * 'name'<~String> - Filters the list of images by image name # * 'limit'<~String> - Maximum number of objects to return # * 'marker'<~String> - Only return objects whose name is greater than marker # * 'status'<~String> - Filters the list of images by status # * 'type'<~String> - Filters base Rackspace images or anyn custom server images that have been created # # @return [Excon::Response] response: # * body [Hash]: # * images [Array]: # * [Hash]: # * id [String] - image id # * links [Array] - image links # * name [String] - image name # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Images-d1e4435.html def list_images(options = {}) options = options.reject {|key, value| value.nil?} request( :expects => [200, 203], :method => 'GET', :path => 'images', :query => {'format' => 'json'}.merge!(options) ) end end class Mock def list_images(options = {}) images = self.data[:images].values response(:body => {"images" => images}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_virtual_interfaces.rb0000644000004100000410000000140213411315054030731 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Lists virtual interfaces for a server # @param [String] server_id # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/list_virt_interfaces.html def list_virtual_interfaces(server_id) request( :expects => [200], :method => 'GET', :path => "servers/#{server_id}/os-virtual-interfacesv2" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/attach_volume.rb0000644000004100000410000000514513411315054026650 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # This operation attaches a volume to the specified server. # @param [String] server_id # @param [String] volume_id # @param [String] device name of the device /dev/xvd[a-p] (optional) # @return [Excon::Response] response: # * body [Hash]: # * volumeAttachment [Hash]: # * device [String] - The name of the device, such as /dev/xvdb. Specify auto for auto-assignment. # * serverId [String] - The id of the server that attached the volume # * id [String] - The id of the attachment # * volumeId [String] - The id of the volume that was attached # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Attach_Volume_to_Server.html def attach_volume(server_id, volume_id, device) data = { 'volumeAttachment' => { 'volumeId' => volume_id } } data['volumeAttachment']['device'] = device if device request( :body => Fog::JSON.encode(data), :expects => [200], :method => 'POST', :path => "servers/#{server_id}/os-volume_attachments" ) end end class Mock def attach_volume(server_id, volume_id, device) volume = self.data[:volumes][volume_id] server = self.data[:servers][server_id] if server.nil? || volume.nil? raise Fog::Compute::RackspaceV2::NotFound else self.data[:volume_attachments] << { "device" => device, "serverId" => server_id, "volumeId" => volume_id, "id" => volume_id, } volume["attachments"] << { "volumeId" => volume_id, "serverId" => server_id, "device" => device, "id" => volume_id, } body = { "volumeAttachment" => { "serverId" => server_id, "volumeId" => volume_id, "device" => device, "id" => volume_id, } } volume["status"] = "in-use" response(:body => body) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/delete_network.rb0000644000004100000410000000071513411315054027026 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real def delete_network(id) request(:method => 'DELETE', :path => "os-networksv2/#{id}", :expects => 202) end end class Mock def delete_network(id) unless self.data[:networks].key?(id) raise Fog::Compute::RackspaceV2::NotFound end response(:body => '', :status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/delete_keypair.rb0000644000004100000410000000225513411315054027002 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Delete the key specified with key_name # @param [String] key_name name of the key to delete # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] # @raise [Fog::Compute::RackspaceV2::BadRequest] # @raise [Fog::Compute::RackspaceV2::InternalServerError] # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/DeleteKeyPair.html def delete_keypair(key_name) request( :method => 'DELETE', :expects => 202, :path => "/os-keypairs/#{URI.escape(key_name)}" ) end end class Mock def delete_keypair(key_name) if self.data[:keypairs].select { |k| key_name.include? k['keypair']['name'] }.empty? raise Fog::Compute::RackspaceV2::NotFound else self.data[:keypairs].reject! { |k| key_name.include? k['keypair']['name'] } response(:status => 202) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_attachments.rb0000644000004100000410000000273413411315054027364 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves list of attached volumes # @param [String] server_id # @return [Excon::Response] response: # * body [Hash]: # * volumeAttachment [Array]: # * [Hash]: # * device [String] - The name of the device, such as /dev/xvdb. Specify auto for auto-assignment. # * serverId [String] - The id of the server that attached the volume # * id [String] - The id of the attachment # * volumeId [String] - The id of the volume that was attached # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Volume_Attachments.html def list_attachments(server_id) request( :expects => [200, 203, 300], :method => 'GET', :path => "servers/#{server_id}/os-volume_attachments" ) end end class Mock def list_attachments(server_id) volumes_array = self.data[:volume_attachments].select { |va| va["serverId"] == server_id } response(:body => {"volumeAttachments" => volumes_array}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/start_server.rb0000644000004100000410000000244713411315054026542 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # This operation starts a stopped server, and changes its status to ACTIVE. # Prior to running this command, the server status must be SHUTTOFF # @param [String] server_id id of server to rescue # @return [Excon::Response] response # @raise [Fog::Rackspace::Errors::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Errors::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Errors::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Errors::ServiceError] # @note Rescue mode is only guaranteed to be active for 90 minutes # @see https://developer.rackspace.com/docs/cloud-servers/v2/api-reference/svr-basic-operations/#start-specified-server def start_server(server_id) data = { 'os-start' => nil } request( :body => Fog::JSON.encode(data), :expects => [202], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def start_server(server_id) server = self.data[:servers][server_id] server["status"] = "ACTIVE" response(:status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/create_image.rb0000644000004100000410000000761513411315054026426 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Create an image from a running server # # @param [String] server_id Id of server to create image from # @param [String] name name for created image # @param [Hash] options # @option options [Hash] :metadata - key value pairs of image metadata # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Create_Image-d1e4655.html # # * State Transition: # * SAVING -> ACTIVE # * SAVING -> ERROR (on error) def create_image(server_id, name, options = {}) data = { 'createImage' => { 'name' => name } } data['createImage'].merge!(options) request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def create_image(server_id, name, options = {}) image_id = Fog::Rackspace::MockData.uuid image = { "OS-DCF:diskConfig" => "AUTO", "created" => "2012-02-28T19:38:57Z", "id" => image_id, "links" => [ { "href" => "https://dfw.servers.api.rackspacecloud.com/v2/010101/images/#{image_id}", "rel" => "self" }, { "href" => "https://dfw.servers.api.rackspacecloud.com/010101/images/#{image_id}", "rel" => "bookmark" }, { "href" => "https://dfw.servers.api.rackspacecloud.com/010101/images/#{image_id}", "rel" => "alternate", "type" => "application/vnd.openstack.image" } ], "metadata" => { "arch" => "x86-64", "auto_disk_config" => "True", "com.rackspace__1__build_core" => "1", "com.rackspace__1__build_managed" => "0", "com.rackspace__1__build_rackconnect" => "0", "com.rackspace__1__options" => "0", "com.rackspace__1__visible_core" => "1", "com.rackspace__1__visible_managed" => "0", "com.rackspace__1__visible_rackconnect" => "0", "image_type" => "base", "org.openstack__1__architecture" => "x64", "org.openstack__1__os_distro" => "org.ubuntu", "org.openstack__1__os_version" => "11.10", "os_distro" => "ubuntu", "os_type" => "linux", "os_version" => "11.10", "rax_managed" => "false", "rax_options" => "0" }, "minDisk" => 10, "minRam" => 256, "name" => "Ubuntu 11.10", "progress" => 100, "status" => "SAVING", "updated" => "2012-02-28T19:39:05Z" } self.data[:images][image_id] = image response( :status => 202, :headers => {"Location" => "/#{image_id}"} ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/reboot_server.rb0000644000004100000410000000226713411315054026677 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Reboots server # @param [String] server_id # @param [String] type type of reboot # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Reboot_Server-d1e3371.html def reboot_server(server_id, type) data = { 'reboot' => { 'type' => type } } request( :body => Fog::JSON.encode(data), :expects => [202], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def reboot_server(server_id, type) body = { "reboot" => { "type" => type.upcase } } response( :body => body, :status => 202 ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_servers.rb0000644000004100000410000000513613411315054026541 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves list of servers # @return [Excon::Response] response: # * body [Hash]: # * server [Hash]: # * OS-DCF:diskConfig [String] - The disk configuration value. # * OS-EXT-STS:power_state [Fixnum] - The power state. # * OS-EXT-STS:task_state [String] - The task state. # * OS-EXT-STS:vm_state [String] - The VM state. # * accessIPv4 [String] - The public IP version 4 access address. # * accessIPv6 [String] - The public IP version 6 access address. # * addresses [Hash] - Public and private IP addresses, The version field indicates whether the IP address is version 4 or 6. # * created [String] - created timestamp # * hostId [String] - The host id. # * id [String] - id of image # * image [Hash]: # * id [String] - id of the image # * links [Hash] - links to image # * flavor [Hash]: # * id [String] - id of the flavor # * links [Hash] - links to flavor # * links [Hash] - links to server # * metadata [Hash] - server metadata # * name [String] - name of server # * progress [Fixnum] - progress complete. Value is from 0 to 100. # * rax-bandwidth:bandwidth [Array] - The amount of bandwidth used for the specified audit period. # * status [String] - The server status. # * tenant_id [String] - The tenant ID. # * updated [String] - updated timestamp # * user_id [Array] - The user ID. # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Servers-d1e2078.html def list_servers request( :expects => [200, 203, 300], :method => 'GET', :path => 'servers/detail' ) end end class Mock def list_servers servers = self.data[:servers].values.map { |s| Fog::Rackspace::MockData.keep(s, 'id', 'name', 'hostId', 'created', 'updated', 'status', 'progress', 'user_id', 'tenant_id', 'links', 'metadata') } response(:body => {"servers" => servers}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/create_network.rb0000644000004100000410000000145713411315054027033 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real def create_network(label, cidr) data = { 'network' => { 'label' => label, 'cidr' => cidr } } request( :method => 'POST', :body => Fog::JSON.encode(data), :path => "os-networksv2", :expects => 200 ) end end class Mock def create_network(label, cidr) network_id = Fog::Rackspace::MockData.uuid self.data[:networks][network_id] = { 'id' => network_id, 'label' => label, 'cidr' => cidr } response(:body => { 'network' => self.data[:networks][network_id] }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_keypairs.rb0000644000004100000410000000233313411315054026673 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Returns a list of all key pairs associated with an account. # @return [Excon::Response] response : # * body [Hash]: - # * 'keypairs' [Array]: list of keypairs # * 'keypair' [Hash]: - # * 'fingerprint' [String]: unique fingerprint of the keypair # * 'name' [String]: unique name of the keypair # * 'public_key' [String]: the public key assigned to the keypair # @raise [Fog::Compute::RackspaceV2::NotFound] # @raise [Fog::Compute::RackspaceV2::BadRequest] # @raise [Fog::Compute::RackspaceV2::InternalServerError] # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ListKeyPairs.html def list_keypairs request( :method => 'GET', :expects => 200, :path => 'os-keypairs' ) end end class Mock def list_keypairs response( :status => 200, :body => { 'keypairs' => self.data[:keypairs] }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/get_vnc_console.rb0000644000004100000410000000253113411315054027160 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Get a vnc console for an instance. # # === Parameters # * server_id <~String> - The ID of the server. # * console_type <~String> - Type of vnc console to get ('novnc' or 'xvpvnc'). # === Returns # * response <~Excon::Response>: # * body <~Hash>: # * url <~String> # * type <~String> def get_vnc_console(server_id, console_type) data = { 'os-getVNCConsole' => { 'type' => console_type } } request( :body => Fog::JSON.encode(data), :expects => [200], :method => 'POST', :path => "servers/#{server_id}/action" ) end # def get_vnc_console end # class Real class Mock def get_vnc_console(server_id, console_type) response = Excon::Response.new response.status = 200 response.body = { "console" => { "url" => "http://192.168.27.100:6080/vnc_auto.html?token=c3606020-d1b7-445d-a88f-f7af48dd6a20", "type" => "novnc" } } response end # def get_vnc_console end # class Mock end # class OpenStack end # module Compute end # module Fog fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/get_network.rb0000644000004100000410000000073313411315054026343 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real def get_network(id) request(:method => 'GET', :path => "os-networksv2/#{id}", :expects => 200) end end class Mock def get_network(id) unless self.data[:networks].key?(id) raise Fog::Compute::RackspaceV2::NotFound end response(:body => { 'network' => self.data[:networks][id] }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/create_server.rb0000644000004100000410000002512513411315054026646 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Create server # @param [String] name name of server # @param [String] image_id of the image used to create server # @param [String] flavor_id id of the flavor of the image # @param [String] min_count # @param [String] max_count # @param [Hash] options # @option options [Hash] metadata key value pairs of server metadata # @option options [String] OS-DCF:diskConfig The disk configuration value. (AUTO or MANUAL) # @option options [Hash] personality Hash containing data to inject into the file system of the cloud server instance during server creation. # @option options [Boolean] config_drive whether to attach a read-only configuration drive # @option options [String] keypair Name of the kay-pair to associate with this server. # @option options [Array] block_device_mapping A manually specified block device mapping to fully control the creation and # attachment of volumes to this server. Mutually exclusive with :volume_id or :volume_image_id. If provided, leave image_id # as "". See http://developer.openstack.org/api-ref-compute-v2-ext.html#ext-os-block-device-mapping-v2-boot for details. # @option options [String] boot_volume_id Id of a pre-created bootable volume to use for this server. If provided, leave image_id as "". # @option options [Integer] boot_volume_size Size of the bootable volume to be created expressed in GB. (defaults to 100) # @option options [String] boot_image_id Id of an image to create a bootable volume from and attach to this server. If provided, # leave image_id as "". # @return [Excon::Response] response: # * body [Hash]: # * server [Hash]: # * name [String] - name of server # * imageRef [String] - id of image used to create server # * flavorRef [String] - id of flavor used to create server # * OS-DCF:diskConfig [String] - The disk configuration value. # * name [String] - name of server # * metadata [Hash] - Metadata key and value pairs. # * personality [Array]: # * [Hash]: # * path - path of the file created # * contents - Base 64 encoded file contents # * networks [Array]: # * [Hash]: # * uuid [String] - uuid of attached network # * config_drive [Boolean]: Wether to use a config drive or not # * user_data [String]: User data for cloud init # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/CreateServers.html # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Metadata-d1e2529.html # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Personality-d1e2543.html # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#diskconfig_attribute # @see http://developer.openstack.org/api-ref-compute-v2-ext.html#ext-os-block-device-mapping-v2-boot # # * State Transitions # * BUILD -> ACTIVE # * BUILD -> ERROR (on error) def create_server(name, image_id, flavor_id, min_count, max_count, options = {}) data = { 'server' => { 'name' => name, 'imageRef' => image_id, 'flavorRef' => flavor_id, 'minCount' => min_count, 'maxCount' => max_count } } data['server']['adminPass'] = options[:password] unless options[:password].nil? data['server']['OS-DCF:diskConfig'] = options[:disk_config] unless options[:disk_config].nil? data['server']['metadata'] = options[:metadata] unless options[:metadata].nil? data['server']['personality'] = options[:personality] unless options[:personality].nil? data['server']['config_drive'] = options[:config_drive] unless options[:config_drive].nil? data['server']['user_data'] = options[:user_data] unless options[:user_data].nil? data['server']['networks'] = options[:networks] || [ { :uuid => '00000000-0000-0000-0000-000000000000' }, { :uuid => '11111111-1111-1111-1111-111111111111' } ] if options[:keypair] Fog::Logger.deprecation(":keypair has been depreciated. Please use :key_name instead.") options[:key_name] = options[:keypair] end data['server']['key_name'] = options[:key_name] unless options[:key_name].nil? if options[:block_device_mapping] if options[:boot_volume_id] Fog::Logger.warning("Manual :block_device_mapping overrides :boot_volume_id in #create_server!") end if options[:boot_image_id] Fog::Logger.warning("Manual :block_device_mapping overrides :boot_image_id in #create_server!") end data['server']['block_device_mapping_v2'] = options[:block_device_mapping] else if options[:boot_volume_id] if options[:boot_image_id] Fog::Logger.warning(":boot_volume_id overrides :boot_image_id!") end if options[:boot_volume_size] Fog::Logger.warning("Boot volume size: " + options[:boot_volume_size] + "GB") end data['server']['block_device_mapping_v2'] = [{ 'boot_index' => '0', 'uuid' => options[:boot_volume_id], 'source_type' => 'volume', 'destination_type' => 'volume', 'volume_size' => options[:boot_volume_size] ? options[:boot_volume_size] : 100 }] end if options[:boot_image_id] data['server']['block_device_mapping_v2'] = [{ 'boot_index' => '0', 'uuid' => options[:boot_image_id], 'source_type' => 'image', 'destination_type' => 'volume', 'volume_size' => options[:boot_volume_size] ? options[:boot_volume_size] : 100 }] end end request( :body => Fog::JSON.encode(data), :expects => [202], :method => 'POST', :path => "servers" ) end end class Mock def create_server(name, image_id, flavor_id, min_count, max_count, options={}) server_id = Fog::Rackspace::MockData.uuid public_ip4 = Fog::Rackspace::MockData.ipv4_address public_ip6 = Fog::Rackspace::MockData.ipv6_address private_ip4 = Fog::Rackspace::MockData.ipv4_address private_ip6 = Fog::Rackspace::MockData.ipv6_address admin_pass = Fog::Mock.random_letters(12) flavor = self.data[:flavors][flavor_id] image = self.data[:images][image_id] server = { "OS-DCF:diskConfig" => "AUTO", "OS-EXT-STS:power_state" => 1, "OS-EXT-STS:task_state" => nil, "OS-EXT-STS:vm_state" => "active", "accessIPv4" => public_ip4, "accessIPv6" => public_ip6, "addresses" => { "private" => [ { "addr" => private_ip4, "version" => 4 } ], "public" => [ { "addr" => public_ip4, "version" => 4 }, { "addr" => public_ip6, "version" => 6 } ] }, "created" => "2012-07-28T15:32:25Z", "flavor" => Fog::Rackspace::MockData.keep(flavor, "id", "links"), "hostId" => Fog::Mock.random_hex(56), "id" => server_id, "image" => Fog::Rackspace::MockData.keep(image, "id", "links"), "links" => [ { "href" => "https://dfw.servers.api.rackspacecloud.com/v2/010101/servers/#{server_id}", "rel" => "self", }, { "href" => "https://dfw.servers.api.rackspacecloud.com/010101/servers/#{server_id}", "rel" => "bookmark", } ], "metadata" => {}, "name" => name, "progress" => 100, "rax-bandwidth:bandwidth" => [ { "audit_period_end" => "2012-08-16T14:12:00Z", "audit_period_start" => "2012-08-16T06:00:00Z", "bandwidth_inbound" => 39147845, "bandwidth_outbound" => 13390651, "interface" => "public", }, { "audit_period_end" => "2012-08-16T14:12:00Z", "audit_period_start" => "2012-08-16T06:00:00Z", "bandwidth_inbound" => 24229191, "bandwidth_outbound" => 84, "interface" => "private", } ], "status" => "ACTIVE", "tenant_id" => "010101", "updated" => "2012-07-28T15:37:09Z", "user_id" => "170454", :volume_ids => [], } # add in additional networks if options[:networks] options[:networks].each do |network| net_label = self.data[:networks][network[:uuid]]["label"] server["addresses"] = { net_label => []} end end self.data[:servers][server_id] = server response = { "server" => { "OS-DCF:diskConfig" => "AUTO", "adminPass" => admin_pass, "id" => server_id, "links" => [ { "href" => "https://dfw.servers.api.rackspacecloud.com/v2/010101/servers/#{server_id}", "rel" => "self" }, { "href" => "https://dfw.servers.api.rackspacecloud.com/010101/servers/#{server_id}", "rel" => "bookmark" } ] } } response(:body => response) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/delete_metadata_item.rb0000644000004100000410000000240413411315054030130 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Deletes a metadata item. # @param [String] collection type of metadata # @param [String] obj_id id of the object where the metadata is attached # @param [String] key the key of the metadata to delete # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Delete_Metadata_Item-d1e5790.html def delete_metadata_item(collection, obj_id, key) request( :expects => 204, :method => 'DELETE', :path => "#{collection}/#{obj_id}/metadata/#{key}" ) end end class Mock def delete_metadata_item(collection, obj_id, key) raise Fog::Compute::RackspaceV2::NotFound if obj_id == 0 response = Excon::Response.new response.body = "" response.status = 204 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_images_detail.rb0000644000004100000410000000420113411315054027627 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves a list of images # ==== Parameters # * options<~String>: # * 'name'<~String> - Filters the list of images by image name # * 'limit'<~String> - Maximum number of objects to return # * 'marker'<~String> - Only return objects whose name is greater than marker # * 'status'<~String> - Filters the list of images by status # * 'type'<~String> - Filters base Rackspace images or anyn custom server images that have been created # # @return [Excon::Response] response: # * body [Hash]: # * images [Array]: # * [Hash]: # * id [String] - image id # * links [Array] - image links # * name [String] - image name # * minDisk [Fixnum] - image minimum disk required # * minRam [Fixnum] - image minimum ram required # * created [String] - image creation date (ISO 8601 format) # * updated [String] - date of most recent image update # * state [String] - image status (e.g. ACTIVE, SAVING, ERROR) # * progress [Fixnum] - image saving progress # # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Images-d1e4435.html def list_images_detail(options = {}) options = options.reject {|key, value| value.nil?} request( :expects => [200, 203], :method => 'GET', :path => 'images/detail', :query => {'format' => 'json'}.merge!(options) ) end end class Mock def list_images_detail(options = {}) images = self.data[:images].values response(:body => {"images" => images}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/get_metadata_item.rb0000644000004100000410000000254413411315054027452 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves single metadatum item by key. # @param [String] collection type of metadata # @param [String] obj_id id of the object where the metadata is attached # @param [String] key the key of the metadata to retrieve # @return [Excon::Response] response: # * body [Hash]: # * meta [Hash]: # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Get_Metadata_Item-d1e5507.html def get_metadata_item(collection, obj_id, key) request( :expects => 200, :method => 'GET', :path => "#{collection}/#{obj_id}/metadata/#{key}" ) end end class Mock def get_metadata_item(collection, obj_id, key) raise Fog::Compute::RackspaceV2::NotFound if obj_id == 0 response = Excon::Response.new response.status = 202 response.body = {"meta" => {"environment" => "dev"}} response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/revert_resize_server.rb0000644000004100000410000000256713411315054030300 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Reverts server resize operation # @param [String] server_id # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note All resizes are automatically confirmed after 24 hours if you do not explicitly confirm or revert the resize. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Revert_Resized_Server-d1e4024.html # @see Server#resize # # * Status Transition: # * VERIFY_RESIZE -> ACTIVE # * VERIFY_RESIZE -> ERROR (on error) def revert_resize_server(server_id) data = { 'revertResize' => nil } request( :body => Fog::JSON.encode(data), :expects => [202], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def revert_resize_server(server_id) server = self.data[:servers][server_id] server["status"] = "ACTIVE" response(:status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/stop_server.rb0000644000004100000410000000255613411315054026373 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # This operation stops a running server, and changes the server status to SHUTOFF # and changes the clean_shutdown parameter to TRUE. # Prior to running this command, the server status must be ACTIVE or ERROR. # @param [String] server_id id of server to rescue # @return [Excon::Response] response # @raise [Fog::Rackspace::Errors::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Errors::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Errors::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Errors::ServiceError] # @note Rescue mode is only guaranteed to be active for 90 minutes # @see https://developer.rackspace.com/docs/cloud-servers/v2/api-reference/svr-basic-operations/#stop-specified-server def stop_server(server_id) data = { 'os-stop' => nil } request( :body => Fog::JSON.encode(data), :expects => [202], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def stop_server(server_id) server = self.data[:servers][server_id] server["status"] = "SHUTOFF" response(:status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/update_metadata.rb0000644000004100000410000000273213411315054027136 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Updates metadata items for a specified server or image. # @param [String] collection type of metadata # @param [String] obj_id id of the object where the metadata is attached # @param [Hash] metadata key value pairs of metadata # @return [Excon::Response] response: # * body [Hash]: # * metadata [Hash]: # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Update_Metadata-d1e5208.html def update_metadata(collection, obj_id, metadata = {}) request( :expects => [200, 203], :method => 'POST', :path => "#{collection}/#{obj_id}/metadata", :body => Fog::JSON.encode('metadata' => metadata) ) end end class Mock def update_metadata(collection, obj_id, metadata = {}) raise Fog::Compute::RackspaceV2::NotFound if obj_id == 0 response = Excon::Response.new response.status = 202 response.body = {"metadata" => {"environment" => "dev", "tag" => "database"}} response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/set_metadata.rb0000644000004100000410000000270113411315054026443 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Sets metadata associated with a server or an image. # @param [String] collection type of metadata # @param [String] obj_id id of the object where the metadata is attached # @param [Hash] metadata key value pairs of metadata # @return [Excon::Response] response: # * body [Hash]: # * metadata [Hash]: # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Create_or_Replace_Metadata-d1e5358.html def set_metadata(collection, obj_id, metadata = {}) request( :expects => [200, 203], :method => 'PUT', :path => "#{collection}/#{obj_id}/metadata", :body => Fog::JSON.encode('metadata' => metadata) ) end end class Mock def set_metadata(collection, obj_id, metadata = {}) raise Fog::Compute::RackspaceV2::NotFound if obj_id == 0 response = Excon::Response.new response.status = 202 response.body = {"metadata"=>{"environment"=>"dev"}} response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/change_server_password.rb0000644000004100000410000000246213411315054030551 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Changes server admin password # @param [String] server_id # @param [String] password # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note Though Rackspace does not enforce complexity requirements for the password, the operating system might. If the password is not complex enough, the server might enter an ERROR state. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Change_Password-d1e3234.html def change_server_password(server_id, password) data = { 'changePassword' => { 'adminPass' => password } } request( :body => Fog::JSON.encode(data), :expects => [202], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def change_server_password(server_id, password) response(:status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/delete_image.rb0000644000004100000410000000205713411315054026420 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Delete an image # @param [String] image_id Id of image to delete # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Delete_Image-d1e4957.html def delete_image(image_id) request( :expects => 204, :method => 'DELETE', :path => "images/#{image_id}" ) end end class Mock def delete_image(image_id) raise Fog::Compute::RackspaceV2::NotFound.new if image_id == Fog::Rackspace::MockData::NOT_FOUND_ID response = Excon::Response.new response.status = 202 response.body = "" end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/create_virtual_interface.rb0000644000004100000410000000211013411315054031033 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Creates virtual interface for a server # @param [String] server_id The server id to create the virtual interface on # @param [String] network_id The network id to attach the virtual interface to # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/api_create_virtual_interface.html def create_virtual_interface(server_id, network_id) data = { :virtual_interface => { :network_id => network_id } } request( :expects => [200], :method => 'POST', :path => "servers/#{server_id}/os-virtual-interfacesv2", :body => Fog::JSON.encode(data) ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/update_server.rb0000644000004100000410000000367113411315054026667 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Update the editable attributes of a specified server. # @param [String] server_id # @param [Hash] options # @option options [Hash] name name for server # @option options [String] accessIPv4 The IP version 4 address. # @option options [Hash] accessIPv6 The IP version 6 address. # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note If you edit the server name, the server host name does not change. Also, server names are not guaranteed to be unique. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ServerUpdate.html def update_server(server_id, options={}) data = options.is_a?(Hash) ? options : { 'name' => options } #LEGACY - second parameter was previously server name request( :body => Fog::JSON.encode('server' => data), :expects => [200], :method => 'PUT', :path => "servers/#{server_id}" ) end end class Mock def update_server(server_id, name) server = self.data[:servers][server_id] name.each_pair {|k,v| server[k] = v } if name.is_a?(Hash) server['name'] = name if name.is_a?(String) server_response = Fog::Rackspace::MockData.keep(server, 'id', 'name', 'hostId', 'created', 'updated', 'status', 'progress', 'user_id', 'tenant_id', 'links', 'metadata', 'accessIPv4', 'accessIPv6', 'OS-DCF:diskConfig', 'rax-bandwidth:bandwidth', 'addresses', 'flavor', 'links', 'image') response( :status => 200, :body => {'server' => server_response} ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/delete_virtual_interface.rb0000644000004100000410000000164213411315054031043 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Deletes virtual interface from server # @param [String] server_id The server id that contains the virtual interface # @param [String] interface_id The id of the virtual interface # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/delete_virt_interface_api.html def delete_virtual_interface(server_id, interface_id) request( :expects => [200], :method => 'DELETE', :path => "servers/#{server_id}/os-virtual-interfacesv2/#{interface_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_flavors.rb0000644000004100000410000000222713411315054026522 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves a list of flavors # @return [Excon::Response] response: # * body [Hash]: # * flavors [Array]: # * [Hash]: # * id [String] - flavor id # * links [Array] - flavor links # * name [String] - flavor name # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Flavors-d1e4188.html def list_flavors request( :expects => [200, 203], :method => 'GET', :path => 'flavors' ) end end class Mock def list_flavors flavors = self.data[:flavors].values.map { |f| Fog::Rackspace::MockData.keep(f, 'id', 'name', 'links') } response(:body => {"flavors" => flavors}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/get_attachment.rb0000644000004100000410000000301013411315054026771 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves attachment # @param [String] server_id # @param [String] volume_id # @return [Excon::Response] response: # * body [Hash]: # * volumeAttachment [Hash]: # * device [String] - The name of the device, such as /dev/xvdb. Specify auto for auto-assignment. # * serverId [String] - The id of the server that attached the volume # * id [String] - The id of the attachment # * volumeId [String] - The id of the volume that was attached # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Get_Volume_Attachment_Details.html def get_attachment(server_id, volume_id) request( :expects => [200, 203, 300], :method => 'GET', :path => "servers/#{server_id}/os-volume_attachments/#{volume_id}" ) end end class Mock def get_attachment(server_id, volume_id) attachment = self.data[:volume_attachments].find { |v| v["serverId"] == server_id && v["volumeId"] == volume_id } response(:body => {"volumeAttachment" => attachment}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/delete_server.rb0000644000004100000410000000231613411315054026642 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Deletes a specified server instance from the system. # @param [String] server_id the id of the server to delete # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Delete_Server-d1e2883.html def delete_server(server_id) request({ :expects => [204], :method => 'DELETE', :path => "servers/#{server_id}" }, false) end end class Mock def delete_server(server_id) self.data[:servers].delete(server_id) volumes = self.data[:volumes].values volumes.each do |v| v["attachments"].delete_if { |a| a["serverId"] == server_id } v["status"] = "available" if v["attachments"].empty? end response(:status => 204) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/get_keypair.rb0000644000004100000410000000256613411315054026324 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retreive single keypair details # @param [String] key_name name of the key for which to request the details # @return [Excon::Response] response : # * body [Hash]: - # * 'keypair' [Hash]: - # * 'fingerprint' [String]: unique fingerprint of the keypair # * 'name' [String]: unique name of the keypair # * 'public_key' [String]: the public key assigne to the keypair # @raise [Fog::Compute::RackspaceV2::NotFound] # @raise [Fog::Compute::RackspaceV2::BadRequest] # @raise [Fog::Compute::RackspaceV2::InternalServerError] # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ListKeyPairs.html def get_keypair(key_name) request( :method => 'GET', :expects => 200, :path => "/os-keypairs/#{key_name}" ) end end class Mock def get_keypair(key_name) key = self.data[:keypairs].select { |k| key_name.include? k['keypair']['name'] }.first if key.nil? raise Fog::Compute::RackspaceV2::NotFound end response(:body => key, :status => 200) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/confirm_resize_server.rb0000644000004100000410000000257413411315054030424 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Confirm server resize operation # @param [String] server_id The id of the server to revert # @return [Excon::Response] response # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note All resizes are automatically confirmed after 24 hours if you do not explicitly confirm or revert the resize. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Revert_Resized_Server-d1e4024.html # # * Status Transition: # * VERIFY_RESIZE -> ACTIVE # * VERIFY_RESIZE -> ERROR (on error) def confirm_resize_server(server_id) data = { 'confirmResize' => nil } request( :body => Fog::JSON.encode(data), :expects => [204], :method => 'POST', :path => "servers/#{server_id}/action" ) end end class Mock def confirm_resize_server(server_id) server = self.data[:servers][server_id] server["status"] = "ACTIVE" response(:status => 204) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_addresses.rb0000644000004100000410000000260413411315054027022 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Lists all networks and addresses associated with a specified server. # @param [String] server_id # @return [Excon::Response] response: # * body [Hash]: # * addresses [Hash] - key is the network name and the value are an array of addresses allocated for that network # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def list_addresses(server_id) request( :method => 'GET', :expects => 200, :path => "/servers/#{server_id}/ips" ) end end class Mock def list_addresses(server_id) raise Fog::Compute::RackspaceV2::NotFound.new if server_id == 0 response = Excon::Response.new response.status = 200 response.body = { "addresses" => { "public"=>[{"version"=>6, "addr"=>"2001:4800:7811:0513:0fe1:75e8:ff04:760b"}, {"version"=>4, "addr"=>"166.78.18.176"}], "private"=>[{"version"=>4, "addr"=>"10.181.129.68"}] } } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/get_server.rb0000644000004100000410000000575013411315054026164 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves server detail # @param [String] server_id # @return [Excon::Response] response: # * body [Hash]: # * server [Hash]: # * OS-DCF:diskConfig [String] - The disk configuration value. # * OS-EXT-STS:power_state [Fixnum] - The power state. # * OS-EXT-STS:task_state [String] - The task state. # * OS-EXT-STS:vm_state [String] - The VM state. # * accessIPv4 [String] - The public IP version 4 access address. # * accessIPv6 [String] - The public IP version 6 access address. # * addresses [Hash] - Public and private IP addresses, The version field indicates whether the IP address is version 4 or 6. # * created [String] - created timestamp # * hostId [String] - The host id. # * id [String] - id of image # * image [Hash]: # * id [String] - id of the image # * links [Hash] - links to image # * flavor [Hash]: # * id [String] - id of the flavor # * links [Hash] - links to flavor # * links [Hash] - links to server # * metadata [Hash] - server metadata # * name [String] - name of server # * progress [Fixnum] - progress complete. Value is from 0 to 100. # * rax-bandwidth:bandwidth [Array] - The amount of bandwidth used for the specified audit period. # * status [String] - The server status. # * tenant_id [String] - The tenant ID. # * updated [String] - updated timestamp # * user_id [Array] - The user ID. # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Get_Server_Details-d1e2623.html def get_server(server_id) request( :expects => [200, 203, 300], :method => 'GET', :path => "servers/#{server_id}" ) end end class Mock def get_server(server_id) server = self.data[:servers][server_id] if server.nil? raise Fog::Compute::RackspaceV2::NotFound else server_response = Fog::Rackspace::MockData.keep(server, 'id', 'name', 'hostId', 'created', 'updated', 'status', 'progress', 'user_id', 'tenant_id', 'links', 'metadata', 'accessIPv4', 'accessIPv6', 'OS-DCF:diskConfig', 'rax-bandwidth:bandwidth', 'addresses', 'flavor', 'image') server_response['image']['links'].map! { |l| l.delete("type"); l } response(:body => {"server" => server_response}) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute_v2/list_metadata.rb0000644000004100000410000000244013411315054026623 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Real # Retrieves all metadata associated with a server or an image. # @param [String] collection type of metadata # @param [String] obj_id id of the object where the metadata is attached # @return [Excon::Response] response: # * body [Hash]: # * meta [Hash]: # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Metadata-d1e5089.html def list_metadata(collection, obj_id) request( :expects => [200, 203], :method => 'GET', :path => "#{collection}/#{obj_id}/metadata" ) end end class Mock def list_metadata(collection, obj_id) raise Fog::Compute::RackspaceV2::NotFound if obj_id == 0 response = Excon::Response.new response.status = 202 response.body = { "metadata"=>{"tag"=>"database"} } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/0000755000004100000410000000000013411315054022553 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/get_ping.rb0000644000004100000410000000030113411315054024666 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def get_ping request( :expects => [204], :method => 'GET', :path => "ping", :headers => { :accept => "*/*" } ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/get_service.rb0000644000004100000410000000025013411315054025374 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def get_service(id) request( :expects => 200, :method => 'GET', :path => "services/#{id}" ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/get_flavor.rb0000644000004100000410000000025013411315054025225 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def get_flavor(id) request( :expects => [200], :method => 'GET', :path => "flavors/#{id}" ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/list_services.rb0000644000004100000410000000030413411315054025753 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def list_services(options={}) request( :expects => [200], :method => 'GET', :path => request_uri("services", options) ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/delete_service.rb0000644000004100000410000000027313411315054026064 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def delete_service(service) request( :expects => 202, :method => 'DELETE', :path => "services/#{service.id}" ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/update_service.rb0000644000004100000410000000053313411315054026103 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def update_service(service) request( :expects => [201, 202], :method => 'PATCH', :headers => {"Content-Type" => "application/json-patch+json"}, :body => Fog::JSON.encode(service.operations), :path => "services/#{service.id}" ) service.operations = [] end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/create_service.rb0000644000004100000410000000033713411315054026066 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def create_service(service) request( :expects => [201, 202], :method => 'POST', :body => Fog::JSON.encode(service), :path => "services" ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/get_home_document.rb0000644000004100000410000000023613411315054026566 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def get_home_document request( :expects => [200], :method => 'GET', :path => "" ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/list_flavors.rb0000644000004100000410000000024013411315054025603 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def list_flavors request( :expects => [200], :method => 'GET', :path => "flavors" ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/cdn_v2/delete_assets.rb0000644000004100000410000000043213411315054025723 0ustar www-datawww-dataclass Fog::Rackspace::CDNV2::Real def delete_assets(service, options={}) uri = request_uri("services/#{service.id}/assets", options) request( :expects => 202, :method => 'DELETE', :path => uri, :headers => { :accept => "*/*" } ) end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/0000755000004100000410000000000013411315054024331 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/list_protocols.rb0000644000004100000410000000043213411315054027734 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def list_protocols request( :expects => 200, :method => 'GET', :path => 'loadbalancers/protocols' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_monitor.rb0000644000004100000410000000047313411315054027210 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_monitor(load_balancer_id) request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}/healthmonitor", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/delete_all_access_rules.rb0000644000004100000410000000051513411315054031504 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def delete_all_access_rules(load_balancer_id) request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/accesslist", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_ssl_termination.rb0000644000004100000410000000050613411315054030730 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_ssl_termination(load_balancer_id) request( :expects => [200], :path => "loadbalancers/#{load_balancer_id}/ssltermination", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/update_node.rb0000644000004100000410000000150613411315054027147 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def update_node(load_balancer_id, node_id, options = {}) data = { 'node' => {} } if options.key? :weight data['node']['weight'] = options[:weight] end if options.key? :condition data['node']['condition'] = options[:condition] end if options.key? :type data['node']['type'] = options[:type] end #TODO - Do anything if no valid options are passed in? request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'PUT', :path => "loadbalancers/#{load_balancer_id}/nodes/#{node_id}.json" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/delete_access_rule.rb0000644000004100000410000000055213411315054030472 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def delete_access_rule(load_balancer_id, access_rule_id) request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/accesslist/#{access_rule_id}", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/delete_virtual_ip.rb0000644000004100000410000000054713411315054030364 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def delete_virtual_ip(load_balancer_id, virtual_ip_id) request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/virtualips/#{virtual_ip_id}", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_content_caching.rb0000644000004100000410000000050413411315054030642 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_content_caching(load_balancer_id) request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}/contentcaching", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_usage.rb0000644000004100000410000000075513411315054026630 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_usage(options = {}) if options.key? :start_time and options.key? :end_time query = "?startTime=#{options[:start_time]}&endTime=#{options[:end_time]}" else query = '' end request( :expects => 200, :path => "loadbalancers/usage#{query}", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_error_page.rb0000644000004100000410000000047213411315054027645 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_error_page(load_balancer_id) request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}/errorpage", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/delete_nodes.rb0000644000004100000410000000064613411315054027316 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def delete_nodes(load_balancer_id, *node_ids) query_string = node_ids.map { |node_id| "id=#{node_id}" }.join('&') request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/nodes?#{query_string}", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/remove_session_persistence.rb0000644000004100000410000000053113411315054032321 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def remove_session_persistence(load_balancer_id) request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/sessionpersistence", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/update_load_balancer.rb0000644000004100000410000000134713411315054030773 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def update_load_balancer(load_balancer_id, options = {}) data = { 'loadBalancer' => { 'name' => options[:name], 'port' => options[:port], 'protocol' => options[:protocol], 'algorithm' => options[:algorithm], 'timeout' => options[:timeout], 'httpsRedirect' => options[:https_redirect] } } request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'PUT', :path => "loadbalancers/#{load_balancer_id}.json" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_session_persistence.rb0000644000004100000410000000051413411315054031604 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_session_persistence(load_balancer_id) request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}/sessionpersistence", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_stats.rb0000644000004100000410000000130213411315054026647 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_stats(load_balancer_id) request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}/stats", :method => 'GET' ) end end class Mock def get_stats(load_balancer_id) mock_data = { 'connectTimeOut' => 0, 'connectError' => 1, 'connectFailure' => 2, 'dataTimedOut' => 3, 'keepAliveTimedOut' => 4, 'maxConn' => 5 } Excon::Response.new(:body => mock_data, :status => 200) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/list_access_rules.rb0000644000004100000410000000050413411315054030363 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def list_access_rules(load_balancer_id) request( :expects => 200, :method => 'GET', :path => "loadbalancers/#{load_balancer_id}/accesslist" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/remove_connection_throttling.rb0000644000004100000410000000053313411315054032651 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def remove_connection_throttling(load_balancer_id) request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/connectionthrottle", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/list_nodes.rb0000644000004100000410000000047513411315054027027 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def list_nodes(load_balancer_id) request( :expects => 200, :method => 'GET', :path => "loadbalancers/#{load_balancer_id}/nodes.json" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/remove_ssl_termination.rb0000644000004100000410000000052113411315054031443 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def remove_ssl_termination(load_balancer_id) request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/ssltermination", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/create_node.rb0000644000004100000410000000146613411315054027135 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def create_node(load_balancer_id, address, port, condition, options = {}) data = { 'nodes' => [ { 'address' => address, 'port' => port, 'condition' => condition } ]} if options.key?(:weight) data['nodes'][0]['weight'] = options[:weight] end if options.key? :type data['nodes'][0]['type'] = options[:type] end request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => "loadbalancers/#{load_balancer_id}/nodes.json" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/list_algorithms.rb0000644000004100000410000000043413411315054030063 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def list_algorithms request( :expects => 200, :method => 'GET', :path => 'loadbalancers/algorithms' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_connection_logging.rb0000644000004100000410000000051213411315054031360 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_connection_logging(load_balancer_id) request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}/connectionlogging", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/remove_error_page.rb0000644000004100000410000000050713411315054030362 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def remove_error_page(load_balancer_id) request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/errorpage", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/remove_monitor.rb0000644000004100000410000000051013411315054027716 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def remove_monitor(load_balancer_id) request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/healthmonitor", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/create_virtual_ip.rb0000644000004100000410000000074513411315054030365 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def create_virtual_ip(load_balancer_id, type) data = { 'type' => type, 'ipVersion' => 'IPV6' } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => "loadbalancers/#{load_balancer_id}/virtualips.json" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/set_content_caching.rb0000644000004100000410000000077713411315054030672 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def set_content_caching(load_balancer_id, value) data = { 'contentCaching' => { 'enabled' => value.to_s } } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/contentcaching", :method => 'PUT' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/set_session_persistence.rb0000644000004100000410000000104413411315054031617 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def set_session_persistence(load_balancer_id, persistence_type) data = { 'sessionPersistence' => { 'persistenceType' => persistence_type } } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/sessionpersistence", :method => 'PUT' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/delete_node.rb0000644000004100000410000000052013411315054027122 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def delete_node(load_balancer_id, node_id) request( :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/nodes/#{node_id}", :method => 'DELETE' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/list_virtual_ips.rb0000644000004100000410000000051013411315054030246 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def list_virtual_ips(load_balancer_id) request( :expects => 200, :method => 'GET', :path => "loadbalancers/#{load_balancer_id}/virtualips.json" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_node.rb0000644000004100000410000000051113411315054026437 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_node(load_balancer_id, node_id) request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}/nodes/#{node_id}.json", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/set_monitor.rb0000644000004100000410000000165213411315054027224 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def set_monitor(load_balancer_id, type, delay, timeout, attempsBeforeDeactivation, options = {}) data = { 'type' => type, 'delay' => delay, 'timeout' => timeout, 'attemptsBeforeDeactivation' => attempsBeforeDeactivation } if options.key? :path data['path'] = options[:path] end if options.key? :body_regex data['bodyRegex'] = options[:body_regex] end if options.key? :status_regex data['statusRegex'] = options[:status_regex] end request( :body => Fog::JSON.encode(data), :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/healthmonitor", :method => 'PUT' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/create_access_rule.rb0000644000004100000410000000117213411315054030472 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def create_access_rule(load_balancer_id, address, type) #TODO - This can actually support adding multiple access rules. data = { 'accessList' => [ { 'address' => address, 'type' => type } ]} request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => "loadbalancers/#{load_balancer_id}/accesslist" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/set_connection_logging.rb0000644000004100000410000000101013411315054031366 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def set_connection_logging(load_balancer_id, value) data = { 'connectionLogging' => { 'enabled' => value.to_s } } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/connectionlogging", :method => 'PUT' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/set_ssl_termination.rb0000644000004100000410000000167413411315054030753 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def set_ssl_termination(load_balancer_id, securePort, privatekey, certificate, options = {}) data = { :securePort => securePort, :privatekey => privatekey, :certificate => certificate } if options.key? :intermediate_certificate data['intermediateCertificate'] = options[:intermediate_certificate] end if options.key? :enabled data['enabled'] = options[:enabled] end if options.key? :secure_traffic_only data['secureTrafficOnly'] = options[:secure_traffic_only] end request( :body => Fog::JSON.encode(data), :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/ssltermination", :method => 'PUT' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/set_connection_throttling.rb0000644000004100000410000000127013411315054032146 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def set_connection_throttling(load_balancer_id, max_connections, min_connections, max_connection_rate, rate_interval) data = { 'maxConnections' => max_connections, 'minConnections' => min_connections, 'maxConnectionRate' => max_connection_rate, 'rateInterval' => rate_interval } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/connectionthrottle", :method => 'PUT' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_connection_throttling.rb0000644000004100000410000000051613411315054032134 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_connection_throttling(load_balancer_id) request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}/connectionthrottle", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/list_load_balancers.rb0000644000004100000410000000074013411315054030643 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def list_load_balancers(options = {}) if options.key? :node_address query_string = "?nodeaddress=#{options[:node_address]}" else query_string = '' end request( :expects => 200, :method => 'GET', :path => "loadbalancers.json?#{query_string}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_load_balancer.rb0000644000004100000410000000336613411315054030273 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_load_balancer(load_balancer_id) request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}.json", :method => 'GET' ) end end class Mock def get_load_balancer(load_balancer_id) response = Excon::Response.new response.status = 200 response.body = { "loadBalancer"=> { "name"=>"load_balancer_#{load_balancer_id}", "id"=> load_balancer_id, "protocol"=>"HTTP", "port"=>80, "algorithm"=>"RANDOM", "status"=>"ACTIVE", "cluster"=>{"name"=>"my-cluster.rackspace.net"}, "nodes"=>[{"address"=> MockData.ipv4_address, "id"=> Fog::Mock.random_numbers(6), "type"=>"PRIMARY", "port"=>80, "status"=>"ONLINE", "condition"=>"ENABLED"}], "timeout"=>30, "created"=>{"time"=>MockData.zulu_time}, "virtualIps"=>[ {"address"=> MockData.ipv4_address, "id"=>Fog::Mock.random_numbers(4), "type"=>"PUBLIC", "ipVersion"=>"IPV4"}, {"address"=> MockData.ipv6_address, "id"=>Fog::Mock.random_numbers(4), "type"=>"PUBLIC", "ipVersion"=>"IPV6"}], "sourceAddresses"=>{"ipv6Public"=> MockData.ipv6_address, "ipv4Servicenet"=> MockData.ipv4_address, "ipv4Public"=> MockData.ipv4_address}, "updated"=>{"time"=>"2013-09-04T06:29:09Z"}, "halfClosed"=>false, "connectionLogging"=>{"enabled"=>false}, "contentCaching"=>{"enabled"=>false}, "httpsRedirect"=>false}} response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/get_load_balancer_usage.rb0000644000004100000410000000115513411315054031451 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def get_load_balancer_usage(load_balancer_id, options = {}) #TODO - Didn't implement usage/current. Not sure if it is needed if options.key? :start_time and options.key? :end_time query = "?startTime=#{options[:start_time]}&endTime=#{options[:end_time]}" else query = '' end request( :expects => 200, :path => "loadbalancers/#{load_balancer_id}/usage#{query}", :method => 'GET' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/delete_load_balancer.rb0000644000004100000410000000077613411315054030760 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def delete_load_balancer(load_balancer_id) request( :expects => 202, :path => "loadbalancers/#{load_balancer_id}.json", :method => 'DELETE' ) end end class Mock def delete_load_balancer(load_balancer_id) response = Excon::Response.new response.status = 202 response.body = "" end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/create_load_balancer.rb0000644000004100000410000001012713411315054030750 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real # Issue an asynchronous request to create a new Load Balancer. # # @param name [String] human-friendly identifier for the balancer that will be shown in # the web UI. # @param protocol [String] well-known protocol describing the traffic to be load balanced. # @param port [Integer] port for the balancer to listen on and balance to. # @param virtual_ips [Array] description of the kind of IP address to bind to, or id # of the existing virtual IP from another balancer. Examples: `{ 'type' => 'PUBLIC' }`, # `{ 'type' => 'PRIVATE' }`, `{ 'id' => 1234 }` # @param nodes [Array] collection of # @option options [String] :algorithm balancing algorithm for the balancer to use. # See http://docs.rackspace.com/loadbalancers/api/v1.0/clb-devguide/content/Algorithms-d1e4367.html # @option options [String] :timeout amount of time the load balancer will wait for a response # from a back-end node before terminating the connection. Defaults to 30 seconds, may be # increased to a maximum of 120 seconds. # def create_load_balancer(name, protocol, port = nil, virtual_ips = [{'type' => 'PUBLIC'}], nodes = nil, options = {}) lb_data = { 'name' => name, 'protocol' => protocol, 'virtualIps' => virtual_ips } lb_data['nodes'] = nodes if nodes && !nodes.empty? lb_data['port'] = port if port lb_data['algorithm'] = options[:algorithm] if options.key? :algorithm lb_data['timeout'] = options[:timeout] if options.key? :timeout lb_data['httpsRedirect'] = options[:https_redirect] if options.key? :https_redirect data = { 'loadBalancer' => lb_data } request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'POST', :path => 'loadbalancers.json' ) end end class Mock def create_load_balancer(name, protocol, port, virtual_ips, nodes, options = {}) data = { "loadBalancer" => { "name" => name, "id" => Fog::Mock.random_numbers(6), "protocol" => protocol, "port" => port, "algorithm" => "RANDOM", "status" => "BUILD", "cluster" => { "name" => "my-cluster.rackspace.net" }, "timeout" => 30, "created" => {"time" => MockData.zulu_time }, "updated" => {"time" => MockData.zulu_time }, "halfClosed" => false, "connectionLogging" => { "enabled" => false }, "contentCaching" => { "enabled" => false }, "httpsRedirect" => false } } data["virtual_ips"] = virtual_ips.map do |n| { "virtualIps" => [ { "address" => MockData.ipv4_address, "id" => Fog::Mock.random_numbers(6), "type" => n.type, "ipVersion" => "IPV4" }, { "address" => MockData.ipv6_address, "id" => Fog::Mock.random_numbers(4), "type" => "PUBLIC", "ipVersion" => "IPV6" } ], "sourceAddresses" => { "ipv6Public" => MockData.ipv6_address, "ipv4Servicenet" => MockData.ipv4_address, "ipv4Public" => MockData.ipv4_address } } end data["nodes"] = nodes.map do |n| { "address" => n.address, "id" => Fog::Mock.random_numbers(6), "type" => "PRIMARY", "port" => n.port, "status" => "ONLINE", "condition" => "ENABLED", "weight" => 1 } end Excon::Response.new(:body => data, :status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/load_balancers/set_error_page.rb0000644000004100000410000000075713411315054027667 0ustar www-datawww-datamodule Fog module Rackspace class LoadBalancers class Real def set_error_page(load_balancer_id, content) data = { 'errorpage' => { 'content' => content } } request( :body => Fog::JSON.encode(data), :expects => [200, 202], :path => "loadbalancers/#{load_balancer_id}/errorpage", :method => 'PUT' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/0000755000004100000410000000000013411315054024216 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/delete_snapshot.rb0000644000004100000410000000176613411315054027736 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Delete snapshot # # @param [String] snapshot_id Id of snapshot to delete # @return [Excon::Response] response # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/POST_createSnapshot__v1__tenant_id__snapshots.html def delete_snapshot(snapshot_id) request( :expects => [202], :method => 'DELETE', :path => "snapshots/#{snapshot_id}" ) end end class Mock def delete_snapshot(snapshot_id) self.data[:snapshots].delete(snapshot_id) response(:status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/create_snapshot.rb0000644000004100000410000000653413411315054027735 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Create a snapshot from a volume # # @param [String] volume_id Id of server to create image from # @param [Hash] options # @option options [String] :display_name display name for snapshot # @option options [String] :display_description display description for snapshot # @option options [Boolean] :force Set to true to force service to create snapshot # @return [Excon::Response] response: # * body [Hash]: # * 'snapshot' [Hash]: # * 'volume_id' [String]: - the volume_id of the snapshot # * 'display_description' [String]: - display description of snapshot # * 'status' [String]: - status of snapshot # * 'id' [String]: - id of snapshot # * 'size' [Fixnum]: - size of the snapshot in GB # * 'display_name' [String]: - display name of snapshot # * 'created_at' [String]: - creation time of snapshot # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @note All writes to the volume should be flushed before creating the snapshot, either by un-mounting any file systems on the volume or by detaching the volume. # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/POST_createSnapshot__v1__tenant_id__snapshots.html def create_snapshot(volume_id, options = {}) data = { 'snapshot' => { 'volume_id' => volume_id } } data['snapshot']['display_name'] = options[:display_name] unless options[:display_name].nil? data['snapshot']['display_description'] = options[:display_description] unless options[:display_description].nil? data['snapshot']['force'] = options[:force] unless options[:force].nil? request( :body => Fog::JSON.encode(data), :expects => [200], :method => 'POST', :path => "snapshots" ) end end class Mock def create_snapshot(volume_id, options = {}) volume = self.data[:volumes][volume_id] if volume.nil? raise Fog::Rackspace::BlockStorage::NotFound else snapshot_id = Fog::Rackspace::MockData.uuid display_name = options[:display_name] || "test snapshot" display_description = options[:display_description] || "test snapshot description" snapshot = { "id" => snapshot_id, "display_name" => display_name, "display_description" => display_description, "volume_id" => volume_id, "status" => "available", "size" => volume["size"], "created_at" => Fog::Rackspace::MockData.zulu_time, "availability_zone" => "nova", } self.data[:snapshots][snapshot_id] = snapshot response(:body => {"snapshot" => snapshot}) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/create_volume.rb0000644000004100000410000001071113411315054027375 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Create volume # # @param [Integer] size size of volume in GB. Minimum size is 100 # @param [Hash] options # @option options [String] :display_name display name for volume # @option options [String] :display_description display description for volume # @option options [String] :volume_type type of volume # @option options [String] :snapshot_id The optional snapshot from which to create a volume. # @option options [String] :image_id The ID of an image from the compute service. If provided, a bootable volume will be # created. # @return [Excon::Response] response: # * body [Hash]: # * 'volume' [Hash]: # * 'volume_type' [String]: - type of volume # * 'display_description' [String]: - volume description # * 'metadata' [Hash]: - volume metadata # * 'availability_zone'[String]: - region of the volume # * 'status' [String]: - status of volume # * 'id' [String]: - id of volume # * 'attachments' [Array { 'size' => size } } data['volume']['display_name'] = options[:display_name] unless options[:display_name].nil? data['volume']['display_description'] = options[:display_description] unless options[:display_description].nil? data['volume']['volume_type'] = options[:volume_type] unless options[:volume_type].nil? data['volume']['availability_zone'] = options[:availability_zone] unless options[:availability_zone].nil? data['volume']['snapshot_id'] = options[:snapshot_id] unless options[:snapshot_id].nil? data['volume']['imageRef'] = options[:image_id] unless options[:image_id].nil? request( :body => Fog::JSON.encode(data), :expects => [200], :method => 'POST', :path => "volumes" ) end end class Mock def create_volume(size, options = {}) if size < 1 && !options[:snapshot_id] raise Fog::Rackspace::BlockStorage::BadRequest elsif size < 100 || size > 1024 raise Fog::Rackspace::BlockStorage::BadRequest.new("'size' parameter must be between 100 and 1024") else volume_id = Fog::Rackspace::MockData.uuid name = options[:display_name] || "test volume" description = options[:display_description] || "description goes here" volume_type = options[:volume_type] || "SATA" volume = { "id" => volume_id, "display_name" => name, "display_description" => description, "size" => size, "status" => "available", "volume_type" => volume_type, "snapshot_id" => nil, "attachments" => [], "created_at" => Fog::Rackspace::MockData.zulu_time, "availability_zone" => "nova", "metadata" => {}, } if snapshot_id = options[:snapshot_id] snapshot = self.data[:snapshots][snapshot_id] volume.merge!("size" => snapshot["size"]) end volume["image_id"] = options[:image_id] if options[:image_id] self.data[:volumes][volume_id] = volume response(:body => {"volume" => volume}) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/list_volumes.rb0000644000004100000410000000331213411315054027267 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Retrieves list of volumes # @return [Excon::Response] response: # * body [Hash]: # * 'volumes' [Array]: - # * 'volume_type' [String]: - volume type # * 'display_description' [String]: - display desciption for volume # * 'metadata' [Hash]: - metadata for volume # * 'availability_zone' [String]: - region for volume # * 'status' [String]: - status of volume # * 'id' [String]: - id of volume # * 'attachments' [Array]: - array of hashes containing attachment information # * 'size' [Fixnum]: - size of volume in GB (100 GB minimum) # * 'snapshot_id' [String]: - optional snapshot from which to create a volume. # * 'display_name' [String]: - display name of bolume # * 'created_at' [String]: - volume creation time # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getVolumesSimple__v1__tenant_id__volumes.html def list_volumes request( :expects => [200], :method => 'GET', :path => 'volumes' ) end end class Mock def list_volumes volumes = self.data[:volumes].values response(:body => {"volumes" => volumes}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/list_volume_types.rb0000644000004100000410000000217213411315054030333 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Retrieves list of volume types # @return [Excon::Response] response # * body [Hash]: # * 'volume_types' [Array]: - # * 'name' [String]: - name of volume type # * 'extra_specs' [Hash]: - # * 'id' [Fixnum]: - id of volume type # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getVolumeTypes__v1__tenant_id__types.html def list_volume_types request( :expects => [200], :method => 'GET', :path => 'types' ) end end class Mock def list_volume_types types = self.data[:volume_types].values response(:body => {"volume_types" => types}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/list_snapshots.rb0000644000004100000410000000266513411315054027631 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Retrieves list of snapshots # @return [Excon::Response] response: # * body [Hash]: # * 'snapshots' [Array]: - # * 'volume_id' [String]: - volume_id of the snapshot # * 'display_description' [String]: - display description of snapshot # * 'status' [String]: - status of snapshot # * 'id' [String]: - id of snapshot # * 'size' [Fixnum]: - size of the snapshot in GB # * 'display_name' [String]: - display name of snapshot # * 'created_at' [String]: - creation time of snapshot # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getSnapshotsSimple__v1__tenant_id__snapshots.html def list_snapshots request( :expects => [200], :method => 'GET', :path => 'snapshots' ) end end class Mock def list_snapshots snapshots = self.data[:snapshots].values response(:body => {"snapshots" => snapshots}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/get_volume.rb0000644000004100000410000000434613411315054026720 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Retrieves volume detail # @param [String] volume_id # @return [Excon::Response] response: # * body [Hash]: # * 'volume' [Hash]: # * 'volume_type' [String]: - volume type # * 'display_description' [String]: - volume display description # * 'metadata' [Hash]: - volume metadata # * 'availability_zone' [String]: - region of volume # * 'status' [String]: - status of volume # * 'id' [String]: - id of volume # * 'attachments' [Array [200], :method => 'GET', :path => "volumes/#{volume_id}" ) end end class Mock def get_volume(volume_id) possible_states = ["available", "in-use"] volume = self.data[:volumes][volume_id] if volume.nil? raise Fog::Rackspace::BlockStorage::NotFound else volume["status"] = possible_states[rand(possible_states.length)] if volume.nil? raise Fog::Rackspace::BlockStorage::NotFound else response(:body => {"volume" => volume}) end end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/get_snapshot.rb0000644000004100000410000000336413411315054027247 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Retrieves snapshot detail # @param [String] snapshot_id # @return [Excon::Response] response: # * body [Hash]: # * 'snapshot' [Hash]: # * 'volume_id' [String]: - volume_id of the snapshot # * 'display_description' [String]: - snapshot display description # * 'status' [String]: - snapshot status # * 'os-extended-snapshot-attributes:project_id' [String]: - # * 'id' [String]: - snapshot id # * 'size' [Fixnum]: - size of the snapshot in GB # * 'os-extended-snapshot-attributes:progress' [String]: - # * 'display_name' [String]: - display name of snapshot # * 'created_at' [String]: - creation time of snapshot # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getSnapshot__v1__tenant_id__snapshots.html def get_snapshot(snapshot_id) request( :expects => [200], :method => 'GET', :path => "snapshots/#{snapshot_id}" ) end end class Mock def get_snapshot(snapshot_id) snapshot = self.data[:snapshots][snapshot_id] if snapshot.nil? raise Fog::Rackspace::BlockStorage::NotFound else response(:body => {"snapshot" => snapshot}) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/delete_volume.rb0000644000004100000410000000320213411315054027371 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Delete volume # # @param [String] volume_id Id of volume to delete # @return [Excon::Response] response # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @note You cannot delete a volume until all of its dependent snaphosts have been deleted. # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/DELETE_deleteVolume__v1__tenant_id__volumes.html def delete_volume(volume_id) request( :expects => [202], :method => 'DELETE', :path => "volumes/#{volume_id}" ) end end class Mock def delete_volume(volume_id) volume = self.data[:volumes][volume_id] snapshots = self.data[:snapshots].values.select { |s| s["volume_id"] == volume_id } raise Fog::Rackspace::BlockStorage::BadRequest.new("Volume still has #{snapshots.count} dependent snapshots") if !snapshots.empty? unless volume.nil? unless volume["attachments"].empty? raise Fog::Rackspace::BlockStorage::BadRequest.new("Volume status must be available or error") end self.data[:volumes].delete(volume_id) response(:status => 202) else raise Fog::Rackspace::BlockStorage::NotFound end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/block_storage/get_volume_type.rb0000644000004100000410000000260713411315054027757 0ustar www-datawww-datamodule Fog module Rackspace class BlockStorage class Real # Retrieves volume type detail # @param [String] volume_type_id # @return [Excon::Response] response: # * body [Hash]: # * 'volume_type' [Hash]: - # * 'name' [String]: - name of volume type # * 'extra_specs' [Hash]: - # * 'id' [String]: - id of volume type # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getVolumeType__v1__tenant_id__types.html def get_volume_type(volume_type_id) request( :expects => [200], :method => 'GET', :path => "types/#{volume_type_id}" ) end end class Mock def get_volume_type(volume_type_id) type = self.data[:volume_types][volume_type_id] if type.nil? raise Fog::Rackspace::BlockStorage::NotFound else type = type.dup type["id"] = type["id"].to_s response(:body => {"volume_type" => type}) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/0000755000004100000410000000000013411315054023054 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/get_image_details.rb0000644000004100000410000000132513411315054027030 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Get details for image by id # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> - Id of the image # * 'name'<~String> - Name of the image # * 'serverId'<~Integer> - Id of server image was created from # * 'status'<~Integer> - Status of image # * 'updated'<~String> - Timestamp of last update def get_image_details(image_id) request( :expects => [200, 203], :method => 'GET', :path => "images/#{image_id}.json" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/resize_server.rb0000644000004100000410000000207513411315054026274 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Reboot an existing server # # ==== Parameters # * server_id<~Integer> - Id of server to resize # * size<~String> - new size. call list_flavors to get available flavors # def resize_server(server_id, flavor_id) body = { 'resize' => { 'flavorId' => flavor_id }} server_action(server_id, body) end end class Mock # FIXME: should probably transition instead of skipping to VERIFY_RESIZE def resize_server(server_id, flavor_id) response = Excon::Response.new response.status = 202 # keep track of this for reverts self.data[:servers][server_id]['old_flavorId'] = self.data[:servers][server_id]['flavorId'] self.data[:servers][server_id]['flavorId'] = flavor_id self.data[:last_modified][:servers][server_id] = Time.now self.data[:servers][server_id]['status'] = 'VERIFY_RESIZE' response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/list_servers_detail.rb0000644000004100000410000000311513411315054027447 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # List all servers details # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'servers'<~Array>: # * 'id'<~Integer> - Id of server # * 'name<~String> - Name of server # * 'imageId'<~Integer> - Id of image used to boot server # * 'flavorId'<~Integer> - Id of servers current flavor # * 'hostId'<~String> # * 'status'<~String> - Current server status # * 'progress'<~Integer> - Progress through current status # * 'addresses'<~Hash>: # * 'public'<~Array> - public address strings # * 'private'<~Array> - private address strings # * 'metadata'<~Hash> - metadata def list_servers_detail request( :expects => [200, 203], :method => 'GET', :path => 'servers/detail.json' ) end end class Mock def list_servers_detail response = Excon::Response.new servers = self.data[:servers].values for server in servers case server['status'] when 'BUILD' if Time.now - self.data[:last_modified][:servers][server['id']] > Fog::Mock.delay * 2 server['status'] = 'ACTIVE' end end end response.status = [200, 203][rand(1)] response.body = { 'servers' => servers } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/list_flavors_detail.rb0000644000004100000410000000275213411315054027440 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # List all flavors # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> - Id of the flavor # * 'name'<~String> - Name of the flavor # * 'ram'<~Integer> - Amount of ram for the flavor # * 'disk'<~Integer> - Amount of diskspace for the flavor def list_flavors_detail request( :expects => [200, 203], :method => 'GET', :path => 'flavors/detail.json' ) end end class Mock def list_flavors_detail response = Excon::Response.new response.status = 200 response.body = { 'flavors' => [ { 'name' => '256 server', 'id' => 1, 'ram' => 256, 'disk' => 10 }, { 'name' => '512 server', 'id' => 2, 'ram' => 512, 'disk' => 20 }, { 'name' => '1GB server', 'id' => 3, 'ram' => 1024, 'disk' => 40 }, { 'name' => '2GB server', 'id' => 4, 'ram' => 2048, 'disk' => 80 }, { 'name' => '4GB server', 'id' => 5, 'ram' => 4096, 'disk' => 160 }, { 'name' => '8GB server', 'id' => 6, 'ram' => 8192, 'disk' => 320 }, { 'name' => '15.5GB server', 'id' => 7, 'ram' => 15872, 'disk' => 620 } ] } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/list_images.rb0000644000004100000410000000164613411315054025710 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # List all images (IDs and names only) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> - Id of the image # * 'name'<~String> - Name of the image def list_images request( :expects => [200, 203], :method => 'GET', :path => 'images.json' ) end end class Mock def list_images response = Excon::Response.new data = list_images_detail.body['images'] images = [] for image in data images << image.reject { |key, value| !['id', 'name'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'images' => images } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/revert_resized_server.rb0000644000004100000410000000150613411315054030025 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Revert resizing # # ==== Parameters # * server_id<~Integer> - Id of server to revert # def revert_resized_server(server_id) body = { 'revertResize' => nil } server_action(server_id, body) end end class Mock def revert_resized_server(server_id) response = Excon::Response.new response.status = 202 self.data[:servers][server_id]['flavorId'] = self.data[:servers][server_id]['old_flavorId'] self.data[:servers][server_id].delete('old_flavorId') self.data[:last_modified][:servers][server_id] = Time.now self.data[:servers][server_id]['status'] = 'ACTIVE' response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/list_public_addresses.rb0000644000004100000410000000203713411315054027751 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # List public server addresses # # ==== Parameters # * server_id<~Integer> - Id of server to list addresses for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'public'<~Array> - Public ip addresses def list_public_addresses(server_id) request( :expects => [200, 203], :method => 'GET', :path => "servers/#{server_id}/ips/public.json" ) end end class Mock def list_public_addresses(server_id) response = Excon::Response.new if server = list_servers_detail.body['servers'].find {|_| _['id'] == server_id} response.status = [200, 203][rand(1)] response.body = { 'public' => server['addresses']['public'] } response else raise Fog::Compute::Rackspace::NotFound end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/server_action.rb0000644000004100000410000000126713411315054026252 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Reboot an existing server # # ==== Parameters # * server_id<~Integer> - Id of server to reboot # * body<~String> - Body of the request, describes the action (see reboot_server as an example) # * expect<~Integer> - expected return, 202 except for confirm resize (204) # def server_action(server_id, body, expects=202) request( :body => Fog::JSON.encode(body), :expects => expects, :method => 'POST', :path => "servers/#{server_id}/action.json" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/create_image.rb0000644000004100000410000000316313411315054026011 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Create an image from a running server # # ==== Parameters # * server_id<~Integer> - Id of server to create image from # * options<~Hash> - Name # # ==== Returns # * response<~Excon::Response>: # * 'image'<~Hash>: # * 'id'<~Integer> - Id of image # * 'name'<~String> - Name of image # * 'serverId'<~Integer> - Id of server def create_image(server_id, options = {}) data = { 'image' => { 'serverId' => server_id } } data['image'].merge!(options) request( :body => Fog::JSON.encode(data), :expects => 202, :method => 'POST', :path => "images" ) end end class Mock def create_image(server_id, options = {}) response = Excon::Response.new response.status = 202 now = Time.now data = { 'created' => now, 'id' => Fog::Mock.random_numbers(6).to_i, 'name' => options['name'] || '', 'serverId' => server_id, 'status' => 'SAVING', 'updated' => now.to_s, } self.data[:last_modified][:images][data['id']] = now self.data[:images][data['id']] = data response.body = { 'image' => data.reject {|key, value| !['id', 'name', 'serverId', 'status', 'updated'].include?(key)} } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/reboot_server.rb0000644000004100000410000000120413411315054026256 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Reboot an existing server # # ==== Parameters # * server_id<~Integer> - Id of server to reboot # * type<~String> - Type of reboot, must be in ['HARD', 'SOFT'] # def reboot_server(server_id, type = 'SOFT') body = { 'reboot' => { 'type' => type }} server_action(server_id, body) end end class Mock def reboot_server(server_id, type = 'SOFT') response = Excon::Response.new response.status = 202 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/list_servers.rb0000644000004100000410000000171413411315054026130 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # List all servers (IDs and names only) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'servers'<~Array>: # * 'id'<~Integer> - Id of server # * 'name<~String> - Name of server def list_servers request( :expects => [200, 203], :method => 'GET', :path => 'servers.json' ) end end class Mock def list_servers response = Excon::Response.new data = list_servers_detail.body['servers'] servers = [] for server in data servers << server.reject { |key, value| !['id', 'name'].include?(key) } end response.status = [200, 203][rand(1)] response.body = { 'servers' => servers } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/create_server.rb0000644000004100000410000000652013411315054026235 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Create a new server # # ==== Parameters # * flavor_id<~Integer> - Id of flavor for server # * image_id<~Integer> - Id of image for server # * name<~String> - Name of server # * options<~Hash>: # * 'metadata'<~Hash> - Up to 5 key value pairs containing 255 bytes of info # * 'name'<~String> - Name of server, defaults to "slice#{id}" # * 'personality'<~Array>: Up to 5 files to customize server # * file<~Hash>: # * 'contents'<~String> - Contents of file (10kb total of contents) # * 'path'<~String> - Path to file (255 bytes total of path strings) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'server'<~Hash>: # * 'addresses'<~Hash>: # * 'public'<~Array> - public address strings # * 'private'<~Array> - private address strings # * 'adminPass'<~String> - Admin password for server # * 'flavorId'<~Integer> - Id of servers current flavor # * 'hostId'<~String> # * 'id'<~Integer> - Id of server # * 'imageId'<~Integer> - Id of image used to boot server # * 'metadata'<~Hash> - metadata # * 'name<~String> - Name of server # * 'progress'<~Integer> - Progress through current status # * 'status'<~String> - Current server status def create_server(flavor_id, image_id, options = {}) data = { 'server' => { 'flavorId' => flavor_id, 'imageId' => image_id } } if options['metadata'] data['server']['metadata'] = options['metadata'] end if options['name'] data['server']['name'] = options['name'] end if options['personality'] data['server']['personality'] = [] for file in options['personality'] data['server']['personality'] << { 'contents' => Base64.encode64(file['contents']), 'path' => file['path'] } end end request( :body => Fog::JSON.encode(data), :expects => [200, 202], :method => 'POST', :path => 'servers.json' ) end end class Mock def create_server(flavor_id, image_id, options = {}) response = Excon::Response.new response.status = 202 data = { 'addresses' => { 'private' => ['0.0.0.0'], 'public' => ['0.0.0.0'] }, 'flavorId' => flavor_id, 'id' => Fog::Mock.random_numbers(6).to_i, 'imageId' => image_id, 'hostId' => "123456789ABCDEF01234567890ABCDEF", 'metadata' => options['metadata'] || {}, 'name' => options['name'] || "server_#{rand(999)}", 'progress' => 0, 'status' => 'BUILD' } self.data[:last_modified][:servers][data['id']] = Time.now self.data[:servers][data['id']] = data response.body = { 'server' => data.merge({'adminPass' => 'password'}) } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/list_images_detail.rb0000644000004100000410000000247313411315054027231 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # List all images # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> - Id of the image # * 'name'<~String> - Name of the image # * 'updated'<~String> - Last update timestamp for image # * 'created'<~String> - Creation timestamp for image # * 'status'<~String> - Status of image def list_images_detail request( :expects => [200, 203], :method => 'GET', :path => 'images/detail.json' ) end end class Mock def list_images_detail response = Excon::Response.new images = self.data[:images].values for image in images case image['status'] when 'SAVING' if Time.now - self.data[:last_modified][:images][image['id']] >= Fog::Mock.delay image['status'] = 'ACTIVE' end end end response.status = [200, 203][rand(1)] response.body = { 'images' => images.map {|image| image.reject {|key, value| !['id', 'name', 'status', 'updated'].include?(key)}} } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/get_flavor_details.rb0000644000004100000410000000315113411315054027236 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Get details for flavor by id # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> - Id of the flavor # * 'name'<~String> - Name of the flavor # * 'ram'<~Integer> - Amount of ram for the flavor # * 'disk'<~Integer> - Amount of diskspace for the flavor def get_flavor_details(flavor_id) request( :expects => [200, 203], :method => 'GET', :path => "flavors/#{flavor_id}.json" ) end end class Mock def get_flavor_details(flavor_id) response = Excon::Response.new flavor = { 1 => { 'name' => '256 server', 'ram' => 256, 'disk' => 10 }, 2 => { 'name' => '512 server', 'ram' => 512, 'disk' => 20 }, 3 => { 'name' => '1GB server', 'ram' => 1024, 'disk' => 40 }, 4 => { 'name' => '2GB server', 'ram' => 2048, 'disk' => 80 }, 5 => { 'name' => '4GB server', 'ram' => 4096, 'disk' => 160 }, 6 => { 'name' => '8GB server', 'ram' => 8192, 'disk' => 320 }, 7 => { 'name' => '15.5GB server', 'ram' => 15872, 'disk' => 620 } }[flavor_id] if flavor response.status = 200 response.body = { 'flavor' => flavor } response else raise Fog::Compute::Rackspace::NotFound end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/get_server_details.rb0000644000004100000410000000307213411315054027255 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Get details about a server # # ==== Parameters # * server_id<~Integer> - Id of server to get details for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'server'<~Hash>: # * 'addresses'<~Hash>: # * 'public'<~Array> - public address strings # * 'private'<~Array> - private address strings # * 'flavorId'<~Integer> - Id of servers current flavor # * 'hostId'<~String> # * 'id'<~Integer> - Id of server # * 'imageId'<~Integer> - Id of image used to boot server # * 'metadata'<~Hash> - metadata # * 'name<~String> - Name of server # * 'progress'<~Integer> - Progress through current status # * 'status'<~String> - Current server status def get_server_details(server_id) request( :expects => [200, 203], :method => 'GET', :path => "servers/#{server_id}.json" ) end end class Mock def get_server_details(server_id) response = Excon::Response.new if server = list_servers_detail.body['servers'].find {|_| _['id'].to_s == server_id.to_s} response.status = [200, 203][rand(1)] response.body = { 'server' => server } response else raise Fog::Compute::Rackspace::NotFound end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/delete_image.rb0000644000004100000410000000210413411315054026002 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Delete an image # # ==== Parameters # * image_id<~Integer> - Id of image to delete # def delete_image(image_id) request( :expects => 204, :method => 'DELETE', :path => "images/#{image_id}" ) end end class Mock def delete_image(image_id) response = Excon::Response.new if image = list_images_detail.body['images'].find {|_| _['id'] == image_id} if image['status'] == 'SAVING' response.status = 409 raise(Excon::Errors.status_error({:expects => 202}, response)) else self.data[:last_modified][:images].delete(image_id) self.data[:images].delete(image_id) response.status = 202 end response else response.status = 400 raise Fog::Compute::Rackspace::NotFound.new end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/update_server.rb0000644000004100000410000000225613411315054026256 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Update an existing server # # ==== Parameters # # server_id<~Integer> - Id of server to update # * options<~Hash>: # * adminPass<~String> - New admin password for server # * name<~String> - New name for server def update_server(server_id, options = {}) request( :body => Fog::JSON.encode({ 'server' => options }), :expects => 204, :method => 'PUT', :path => "servers/#{server_id}.json" ) end end class Mock def update_server(server_id, options) response = Excon::Response.new if server = list_servers_detail.body['servers'].find {|_| _['id'] == server_id} if options['adminPass'] server['adminPass'] = options['adminPass'] end if options['name'] server['name'] = options['name'] end response.status = 204 response else raise Fog::Compute::Rackspace::NotFound end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/list_flavors.rb0000644000004100000410000000217613411315054026116 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # List all flavors (IDs and names only) # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'id'<~Integer> - Id of the flavor # * 'name'<~String> - Name of the flavor def list_flavors request( :expects => [200, 203], :method => 'GET', :path => 'flavors.json' ) end end class Mock def list_flavors response = Excon::Response.new response.status = 200 response.body = { 'flavors' => [ { 'name' => '256 server', 'id' => 1 }, { 'name' => '512 server', 'id' => 2 }, { 'name' => '1GB server', 'id' => 3 }, { 'name' => '2GB server', 'id' => 4 }, { 'name' => '4GB server', 'id' => 5 }, { 'name' => '8GB server', 'id' => 6 }, { 'name' => '15.5GB server', 'id' => 7 } ] } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/delete_server.rb0000644000004100000410000000205413411315054026232 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Delete an existing server # # ==== Parameters # * id<~Integer> - Id of server to delete # def delete_server(server_id) request( :expects => 202, :method => 'DELETE', :path => "servers/#{server_id}" ) end end class Mock def delete_server(server_id) response = Excon::Response.new if server = list_servers_detail.body['servers'].find {|_| _['id'] == server_id} if server['status'] == 'BUILD' response.status = 409 raise(Excon::Errors.status_error({:expects => 202}, response)) else self.data[:last_modified][:servers].delete(server_id) self.data[:servers].delete(server_id) response.status = 202 end response else raise Fog::Compute::Rackspace::NotFound end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/confirm_resized_server.rb0000644000004100000410000000135213411315054030152 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # Confirm resizing # # ==== Parameters # * server_id<~Integer> - Id of server to confirm # def confirm_resized_server(server_id) body = { 'confirmResize' => nil } server_action(server_id, body, 204) end end class Mock def confirm_resized_server(server_id) response = Excon::Response.new response.status = 204 self.data[:servers][server_id].delete('old_flavorId') self.data[:last_modified][:servers][server_id] = Time.now self.data[:servers][server_id]['status'] = 'ACTIVE' response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/list_addresses.rb0000644000004100000410000000213413411315054026411 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # List all server addresses # # ==== Parameters # * server_id<~Integer> - Id of server to list addresses for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'addresses'<~Array>: # * 'public'<~Array> - Public ip addresses # * 'private'<~Array> - Private ip addresses def list_addresses(server_id) request( :expects => [200, 203], :method => 'GET', :path => "servers/#{server_id}/ips.json" ) end end class Mock def list_addresses(server_id) response = Excon::Response.new if server = list_servers_detail.body['servers'].find {|_| _['id'] == server_id} response.status = [200, 203][rand(1)] response.body = { 'addresses' => server['addresses'] } response else raise Fog::Compute::Rackspace::NotFound end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/compute/list_private_addresses.rb0000644000004100000410000000204613411315054030145 0ustar www-datawww-datamodule Fog module Compute class Rackspace class Real # List private server addresses # # ==== Parameters # * server_id<~Integer> - Id of server to list addresses for # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'private'<~Array> - Public ip addresses def list_private_addresses(server_id) request( :expects => [200, 203], :method => 'GET', :path => "servers/#{server_id}/ips/private.json" ) end end class Mock def list_private_addresses(server_id) response = Excon::Response.new if server = list_servers_detail.body['servers'].find {|_| _['id'] == server_id} response.status = [200, 203][rand(1)] response.body = { 'private' => server['addresses']['private'] } response else raise Fog::Compute::Rackspace::NotFound end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/0000755000004100000410000000000013411315054024264 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/list_stack_data.rb0000644000004100000410000000071613411315054027746 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def list_stack_data(options={}) request( :method => 'GET', :path => request_uri("stacks", options), :expects => 200 ) end end class Mock def list_stack_data stacks = self.data[:stacks].values response(:body => { 'stacks' => stacks }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/create_stack.rb0000644000004100000410000000051213411315054027237 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def create_stack(options={}) request( :body => Fog::JSON.encode(options), :expects => [201], :method => 'POST', :path => "stacks" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/show_resource_metadata.rb0000644000004100000410000000106613411315054031343 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def show_resource_metadata(stack, resource_name) request( :method => 'GET', :path => "stacks/#{stack.stack_name}/#{stack.id}/resources/#{resource_name}/metadata", :expects => 200 ) end end class Mock def show_resource_metadata(stack, resource_name) resources = self.data[:resources].values response(:body => { 'resources' => resources }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/abandon_stack.rb0000644000004100000410000000047113411315054027402 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def abandon_stack(stack) request( :expects => [200], :method => 'DELETE', :path => "stacks/#{stack.stack_name}/#{stack.id}/abandon" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/list_resource_types.rb0000644000004100000410000000072213411315054030720 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def list_resource_types request( :method => 'GET', :path => "resource_types", :expects => 200 ) end end class Mock def list_resource_types resources = self.data[:resource_types].values response(:body => { 'resource_types' => resources }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/list_stack_events.rb0000644000004100000410000000074013411315054030336 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def list_stack_events(stack, options={}) uri = request_uri("stacks/#{stack.stack_name}/#{stack.id}/events", options) request(:method => 'GET', :path => uri, :expects => 200) end end class Mock def list_stack_events events = self.data[:events].values response(:body => { 'events' => events }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/show_stack_details.rb0000644000004100000410000000072013411315054030462 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def show_stack_details(name, id) request( :method => 'GET', :path => "stacks/#{name}/#{id}", :expects => 200 ) end end class Mock def show_stack_details(name, id) stack = self.data[:stack].values response(:body => { 'stack' => stack }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/show_resource_data.rb0000644000004100000410000000107513411315054030474 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def show_resource_data(stack_name, stack_id, resource_name) request( :method => 'GET', :path => "stacks/#{stack_name}/#{stack_id}/resources/#{resource_name}", :expects => 200 ) end end class Mock def show_resource_data(stack_name, stack_id, resource_name) resources = self.data[:resources].values response(:body => { 'resources' => resources }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/build_info.rb0000644000004100000410000000041013411315054026716 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def build_info request( :expects => [200], :method => 'GET', :path => 'build_info' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/update_stack.rb0000644000004100000410000000056213411315054027263 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def update_stack(stack, options = {}) request( :body => Fog::JSON.encode(options), :expects => [202], :method => 'PUT', :path => "stacks/#{stack.stack_name}/#{stack.id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/show_resource_schema.rb0000644000004100000410000000044213411315054031020 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def show_resource_schema(name) request( :method => 'GET', :path => "resource_types/#{name}", :expects => 200 ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/show_event_details.rb0000644000004100000410000000106213411315054030476 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def show_event_details(stack, resource, event_id) request( :method => 'GET', :path => "stacks/#{stack.stack_name}/#{stack.id}/resources/#{resource.resource_name}/events/#{event_id}", :expects => 200 ) end end class Mock def show_event_details(stack, event) events = self.data[:events].values response(:body => { 'events' => events }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/list_resource_events.rb0000644000004100000410000000102113411315054031051 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def list_resource_events(stack, resource, options={}) uri = request_uri("stacks/#{stack.stack_name}/#{stack.id}/resources/#{resource.resource_name}/events", options) request(:method => 'GET', :path => uri, :expects => 200) end end class Mock def list_stack_events events = self.data[:events].values response(:body => { 'events' => events }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/delete_stack.rb0000644000004100000410000000046013411315054027240 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def delete_stack(stack) request( :expects => [204], :method => 'DELETE', :path => "stacks/#{stack.stack_name}/#{stack.id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/preview_stack.rb0000644000004100000410000000052513411315054027461 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def preview_stack(options = {}) request( :body => Fog::JSON.encode(options), :expects => [200], :method => 'POST', :path => 'stacks/preview' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/show_resource_template.rb0000644000004100000410000000057613411315054031403 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def show_resource_template(name) request( :method => 'GET', :path => "resource_types/#{name}/template", :expects => 200 ) end end class Mock def show_resource_template(name) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/list_resources.rb0000644000004100000410000000076013411315054027661 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def list_resources(stack, options={}) uri = request_uri("stacks/#{stack.stack_name}/#{stack.id}/resources", options) request(:method => 'GET', :path => uri, :expects => 200) end end class Mock def list_resources(stack) resources = self.data[:resources].values response(:body => { 'resources' => resources }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/get_stack_template.rb0000644000004100000410000000061013411315054030445 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def get_stack_template(stack) request( :method => 'GET', :path => "stacks/#{stack.stack_name}/#{stack.id}/template", :expects => 200 ) end end class Mock def get_stack_template(stack) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/orchestration/validate_template.rb0000644000004100000410000000052313411315054030275 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Real def validate_template(options = {}) request( :body => Fog::JSON.encode(options), :expects => [200], :method => 'POST', :path => 'validate' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/0000755000004100000410000000000013411315054023565 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/delete_check.rb0000644000004100000410000000241213411315054026510 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def delete_check(entity_id, check_id) request( :expects => [204], :method => 'DELETE', :path => "entities/#{entity_id}/checks/#{check_id}" ) end end class Mock def delete_check(entity_id, check_id) if entity_id == -1 || check_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 204 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => ".rh-lHJL.h-ord1-maas-prod-api1.r-AGRIH406.c-4085336.ts-1377785008661.v-e602877", "X-LB" => "ord1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain", } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_logged_in_user_info.rb0000644000004100000410000000336713411315054030762 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_logged_in_user_info(agent_id) request( :expects => [200, 203], :method => 'GET', :path => "agents/#{agent_id}/host_info/who" ) end end class Mock def get_logged_in_user_info(agent_id) if agent_id == -1 raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 200 response.body = { "info" => [ { "user" => "root", "device" => "pts/1", "time" => Time.now.to_i - 100, "host" => "somehost1.company.local" }, { "user" => "user123", "device" => "pts/2", "time" => Time.now.to_i - 50, "host" => "somehost2.company.local" } ] } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_agents.rb0000644000004100000410000000334213411315054026430 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_agents request( :expects => [200, 203], :method => 'GET', :path => "agents" ) end end class Mock def list_agents response = Excon::Response.new response.status = 200 response.body = { "values"=>[ { "id" => Fog::Rackspace::MockData.uuid, "last_connected" => Time.now.to_i - 100 }, { "id" => Fog::Rackspace::MockData.uuid, "last_connected" => Time.now.to_i - 110 }, { "id" => Fog::Rackspace::MockData.uuid, "last_connected" => Time.now.to_i - 120 } ], "metadata" => { "count" => 1, "limit" => 100, "marker" => nil, "next_marker" => nil, "next_href" => nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_check.rb0000644000004100000410000000374313411315054026035 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_check(entity_id, check_id) request( :expects => [200, 203], :method => 'GET', :path => "entities/#{entity_id}/checks/#{check_id}" ) end end class Mock def get_check(entity_id, check_id) if entity_id == -1 || check_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 200 response.body = { "id" => check_id, "label" => nil, "type" => "remote.ping", "details" => {"count"=>5}, "monitoring_zones_poll" => ["mzord", "mzdfw", "mziad"], "timeout" => 10, "period" => 30, "target_alias" => nil, "target_hostname" => "1.1.1.1", "target_resolver" => "IPv4", "disabled" => false, "metadata" => nil, "created_at" => Time.now.to_i - 1, "updated_at" => Time.now.to_i }, response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "44676", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "jdnbono34090934nggn", "X-LB" => "ord1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_checks.rb0000644000004100000410000000440013411315054026403 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_checks(entity_id, options={}) request( :expects => [200, 203], :method => 'GET', :path => "entities/#{entity_id}/checks", :query => options ) end end class Mock def list_checks(entity_id) check_id = Fog::Mock.random_letters(10) if entity_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 200 response.body = { "values" => [ { "id" => check_id, "label" => "load", "type" => "agent.load_average", "details" => {}, "monitoring_zones_poll" => nil, "timeout" => 10, "period" => 30, "target_alias" => nil, "target_hostname" => nil, "target_resolver" => nil, "disabled" => false, "metadata" => nil, "created_at" => Time.now.to_i - 1, "updated_at" => Time.now.to_i } ], "metadata" => { "count" => 1, "limit" => 100, "marker" => nil, "next_marker" => nil, "next_href" => nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/delete_agent_token.rb0000644000004100000410000000270713411315054027740 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def delete_agent_token(token_id) request( :expects => [204], :method => 'DELETE', :path => "agent_tokens/#{token_id}" ) end end class Mock def delete_agent_token(options = {}) account_id = Fog::Mock.random_numbers(6).to_s token = Fog::Mock.random_letters(50).to_s if options == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 201 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "Location" => "https://monitoring.api.rackspacecloud.com/v1.0/" + account_id + "/agent_tokens/" + token, "X-Object-ID" => token, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "lsknvnslnv2083ovnsdbno00", "X-LB" => "ord1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain", } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_monitoring_zones.rb0000644000004100000410000000043113411315054030546 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_monitoring_zones request( :expects => [200], :method => 'GET', :path => "monitoring_zones" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/create_notification.rb0000644000004100000410000000055413411315054030127 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def create_notification(options = {}) data = options.dup request( :body => JSON.encode(data), :expects => [201], :method => 'POST', :path => 'notifications' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/update_alarm.rb0000644000004100000410000000305413411315054026552 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def update_alarm(entity_id, alarm_id, options) request( :body => JSON.encode(options), :expects => [204], :method => 'PUT', :path => "entities/#{entity_id}/alarms/#{alarm_id}" ) end end class Mock def update_alarm(entity_id, alarm_id, options) account_id = Fog::Mock.random_numbers(6).to_s if entity_id == -1 || alarm_id == -1 || options[:testing] raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 204 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "Location" => "https://monitoring.api.rackspacecloud.com/v1.0/" + account_id + "/entities/" + entity_id.to_s + "/alarms/" + alarm_id, "X-Object-ID" => alarm_id, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "47877", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "laolsgggopsnfksdovnsv", "X-LB" => "dfw1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_data_points.rb0000644000004100000410000000327513411315054027461 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_data_points(entity_id, check_id, metric_name, options) request( :expects => [200, 203], :method => 'GET', :path => "entities/#{entity_id}/checks/#{check_id}/metrics/#{metric_name}/plot", :query => options ) end end class Mock def list_data_points(entity_id, check_id, metric_name, options) if entity_id == -1 || check_id == -1 || metric_name == -1 || options == -1 raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 200 response.body = { "values" => [], "metadata"=> { "count" =>0, "limit" =>nil, "marker" =>nil, "next_marker" =>nil, "next_href" =>nil } } response.headers = { "Date" => Time.now.utc.to_s, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "slknbnsodb9830unvnve", "X-LB" => "ord1-maas-prod-api1", "Content-Type" => "application/json; charset=UTF-8", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_agent_token.rb0000644000004100000410000000255113411315054027252 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_agent_token(id) request( :expects => [200, 203], :method => 'GET', :path => "agent_tokens/#{id}" ) end end class Mock def get_agent_token(id) token = Fog::Mock.random_letters(50).to_s if id == -1 raise TypeError end response = Excon::Response.new response.status = 200 response.body = { "id" => token, "token" => token, "label" => "mock_token" } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "47903", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "kvnsdonvosnv92989vbvbob", "X-LB" => "ord1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_alarm.rb0000644000004100000410000000341513411315054026050 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_alarm(entity_id, alarm_id) request( :expects => [200, 203], :method => 'GET', :path => "entities/#{entity_id}/alarms/#{alarm_id}" ) end end class Mock def get_alarm(entity_id, alarm_id) if entity_id == -1 || alarm_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 200 response.body = { "id" => alarm_id, "label" => nil, "check_id" => Fog::Mock.random_letters(10), "criteria" => nil, "disabled" => false, "notification_plan_id" => "npTechnicalContactsEmail", "metadata" => nil, "created_at" => Time.now.to_i - 1, "updated_at" => Time.now.to_i } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "38687", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "pomkondbno93gm3030fm303.mmowd", "X-LB" => "ord1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_entity.rb0000644000004100000410000000345613411315054026275 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_entity(entity_id) request( :expects => [200, 203], :method => 'GET', :path => "entities/#{entity_id}" ) end end class Mock def get_entity(entity_id) account_id = Fog::Mock.random_numbers(6).to_s server_id = Fog::Rackspace::MockData.uuid entity_label = Fog::Mock.random_letters(10) if entity_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 200 response.body = { "id" => entity_id, "label" => entity_label, "metadata" => nil, "managed" => false, "uri" => "https://ord.servers.api.rackspacecloud.com/" + account_id + "/servers/" + server_id, "agent_id" => nil, "created_at" => Time.now.to_i - 1, "updated_at" => Time.now.to_i } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlkgmngjl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/delete_alarm.rb0000644000004100000410000000244513411315054026535 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def delete_alarm(entity_id, alarm_id) request( :expects => [204], :method => 'DELETE', :path => "entities/#{entity_id}/alarms/#{alarm_id}" ) end end class Mock def delete_alarm(entity_id, alarm_id) if entity_id == -1 || alarm_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 204 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "38687", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "pomsbnio93gm3030fm303.mmowd", "X-LB" => "ord1-maas-prod-api0", "Vary" => "Accept-Encoding", "Content-Length" => "0" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_disks_info.rb0000644000004100000410000000356113411315054027106 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_disks_info(agent_id) request( :expects => [200, 203], :method => 'GET', :path => "agents/#{agent_id}/host_info/disks" ) end end class Mock def get_disks_info(agent_id) if agent_id == -1 raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 200 response.body = { "info" => [ { "read_bytes" => Fog::Mock.random_numbers(10).to_i, "reads" => Fog::Mock.random_numbers(6).to_i, "rtime" => Fog::Mock.random_numbers(6).to_i, "write_bytes" => Fog::Mock.random_numbers(10).to_i, "writes" => Fog::Mock.random_numbers(8).to_i, "wtime" => Fog::Mock.random_numbers(9).to_i, "time" => Fog::Mock.random_numbers(7).to_i, "name" => "/dev/xvda1" } ] } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/delete_notification.rb0000644000004100000410000000047313411315054030126 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def delete_notification(notification_id) request( :expects => [204], :method => 'DELETE', :path => "notifications/#{notification_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_processes_info.rb0000644000004100000410000000542413411315054027777 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_processes_info(agent_id) request( :expects => [200, 203], :method => 'GET', :path => "agents/#{agent_id}/host_info/processes" ) end end class Mock def get_processes_info(agent_id) memory_major_faults = Fog::Mock.random_numbers(1).to_i memory_minor_faults = Fog::Mock.random_numbers(3).to_i memory_page_faults = memory_major_faults+memory_minor_faults if agent_id == -1 raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 200 response.body = { "info" => [ { "pid" => Fog::Mock.random_numbers(4).to_i, "exe_name" => "/usr/share/nova-agent/0.0.1.38/sbin/nova-agent", "exe_cwd" => "/", "exe_root" => "/", "time_total" => Fog::Mock.random_numbers(3).to_i, "time_sys" => Fog::Mock.random_numbers(2).to_i, "time_user" => Fog::Mock.random_numbers(2).to_i, "time_start_time" => Time.now.utc.to_i - 10000, "state_name" => "nova-agent", "state_ppid" => Fog::Mock.random_numbers(3).to_i, "state_priority" => "15", "state_threads" => Fog::Mock.random_numbers(1).to_i, "memory_size" => Fog::Mock.random_numbers(9).to_i, "memory_resident" => Fog::Mock.random_numbers(7).to_i, "memory_share" => Fog::Mock.random_numbers(6).to_i, "memory_major_faults" => memory_major_faults.to_i, "memory_minor_faults" => memory_minor_faults.to_i, "memory_page_faults" => memory_page_faults.to_i, "cred_user" => "root", "cred_group" => "root" } ] } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_monitoring_zone.rb0000644000004100000410000000044613411315054030175 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_monitoring_zone by_id request( :expects => [200], :method => 'GET', :path => "monitoring_zones/#{by_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_overview.rb0000644000004100000410000001001713411315054027012 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_overview(options={}) request( :expects => [200, 203], :method => 'GET', :path => "views/overview", :query => options ) end end class Mock def list_overview(options={}) alarm_id = Fog::Mock.random_letters(10) check_id = Fog::Mock.random_letters(10) entity_id = Fog::Mock.random_letters(10) account_id = Fog::Mock.random_numbers(6).to_s server_id = Fog::Rackspace::MockData.uuid response = Excon::Response.new response.status = 200 response.body = { "values" => [ { "entity" => { "id" => entity_id, "label" => "mock_entity", "ip_addresses" => { "access_ip0_v6" => Fog::Rackspace::MockData.ipv6_address, "public0_v4" => Fog::Rackspace::MockData.ipv4_address, "public1_v6" => Fog::Rackspace::MockData.ipv6_address, "access_ip1_v4" => Fog::Rackspace::MockData.ipv4_address, "private0_v4" => Fog::Rackspace::MockData.ipv4_address }, "metadata" => { "testing" => "Bar" }, "managed" => false, "uri" => "https://ord.servers.api.rackspacecloud.com/" + account_id + "/servers/" + server_id, "agent_id" => nil, "created_at" => Time.now.to_i - 1, "updated_at" => Time.now.to_i }, "checks" => [ { "id" => check_id, "label" => "mock", "type" => "remote.mock", "details" => {}, "monitoring_zones_poll" => nil, "timeout" => 10, "period" => 30, "target_alias" => nil, "target_hostname" => nil, "target_resolver" => nil, "disabled " => false, "metadata" => nil, "created_at" => Time.now.to_i - 1, "updated_at" => Time.now.to_i } ], "alarms" => [ { "id" => alarm_id, "label" => nil, "check_id" => check_id, "criteria" => nil, "disabled" => false, "notification_plan_id" => "npTechnicalContactsEmail", "metadata" => nil, "created_at" => Time.now.to_i - 1, "updated_at" => Time.now.to_i } ], "latest_alarm_states" => [] } ], "metadata" => { "count" => 1, "limit" => 100, "marker" => nil, "next_marker" => nil, "next_href" => nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" =>" zsdvasdtrq345", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_alarm_examples.rb0000644000004100000410000000043213411315054030136 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_alarm_examples request( :expects => [200, 203], :method => 'GET', :path => 'alarm_examples' ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_alarm_example.rb0000644000004100000410000000044213411315054027560 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_alarm_example(id) request( :expects => [200, 203], :method => 'GET', :path => "alarm_examples/#{id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/update_notification.rb0000644000004100000410000000052613411315054030145 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def update_notification(id, options) request( :body => JSON.encode(options), :expects => [204], :method => 'PUT', :path => "notifications/#{id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_memory_info.rb0000644000004100000410000000413513411315054027277 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_memory_info(agent_id) request( :expects => [200, 203], :method => 'GET', :path => "agents/#{agent_id}/host_info/memory" ) end end class Mock def get_memory_info(agent_id) if agent_id == -1 raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 200 response.body = { "info" => [ { "actual_free" => Fog::Mock.random_numbers(9).to_i, "actual_used" => Fog::Mock.random_numbers(8).to_i, "free" => Fog::Mock.random_numbers(7).to_i, "used" => Fog::Mock.random_numbers(9).to_i, "total" => Fog::Mock.random_numbers(10).to_i, "ram" => Fog::Mock.random_numbers(4).to_i, "swap_total" => Fog::Mock.random_numbers(10).to_i, "swap_used" => Fog::Mock.random_numbers(8).to_i, "swap_free" => Fog::Mock.random_numbers(10).to_i, "swap_page_in" => Fog::Mock.random_numbers(3).to_i, "swap_page_out" => Fog::Mock.random_numbers(3).to_i, } ] } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/create_entity.rb0000644000004100000410000000300313411315054026745 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def create_entity(options = {}) data = options.dup request( :body => JSON.encode(data), :expects => [201], :method => 'POST', :path => 'entities' ) end end class Mock def create_entity(options = {}) account_id = Fog::Mock.random_numbers(6).to_s entity_id = Fog::Mock.random_letters(10) if options[:label] == "" raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 201 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "Location" => "https://monitoring.api.rackspacecloud.com/v1.0/" + account_id + "/entities/" + entity_id, "X-Object-ID" => entity_id, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "47877", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "lakbngf9bgewkgb39sobnsv", "X-LB" => "dfw1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_filesystems_info.rb0000644000004100000410000000427213411315054030340 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_filesystems_info(agent_id) request( :expects => [200, 203], :method => 'GET', :path => "agents/#{agent_id}/host_info/filesystems" ) end end class Mock def get_filesystems_info(agent_id) if agent_id == -1 raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 200 response.body = { "info" => [ { "dir_name" => "/", "dev_name" => "/dev/xvda1", "sys_type_name" => "ext4", "options" => "rw,noatime,acl,errors=remount-ro,barrier=0", "free" => Fog::Mock.random_numbers(8).to_i, "used" => Fog::Mock.random_numbers(5).to_i, "avail" => Fog::Mock.random_numbers(7).to_i, "total" => Fog::Mock.random_numbers(9).to_i, "files" => Fog::Mock.random_numbers(6).to_i, "free_files" => Fog::Mock.random_numbers(6).to_i, }, { "dir_name" => "/proc", "dev_name" => "proc", "sys_type_name" => "ext4", "options" => "rw", } ] } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/create_check.rb0000644000004100000410000000307513411315054026517 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def create_check(entity_id, options = {}) data = options.dup request( :body => JSON.encode(data), :expects => [201], :method => 'POST', :path => "entities/#{entity_id}/checks" ) end end class Mock def create_check(entity_id, options = {}) account_id = Fog::Mock.random_numbers(6).to_s mock_id = Fog::Mock.random_letters(10).to_s if options[:type] == "" raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 201 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "Location" => "https://monitoring.api.rackspacecloud.com/v1.0/" + account_id + "/" + entity_id + "/checks/" + mock_id, "X-Object-ID" => mock_id, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "knvlknvosnd20038hgouwvn9nv", "X-LB" => "ord1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain", } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/update_check.rb0000644000004100000410000000305213411315054026531 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def update_check(entity_id, check_id, options) request( :body => JSON.encode(options), :expects => [204], :method => 'PUT', :path => "entities/#{entity_id}/checks/#{check_id}" ) end end class Mock def update_check(entity_id, check_id, options) account_id = Fog::Mock.random_numbers(6).to_s if entity_id == -1 || check_id == -1 || options[:testing] raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 204 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "Location" => "https://monitoring.api.rackspacecloud.com/v1.0/" + account_id + "/entities/" + entity_id + "/checks/" + check_id, "X-Object-ID" => check_id, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "owbgowb989wno73ubgvw89", "X-LB" => "ord1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain", } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/delete_entity.rb0000644000004100000410000000223313411315054026750 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def delete_entity(entity_id) request( :expects => [204], :method => 'DELETE', :path => "entities/#{entity_id}" ) end end class Mock def delete_entity(entity_id) if entity_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 204 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "47877", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "lakgnnnf9bgewkgb39sobnsv", "X-LB" => "ord1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_system_info.rb0000644000004100000410000000310113411315054027303 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_system_info(agent_id) request( :expects => [200, 203], :method => 'GET', :path => "agents/#{agent_id}/host_info/system" ) end end class Mock def get_system_info(agent_id) if agent_id == -1 raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 200 response.body = { "info" => [ { "name" => "Linux", "arch" => "x86_64", "version" => "2.6.18-308.el5xen", "vendor" => "CentOS", "vendor_version" => "5.10" } ] } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_notification.rb0000644000004100000410000000245413411315054027444 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_notification(notification_id) request( :expects => [200], :method => 'GET', :path => "notifications/#{notification_id}" ) end end class Mock def get_notification(notification_id) response = Excon::Response.new response.status = 200 response.body = { "created_at" => 1378783452067, "details" => { "address" => "test@test.com" }, "id" => "ntnJN3MQrA", "label" => "my email update test", "type" => "email", "updated_at" => 1378784136307 } response.headers = { "Date"=> Time.now.utc.to_s, "Content-Type"=>"application/json; charset=UTF-8", "X-RateLimit-Limit"=>"50000", "X-RateLimit-Remaining"=>"49627", "X-RateLimit-Window"=>"24 hours", "X-RateLimit-Type"=>"global", "X-Response-Id"=>"j23jlk234jl2j34j", "X-LB"=>"dfw1-maas-prod-api0", "Vary"=>"Accept-Encoding", "Transfer-Encoding"=>"chunked" } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_cpus_info.rb0000644000004100000410000000435213411315054026742 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_cpus_info(agent_id) request( :expects => [200, 203], :method => 'GET', :path => "agents/#{agent_id}/host_info/cpus" ) end end class Mock def get_cpus_info(agent_id) if agent_id == -1 raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 200 response.body = { "info" => [ { "name" => "cpu.0", "vendor" => "AMD", "model" => "Opteron", "mhz" => Fog::Mock.random_numbers(4).to_i, "idle" => Fog::Mock.random_numbers(10).to_i, "irq" => Fog::Mock.random_numbers(5).to_i, "soft_irq" => Fog::Mock.random_numbers(7).to_i, "nice" => Fog::Mock.random_numbers(9).to_i, "stolen" => Fog::Mock.random_numbers(7).to_i, "sys" => Fog::Mock.random_numbers(7).to_i, "user" => Fog::Mock.random_numbers(9).to_i, "wait" => Fog::Mock.random_numbers(7).to_i, "total" => Fog::Mock.random_numbers(11).to_i, "total_cores" => 1, "total_sockets" => 1 } ] } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_agent.rb0000644000004100000410000000254713411315054026057 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_agent(agent_id) request( :expects => [200, 203], :method => 'GET', :path => "agents/#{agent_id}" ) end end class Mock def get_agent(agent_id) if agent_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 200 response.body = { "id" => Fog::Rackspace::MockData.uuid, "last_connected" => Time.now.to_i - 100, } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/get_network_interfaces_info.rb0000644000004100000410000000730613411315054031666 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def get_network_interfaces_info(agent_id) request( :expects => [200, 203], :method => 'GET', :path => "agents/#{agent_id}/host_info/network_interfaces" ) end end class Mock def get_network_interfaces_info(agent_id) if agent_id == -1 raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 200 response.body = { "info" => [ { "name" => "lo", "type" => "Local Loopback", "address" => Fog::Mock.random_ip({:version => :v4}), "netmask" => "255.0.0.0", "address6" => "::1", "broadcast" => "0.0.0.0.0", "hwaddr" => "00:00:00:00:00:00", "mtu" => Fog::Mock.random_numbers(4).to_i, "rx_packets" => Fog::Mock.random_numbers(3).to_i, "rx_bytes" => Fog::Mock.random_numbers(4).to_i, "tx_packets" => Fog::Mock.random_numbers(3).to_i, "tx_bytes" => Fog::Mock.random_numbers(4).to_i, "flags" => Fog::Mock.random_numbers(2).to_i, }, { "name" => "eth0", "type" => "Ethernet", "address" => Fog::Mock.random_ip({:version => :v4}), "netmask" => "255.255.255.0", "address6" => Fog::Mock.random_ip({:version => :v6}), "broadcast" => Fog::Mock.random_ip({:version => :v4}), "hwaddr" => "A1:B2:C3:D4:E5:F6", "mtu" => "1500", "rx_packets" => Fog::Mock.random_numbers(7).to_i, "rx_bytes" => Fog::Mock.random_numbers(9).to_i, "tx_packets" => Fog::Mock.random_numbers(7).to_i, "tx_bytes" => Fog::Mock.random_numbers(9).to_i, "flags" => Fog::Mock.random_numbers(4).to_i, }, { "name" => "eth1", "type" => "Ethernet", "address" => Fog::Mock.random_ip({:version => :v4}), "netmask" => "255.255.128.0", "address6" => Fog::Mock.random_ip({:version => :v6}), "broadcast" => Fog::Mock.random_ip({:version => :v4}), "hwaddr" => "A2:B3:C4:D5:E6:F7", "mtu" => "1500", "rx_packets" => Fog::Mock.random_numbers(7).to_i, "rx_bytes" => Fog::Mock.random_numbers(9).to_i, "tx_packets" => Fog::Mock.random_numbers(7).to_i, "tx_bytes" => Fog::Mock.random_numbers(9).to_i, "flags" => Fog::Mock.random_numbers(4).to_i, } ] } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Mock.random_ip({:version => :v4}) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_check_types.rb0000644000004100000410000000476313411315054027460 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_check_types request( :expects => [200, 203], :method => 'GET', :path => "check_types" ) end end class Mock def list_check_types response = Excon::Response.new response.status = 200 response.body = { "values" => [ { "type" => "remote", "id" => "remote.dns", "channel"=> "stable", "fields" => [ { "name" => "port", "description"=> "Port number (default: 53)", "optional" => true }, { "name" => "query", "description"=> "DNS Query", "optional" => false }, { "name" => "record_type", "description" => "DNS Record Type", "optional" => false } ], "category" => "remote" }, { "type" => "agent", "id" => "agent.memory", "channel" =>"stable", "fields" => [], "supported_platforms" => [ "Linux", "Windows" ], "category" => "agent_system" } ], "metadata" => { "count" => 2, "limit" => 100, "marker" => nil, "next_marker" => nil, "next_href" => nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "zsdvasdtrq345", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_entities.rb0000644000004100000410000000501113411315054026766 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_entities(options={}) request( :expects => [200, 203], :method => 'GET', :path => 'entities', :query => options ) end end class Mock def list_entities(options={}) account_id = Fog::Mock.random_numbers(6).to_s server_id = Fog::Rackspace::MockData.uuid entity_id = Fog::Mock.random_letters(10) entity_label = Fog::Mock.random_letters(10) response = Excon::Response.new response.status = 200 response.body = { "values"=> [ { "id" => entity_id, "label" => entity_label, "ip_addresses" => { "access_ip0_v6" => Fog::Rackspace::MockData.ipv6_address, "public0_v4" => Fog::Rackspace::MockData.ipv4_address, "public1_v6" => Fog::Rackspace::MockData.ipv6_address, "access_ip1_v4" => Fog::Rackspace::MockData.ipv4_address, "private0_v4" => Fog::Rackspace::MockData.ipv4_address }, "metadata" => nil, "managed" => false, "uri" => "https://ord.servers.api.rackspacecloud.com/" + account_id + "/servers/" + server_id, "agent_id" => nil, "created_at" => Time.now.to_i - 1, "updated_at" => Time.now.to_i } ], "metadata" => { "count" => 1, "limit" => 100, "marker" => nil, "next_marker" => nil, "next_href" => nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_notification_plans.rb0000644000004100000410000000407613411315054031037 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_notification_plans request( :expects => [200], :method => 'GET', :path => "notification_plans" ) end end class Mock def list_notification_plans notification_id = Fog::Mock.random_letters(10) response = Excon::Response.new response.status = 200 response.body = { "values" => [ { "id" => "npTechnicalContactsEmail", "label" => "Technical Contacts - Email", "critical_state" => [], "warning_state" => [], "ok_state" => [] }, { "id" => "notification_id", "label" => "mock_label", "critical_state" => nil, "warning_state" => nil, "ok_state" => nil, "created_at" => Time.now.to_i - 2, "updated_at" => Time.now.to_i - 1 } ], "metadata" => { "count" => 2, "limit" => 100, "marker" => nil, "next_marker" => nil, "next_href" => nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" =>" zsdvasdtrq345", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_alarms.rb0000644000004100000410000000414613411315054026431 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_alarms(entity_id, options={}) request( :expects => [200, 203], :method => 'GET', :path => "entities/#{entity_id}/alarms", :query => options ) end end class Mock def list_alarms(entity_id) if entity_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 200 response.body = { "values" => [ { "id" => Fog::Mock.random_letters(10), "label" => nil, "check_id" => Fog::Mock.random_letters(10), "criteria" => nil, "disabled" => false, "notification_plan_id" => "npTechnicalContactsEmail", "metadata" => nil, "created_at" => Time.now.to_i - 1, "updated_at" => Time.now.to_i } ], "metadata" => { "count" =>1, "limit" =>100, "marker" =>nil, "next_marker" =>nil, "next_href" =>nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "38687", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "pomegmgm3030fm303.mmowd", "X-LB" => "ord1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/create_agent_token.rb0000644000004100000410000000275213411315054027741 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def create_agent_token(options = {}) data = options.dup request( :body => JSON.encode(data), :expects => [201], :method => 'POST', :path => 'agent_tokens' ) end end class Mock def create_agent_token(options = {}) account_id = Fog::Mock.random_numbers(6).to_s token = Fog::Mock.random_letters(50).to_s if options == -1 raise TypeError end response = Excon::Response.new response.status = 201 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "Location" => "https://monitoring.api.rackspacecloud.com/v1.0/" + account_id + "/agent_tokens/" + token, "X-Object-ID" => token, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "oknwowevown9330wneviniv", "X-LB" => "ord1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain", } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/create_alarm.rb0000644000004100000410000000306613411315054026536 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def create_alarm(entity_id, options = {}) data = options.dup request( :body => JSON.encode(data), :expects => [201], :method => 'POST', :path => "entities/#{entity_id}/alarms" ) end end class Mock def create_alarm(entity_id, options = {}) alarm_id = Fog::Mock.random_letters(10) account_id = Fog::Mock.random_numbers(6).to_s if options[:type] raise Fog::Rackspace::Monitoring::BadRequest end response = Excon::Response.new response.status = 201 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "Location" => "https://monitoring.api.rackspacecloud.com/v1.0/" + account_id + "/entities/" + entity_id.to_s + "/alarms/" + alarm_id, "X-Object-ID" => alarm_id, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "47877", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "laolsgggopnnsv", "X-LB" => "dfw1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_notifications.rb0000644000004100000410000000375613411315054030031 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_notifications(options={}) request( :expects => [200], :method => 'GET', :path => "notifications", :query => options ) end end class Mock def list_notifications(options={}) account_id = Fog::Mock.random_numbers(6).to_s server_id = Fog::Rackspace::MockData.uuid entity_id = Fog::Mock.random_letters(10) entity_label = Fog::Mock.random_letters(10) response = Excon::Response.new response.status = 200 response.body = { "values"=> [ { "created_at"=>1378783452067, "details"=>{ "address"=>"test@test.com" }, "id"=>"ntnJN3MQrA", "label"=>"my email update test", "type"=>"email", "updated_at"=>1378784136307 } ], "metadata" => { "count" => 1, "limit" => 100, "marker" => nil, "next_marker" => nil, "next_href" => nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/update_entity.rb0000644000004100000410000000272113411315054026772 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def update_entity(entity_id, options) request( :body => JSON.encode(options), :expects => [204], :method => 'PUT', :path => "entities/#{entity_id}" ) end end class Mock def update_entity(entity_id, options) account_id = Fog::Mock.random_numbers(6).to_s if entity_id == -1 raise Fog::Rackspace::Monitoring::NotFound end response = Excon::Response.new response.status = 204 response.body = "" response.headers = { "Date" => Time.now.utc.to_s, "Location" => "https://monitoring.api.rackspacecloud.com/v1.0/" + account_id + "/entities/" + entity_id.to_s, "X-Object-ID" => entity_id.to_s, "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "47877", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "lakbngf9bsgkn69gb39sobnsv", "X-LB" => "dfw1-maas-prod-api1", "Content-Length" => "0", "Content-Type" => "text/plain" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/evaluate_alarm_example.rb0000644000004100000410000000064013411315054030607 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def evaluate_alarm_example(id, options = {}) options ||= {} data = {:values => options.dup} request( :body => JSON.encode(data), :expects => [200], :method => 'POST', :path => "alarm_examples/#{id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_metrics.rb0000644000004100000410000000451413411315054026617 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_metrics(entity_id, check_id) request( :expects => [200, 203], :method => 'GET', :path => "entities/#{entity_id}/checks/#{check_id}/metrics" ) end end class Mock def list_metrics(entity_id, check_id) response = Excon::Response.new response.status = 200 response.body = { "values" => [ { "name" => "idle_percent_average", "unit" => "percent" }, { "name" => "irq_percent_average", "unit" => "percent" }, { "name" => "max_cpu_usage", "unit" => "percent" }, { "name" => "min_cpu_usage", "unit" => "percent" }, { "name" => "stolen_percent_average", "unit" => "percent" }, { "name" => "sys_percent_average", "unit" => "percent" }, { "name" => "usage_average", "unit" => "percent" }, { "name" => "user_percent_average", "unit" => "percent" }, { "name" => "wait_percent_average", "unit" => "percent" } ], "metadata" => { "count" => 9, "limit" => nil, "marker" => nil, "next_marker" => nil, "next_href" => nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" => "zsdvasdtrq345", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/monitoring/list_agent_tokens.rb0000644000004100000410000000320513411315054027626 0ustar www-datawww-datamodule Fog module Rackspace class Monitoring class Real def list_agent_tokens(options={}) request( :expects => [200, 203], :method => 'GET', :path => 'agent_tokens', :query => options ) end end class Mock def list_agent_tokens(options={}) token = Fog::Mock.random_letters(50).to_s response = Excon::Response.new response.status = 200 response.body = { "values"=> [ { "id" => token, "token" => token, "label" => "mock_token" } ], "metadata" => { "count" => 1, "limit" => 100, "marker" => nil, "next_marker" => nil, "next_href" => nil } } response.headers = { "Date" => Time.now.utc.to_s, "Content-Type" => "application/json; charset=UTF-8", "X-RateLimit-Limit" => "50000", "X-RateLimit-Remaining" => "49627", "X-RateLimit-Window" => "24 hours", "X-RateLimit-Type" => "global", "X-Response-Id" =>" j23jlk234jl2j34j", "X-LB" => "dfw1-maas-prod-api0", "Vary" => "Accept-Encoding", "Transfer-Encoding" => "chunked" } response.remote_ip = Fog::Rackspace::MockData.ipv4_address response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/0000755000004100000410000000000013411315054023044 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/delete_multiple_objects.rb0000644000004100000410000001174513411315054030267 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Deletes multiple objects or containers with a single request. # # To delete objects from a single container, +container+ may be provided # and +object_names+ should be an Array of object names within the container. # # To delete objects from multiple containers or delete containers, # +container+ should be +nil+ and all +object_names+ should be prefixed with a container name. # # Containers must be empty when deleted. +object_names+ are processed in the order given, # so objects within a container should be listed first to empty the container. # # Up to 10,000 objects may be deleted in a single request. # The server will respond with +200 OK+ for all requests. # +response.body+ must be inspected for actual results. # # @example Delete objects from a container # object_names = ['object', 'another/object'] # conn.delete_multiple_objects('my_container', object_names) # # @example Delete objects from multiple containers # object_names = ['container_a/object', 'container_b/object'] # conn.delete_multiple_objects(nil, object_names) # # @example Delete a container and all it's objects # object_names = ['my_container/object_a', 'my_container/object_b', 'my_container'] # conn.delete_multiple_objects(nil, object_names) # # @param container [String,nil] Name of container. # @param object_names [Array] Object names to be deleted. # @param options [Hash] Additional request headers. # # @return [Excon::Response] # * body [Hash] - Results of the operation. # * "Number Not Found" [Integer] - Number of missing objects or containers. # * "Response Status" [String] - Response code for the subrequest of the last failed operation. # * "Errors" [Array] # * object_name [String] - Object that generated an error when the delete was attempted. # * response_status [String] - Response status from the subrequest for object_name. # * "Number Deleted" [Integer] - Number of objects or containers deleted. # * "Response Body" [String] - Response body for "Response Status". # # @raise [Fog::Storage::Rackspace::NotFound] HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @raise [Excon::Errors::Unauthorized] HTTP 401 # # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Bulk_Delete-d1e2338.html def delete_multiple_objects(container, object_names, options = {}) body = object_names.map do |name| object_name = container ? "#{ container }/#{ name }" : name URI.encode(object_name) end.join("\n") response = request({ :expects => 200, :method => 'DELETE', :headers => options.merge('Content-Type' => 'text/plain', 'Accept' => 'application/json'), :body => body, :query => { 'bulk-delete' => true } }, false) response.body = Fog::JSON.decode(response.body) response end end class Mock def delete_multiple_objects(container, object_names, options = {}) results = { "Number Not Found" => 0, "Response Status" => "200 OK", "Response Body" => "", "Errors" => [], "Number Deleted" => 0 } object_names.each do |name| if container cname, oname = container, name else cname, oname = name.split('/', 2) end c = mock_container cname if c.nil? # Container not found results["Number Not Found"] += 1 next end if oname.nil? # No object name specified; delete the container if it's nonempty unless c.empty? results["Response Status"] = "400 Bad Request" results["Errors"] << [cname, "409 Conflict"] next end remove_container cname results["Number Deleted"] += 1 next end o = c.mock_object oname if o.nil? # Object not found. results["Number Not Found"] += 1 next end c.remove_object oname results["Number Deleted"] += 1 end response = Excon::Response.new response.status = 200 response.body = results response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/post_set_meta_temp_url_key.rb0000644000004100000410000000305713411315054031023 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Set the account wide Temp URL Key. This is a secret key that's # used to generate signed expiring URLs. # # Once the key has been set with this request you should create new # Storage objects with the :rackspace_temp_url_key option then use # the get_object_https_url method to generate expiring URLs. # # *** CAUTION *** changing this secret key will invalidate any expiring # URLS generated with old keys. # # ==== Parameters # * key<~String> - The new Temp URL Key # # ==== Returns # * response<~Excon::Response> # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # ==== See Also # http://docs.rackspace.com/files/api/v1/cf-devguide/content/Set_Account_Metadata-d1a4460.html def post_set_meta_temp_url_key(key) request( :expects => [201, 202, 204], :method => 'POST', :headers => {'X-Account-Meta-Temp-Url-Key' => key} ) end end class Mock def post_set_meta_temp_url_key(key) account_meta['X-Account-Meta-Temp-Url-Key'] = key response = Excon::Response.new response.status = 204 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/put_object_manifest.rb0000644000004100000410000000075013411315054027417 0ustar www-datawww-datamodule Fog module Storage class Rackspace module Common # Create a new dynamic large object manifest # # This is an alias for {#put_dynamic_obj_manifest} for backward compatibility. def put_object_manifest(container, object, options = {}) put_dynamic_obj_manifest(container, object, options) end end class Real include Common end class Mock include Common end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/copy_object.rb0000644000004100000410000000231513411315054025672 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Copy object # # ==== Parameters # * source_container_name<~String> - Name of source bucket # * source_object_name<~String> - Name of source object # * target_container_name<~String> - Name of bucket to create copy in # * target_object_name<~String> - Name for new copy of object # * options<~Hash> - Additional headers # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def copy_object(source_container_name, source_object_name, target_container_name, target_object_name, options={}) headers = { 'X-Copy-From' => "/#{source_container_name}/#{source_object_name}" }.merge(options) request({ :expects => 201, :headers => headers, :method => 'PUT', :path => "#{Fog::Rackspace.escape(target_container_name)}/#{Fog::Rackspace.escape(target_object_name)}" }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/put_object.rb0000644000004100000410000000474713411315054025543 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Create a new object # # When passed a block, it will make a chunked request, calling # the block for chunks until it returns an empty string. # In this case the data parameter is ignored. # # ==== Parameters # * container<~String> - Name for container, should be < 256 bytes and must not contain '/' # * object<~String> - Name for object # * data<~String|File> - data to upload # * options<~Hash> - config headers for object. Defaults to #{}. # * block<~Proc> - chunker # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def put_object(container, object, data, options = {}, &block) data = Fog::Storage.parse_data(data) headers = data[:headers].merge!(options) params = block_given? ? { :request_block => block } : { :body => data[:body] } params.merge!( :expects => 201, :idempotent => !params[:request_block], :headers => headers, :method => 'PUT', :path => "#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object)}" ) request(params) end end class Mock HeaderOptions = %w{ Content-Type Access-Control-Allow-Origin Origin Content-Disposition Etag Content-Encoding }.freeze def put_object(container, object, data, options = {}, &block) c = mock_container! container if block_given? data = "" loop do chunk = yield break if chunk.empty? data << chunk end end o = c.add_object object, data options.keys.each do |k| o.meta[k] = options[k].to_s if k =~ /^X-Object-Meta/ o.meta[k] = options[k] if HeaderOptions.include? k end # Validate the provided Etag etag = o.meta['Etag'] if etag && etag != o.hash c.remove_object object raise Fog::Storage::Rackspace::ServiceError.new end response = Excon::Response.new response.status = 201 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/delete_container.rb0000644000004100000410000000173513411315054026703 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Delete an existing container # # ==== Parameters # * name<~String> - Name of container to delete # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def delete_container(name) request( :expects => 204, :method => 'DELETE', :path => Fog::Rackspace.escape(name) ) end end class Mock def delete_container(name) c = mock_container! name raise Excon::Errors::Conflict.new 'Conflict' unless c.empty? remove_container name response = Excon::Response.new response.status = 204 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/head_object.rb0000644000004100000410000000267313411315054025630 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Get headers for object # # ==== Parameters # * container<~String> - Name of container to look in # * object<~String> - Name of object to look for # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def head_object(container, object) request({ :expects => 200, :method => 'HEAD', :path => "#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object)}" }, false) end end class Mock def head_object(container, object) c = mock_container! container o = c.mock_object! object headers = o.to_headers hashes, length = [], 0 o.each_part do |part| hashes << part.hash length += part.bytes_used end headers['Etag'] = "\"#{Digest::MD5.hexdigest(hashes.join)}\"" headers['Content-Length'] = length.to_s headers['X-Static-Large-Object'] = "True" if o.static_manifest? response = Excon::Response.new response.status = 200 response.headers = headers response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/head_containers.rb0000644000004100000410000000267113411315054026525 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # List number of containers and total bytes stored # # ==== Returns # * response<~Excon::Response>: # * headers<~Hash>: # * 'X-Account-Container-Count'<~String> - Count of containers # * 'X-Account-Bytes-Used'<~String> - Bytes used # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def head_containers request( :expects => 204, :method => 'HEAD', :path => '', :query => {'format' => 'json'} ) end end class Mock def head_containers bytes_used = data.values.map { |c| c.bytes_used }.reduce(0) { |a, b| a + b } container_count = data.size object_count = data.values.map { |c| c.objects.size }.reduce(0) { |a, b| a + b } response = Excon::Response.new response.status = 204 response.headers = { 'X-Account-Bytes-Used' => bytes_used, 'X-Account-Container-Count' => container_count, 'X-Account-Object-Count' => object_count }.merge(account_meta) response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/head_container.rb0000644000004100000410000000235713411315054026343 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # List number of objects and total bytes stored # # ==== Parameters # * container<~String> - Name of container to retrieve info for # # ==== Returns # * response<~Excon::Response>: # * headers<~Hash>: # * 'X-Container-Object-Count'<~String> - Count of containers # * 'X-Container-Bytes-Used'<~String> - Bytes used # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def head_container(container) request( :expects => 204, :method => 'HEAD', :path => Fog::Rackspace.escape(container), :query => {'format' => 'json'} ) end end class Mock def head_container(container) c = mock_container! container response = Excon::Response.new response.status = 204 response.headers = c.to_headers response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/put_dynamic_obj_manifest.rb0000644000004100000410000000570013411315054030427 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Create a new dynamic large object manifest # # Creates an object with a +X-Object-Manifest+ header that specifies the common prefix ("/") # for all uploaded segments. Retrieving the manifest object streams all segments matching this prefix. # Segments must sort in the order they should be concatenated. Note that any future objects stored in the container # along with the segments that match the prefix will be included when retrieving the manifest object. # # All segments must be stored in the same container, but may be in a different container than the manifest object. # The default +X-Object-Manifest+ header is set to "+container+/+object+", but may be overridden in +options+ # to specify the prefix and/or the container where segments were stored. # If overridden, names should be CGI escaped (excluding spaces) if needed (see {Fog::Rackspace.escape}). # # @param container [String] Name for container where +object+ will be stored. Should be < 256 bytes and must not contain '/' # @param object [String] Name for manifest object. # @param options [Hash] Config headers for +object+. # @option options [String] 'X-Object-Manifest' ("container/object") "/" for segment objects. # # @raise [Fog::Storage::Rackspace::NotFound] HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @raise [Excon::Errors::Unauthorized] # # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Large_Object_Creation-d1e2019.html def put_dynamic_obj_manifest(container, object, options = {}) path = "#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object)}" headers = {'X-Object-Manifest' => path}.merge(options) request( :expects => 201, :headers => headers, :method => 'PUT', :path => path ) end end class Mock def put_dynamic_obj_manifest(container, object, options = {}) path = "#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object)}" # Escape the X-Object-Manifest header to match. explicit_manifest = options['X-Object-Manifest'] if explicit_manifest parts = explicit_manifest.split('/', 2) explicit_manifest = parts.map { |p| Fog::Rackspace.escape p }.join('/') end c = mock_container! container o = c.add_object object, '' o.meta['X-Object-Manifest'] = explicit_manifest || path response = Excon::Response.new response.status = 201 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/get_object_https_url.rb0000644000004100000410000000511713411315054027606 0ustar www-datawww-datamodule Fog module Storage class Rackspace module Common # Get an expiring object https url from Cloud Files # # ==== Parameters # * container<~String> - Name of container containing object # * object<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # * options<~Hash> - Options to override the method or scheme # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # ==== See Also # http://docs.rackspace.com/files/api/v1/cf-devguide/content/Create_TempURL-d1a444.html def get_object_https_url(container, object, expires, options = {}) if @rackspace_temp_url_key.nil? raise ArgumentError, "Storage must be instantiated with the :rackspace_temp_url_key option" end method = options[:method] || 'GET' expires = expires.to_i object_path_escaped = "#{@uri.path}/#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object,"/")}" object_path_unescaped = "#{@uri.path}/#{Fog::Rackspace.escape(container)}/#{object}" string_to_sign = "#{method}\n#{expires}\n#{object_path_unescaped}" hmac = Fog::HMAC.new('sha1', @rackspace_temp_url_key) sig = sig_to_hex(hmac.sign(string_to_sign)) temp_url_query = { :temp_url_sig => sig, :temp_url_expires => expires } temp_url_query.merge!(:inline => true) if options[:inline] temp_url_query.merge!(:filename => options[:filename]) if options[:filename] temp_url_options = { :scheme => options[:scheme] || @uri.scheme, :host => @uri.host, :path => object_path_escaped, :query => temp_url_query.map { |param, val| "#{CGI.escape(param.to_s)}=#{CGI.escape(val.to_s)}" }.join('&') } URI::Generic.build(temp_url_options).to_s end private def sig_to_hex(str) str.unpack("C*").map { |c| c.to_s(16) }.map { |h| h.size == 1 ? "0#{h}" : h }.join end end class Mock include Common end class Real include Common end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/get_object.rb0000644000004100000410000000271213411315054025500 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Get details for object # # ==== Parameters # * container<~String> - Name of container to look in # * object<~String> - Name of object to look for # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def get_object(container, object, &block) params = { :expects => 200, :method => 'GET', :path => "#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object)}" } if block_given? params[:response_block] = block end request(params, false) end end class Mock def get_object(container, object, &block) c = mock_container! container o = c.mock_object! object body, size = "", 0 o.each_part do |part| body << part.body size += part.bytes_used end if block_given? # Just send it all in one chunk. block.call(body, 0, size) end response = Excon::Response.new response.body = body response.headers = o.to_headers response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/get_object_http_url.rb0000644000004100000410000000221713411315054027421 0ustar www-datawww-datamodule Fog module Storage class Rackspace module Common # Get an expiring object http url from Cloud Files # # ==== Parameters # * container<~String> - Name of container containing object # * object<~String> - Name of object to get expiring url for # * expires<~Time> - An expiry time for this url # # ==== Returns # * response<~Excon::Response>: # * body<~String> - url for object # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # ==== See Also # http://docs.rackspace.com/files/api/v1/cf-devguide/content/Create_TempURL-d1a444.html def get_object_http_url(container, object, expires, options = {}) get_object_https_url(container, object, expires, options.merge(:scheme => 'http')) end end class Real include Common end class Mock include Common end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/delete_static_large_object.rb0000644000004100000410000000625413411315054030711 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Delete a static large object. # # Deletes the SLO manifest +object+ and all segments that it references. # The server will respond with +200 OK+ for all requests. # +response.body+ must be inspected for actual results. # # @param container [String] Name of container. # @param object [String] Name of the SLO manifest object. # @param options [Hash] Additional request headers. # # @return [Excon::Response] # * body [Hash] - Results of the operation. # * "Number Not Found" [Integer] - Number of missing segments. # * "Response Status" [String] - Response code for the subrequest of the last failed operation. # * "Errors" [Array] # * object_name [String] - Object that generated an error when the delete was attempted. # * response_status [String] - Response status from the subrequest for object_name. # * "Number Deleted" [Integer] - Number of segments deleted. # * "Response Body" [String] - Response body for Response Status. # # @raise [Fog::Storage::Rackspace::NotFound] HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @raise [Excon::Errors::Unauthorized] HTTP 401 # # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Deleting_a_Large_Object-d1e2228.html def delete_static_large_object(container, object, options = {}) response = request({ :expects => 200, :method => 'DELETE', :headers => options.merge('Content-Type' => 'text/plain', 'Accept' => 'application/json'), :path => "#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object)}", :query => { 'multipart-manifest' => 'delete' } }, false) response.body = Fog::JSON.decode(response.body) response end end class Mock def delete_static_large_object(container, object, options = {}) c = mock_container container return not_found(container) unless c o = c.mock_object object return not_found(object) unless o # What happens if o isn't a static large object? raise Fog::Storage::Rackspace::BadRequest.new unless o.static_manifest? segments = Fog::JSON.decode(o.body) paths = segments.map { |s| s['path'] } paths << "#{container}/#{object}" delete_multiple_objects(nil, paths) end def not_found(path) response = Excon::Response.new response.status = 200 response.body = { "Number Not Found" => 1, "Response Status" => "200 OK", "Response Body" => "", "Errors" => [[path, "404 Not Found"]], "Number Deleted" => 0 } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/put_container.rb0000644000004100000410000000244113411315054026244 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Create a new container # # ==== Parameters # * name<~String> - Name for container, should be < 256 bytes and must not contain '/' # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def put_container(name, options={}) if name =~ /\// raise Fog::Errors::Error.new('Folder names cannot include "/".') else request( :expects => [201, 202], :method => 'PUT', :headers => options, :path => Fog::Rackspace.escape(name) ) end end end class Mock def put_container(name, options={}) existed = ! mock_container(name).nil? container = add_container(name) options.keys.each do |k| container.meta[k] = options[k].to_s if k =~ /^X-Container-Meta/ end response = Excon::Response.new response.status = existed ? 202 : 201 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/extract_archive.rb0000644000004100000410000000244213411315054026546 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Extract Archive # # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Extract_Archive-d1e2338.html # # ==== Parameters # * container<~String> - Name for container, should be < 256 bytes and must not contain '/' # * data<~String|File> - file to upload # * archive_format<~String> - "tar", "tar.gz", or "tar.bz2" # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def extract_archive(container, data, archive_format) data = Fog::Storage.parse_data(data) headers = data[:headers] headers["Content-Type"] = "" params = { :body => data[:body], :query => {"extract-archive" => archive_format} } params.merge!( :expects => 200, :idempotent => true, :headers => headers, :method => 'PUT', :path => "#{Fog::Rackspace.escape(container.to_s)}" ) request(params) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/delete_object.rb0000644000004100000410000000206313411315054026162 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Delete an existing object # # ==== Parameters # * container<~String> - Name of container to delete # * object<~String> - Name of object to delete # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def delete_object(container, object) request( :expects => 204, :method => 'DELETE', :path => "#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object)}" ) end end class Mock def delete_object(container, object) c = mock_container! container c.mock_object! object c.remove_object object response = Excon::Response.new response.status = 204 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/put_static_obj_manifest.rb0000644000004100000410000001034613411315054030274 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Create a new static large object manifest. # # A static large object is similar to a dynamic large object. Whereas a GET for a dynamic large object manifest # will stream segments based on the manifest's +X-Object-Manifest+ object name prefix, a static large object # manifest streams segments which are defined by the user within the manifest. Information about each segment is # provided in +segments+ as an Array of Hash objects, ordered in the sequence which the segments should be streamed. # # When the SLO manifest is received, each segment's +etag+ and +size_bytes+ will be verified. # The +etag+ for each segment is returned in the response to {#put_object}, but may also be calculated. # e.g. +Digest::MD5.hexdigest(segment_data)+ # # The maximum number of segments for a static large object is 1000, and all segments (except the last) must be # at least 1 MiB in size. Unlike a dynamic large object, segments are not required to be in the same container. # # @example # segments = [ # { :path => 'segments_container/first_segment', # :etag => 'md5 for first_segment', # :size_bytes => 'byte size of first_segment' }, # { :path => 'segments_container/second_segment', # :etag => 'md5 for second_segment', # :size_bytes => 'byte size of second_segment' } # ] # put_static_obj_manifest('my_container', 'my_large_object', segments) # # @param container [String] Name for container where +object+ will be stored. # Should be < 256 bytes and must not contain '/' # @param object [String] Name for manifest object. # @param segments [Array] Segment data for the object. # @param options [Hash] Config headers for +object+. # # @raise [Fog::Storage::Rackspace::NotFound] HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @raise [Excon::Errors::Unauthorized] HTTP 401 # # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Uploading_the_Manifext-d1e2227.html def put_static_obj_manifest(container, object, segments, options = {}) request( :expects => 201, :method => 'PUT', :headers => options, :body => Fog::JSON.encode(segments), :path => "#{Fog::Rackspace.escape(container)}/#{Fog::Rackspace.escape(object)}", :query => { 'multipart-manifest' => 'put' } ) end end class Mock def put_static_obj_manifest(container, object, segments, options = {}) c = mock_container! container # Verify paths. errors = [] segments.each do |segment| cname, oname = segment[:path].split('/', 2) target_container = mock_container(cname) raise Fog::Storage::Rackspace::NotFound.new unless target_container target_object = target_container.mock_object oname unless target_object errors << [segment[:path], '404 Not Found'] next end unless target_object.hash == segment[:etag] errors << [segment[:path], 'Etag Mismatch'] end unless target_object.bytes_used == segment[:size_bytes] errors << [segment[:path], 'Size Mismatch'] end end unless errors.empty? response = Excon::Response.new response.status = 400 response.body = Fog::JSON.encode({ 'Errors' => errors }) error = Excon::Errors.status_error({}, response) raise Fog::Storage::Rackspace::BadRequest.slurp(error) end data = Fog::JSON.encode(segments) o = c.add_object object, data o.static_manifest = true response = Excon::Response.new response.status = 201 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/get_container.rb0000644000004100000410000000514613411315054026220 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # Get details for container and total bytes stored # # ==== Parameters # * container<~String> - Name of container to retrieve info for # * options<~String>: # * 'limit'<~String> - Maximum number of objects to return # * 'marker'<~String> - Only return objects whose name is greater than marker # * 'prefix'<~String> - Limits results to those starting with prefix # * 'path'<~String> - Return objects nested in the pseudo path # # ==== Returns # * response<~Excon::Response>: # * headers<~Hash>: # * 'X-Account-Container-Count'<~String> - Count of containers # * 'X-Account-Bytes-Used'<~String> - Bytes used # * body<~Array>: # * 'bytes'<~Integer> - Number of bytes used by container # * 'count'<~Integer> - Number of items in container # * 'name'<~String> - Name of container # * item<~Hash>: # * 'bytes'<~String> - Size of object # * 'content_type'<~String> Content-Type of object # * 'hash'<~String> - Hash of object (etag?) # * 'last_modified'<~String> - Last modified timestamp # * 'name'<~String> - Name of object # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def get_container(container, options = {}) options = options.reject {|key, value| value.nil?} request( :expects => 200, :method => 'GET', :path => Fog::Rackspace.escape(container), :query => {'format' => 'json'}.merge!(options) ) end end class Mock def get_container(container, options = {}) c = mock_container! container results = [] c.objects.each do |key, mock_file| results << { "hash" => mock_file.hash, "last_modified" => mock_file.last_modified.strftime('%Y-%m-%dT%H:%M:%S.%L'), "bytes" => mock_file.bytes_used, "name" => key, "content_type" => mock_file.content_type } end response = Excon::Response.new response.status = 200 response.headers = c.to_headers response.body = results response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/storage/get_containers.rb0000644000004100000410000000322613411315054026400 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Real # List existing storage containers # # ==== Parameters # * options<~Hash>: # * 'limit'<~Integer> - Upper limit to number of results returned # * 'marker'<~String> - Only return objects with name greater than this value # # ==== Returns # * response<~Excon::Response>: # * body<~Array>: # * container<~Hash>: # * 'bytes'<~Integer>: - Number of bytes used by container # * 'count'<~Integer>: - Number of items in container # * 'name'<~String>: - Name of container # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def get_containers(options = {}) options = options.reject {|key, value| value.nil?} request( :expects => [200, 204], :method => 'GET', :path => '', :query => {'format' => 'json'}.merge!(options) ) end end class Mock def get_containers(options = {}) results = data.map do |name, container| { "name" => name, "count" => container.objects.size, "bytes" => container.bytes_used } end response = Excon::Response.new response.status = 200 response.body = results response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/0000755000004100000410000000000013411315054022707 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/create_message.rb0000644000004100000410000000451413411315054026207 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation posts the specified message or messages. # @note You can submit up to 10 messages in a single request. # # @param [String] client_id UUID for the client instance. # @param [String] queue_name Specifies the name of the queue. # @param [String, Hash, Array] body The body attribute specifies an arbitrary document that constitutes the body of the message being sent. # The size of this body is limited to 256 KB, excluding whitespace. The document must be valid JSON. # @param [Integer] ttl The ttl attribute specifies how long the server waits before releasing the claim. The ttl value must be between 60 and 43200 seconds (12 hours). # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/POST_postMessage__version__queues__queue_name__messages_message-operations-dle001.html def create_message(client_id, queue_name, body, ttl) data = [{ :ttl => ttl, :body => body }] request( :body => Fog::JSON.encode(data), :expects => 201, :method => 'POST', :path => "queues/#{queue_name}/messages", :headers => { 'Client-ID' => client_id } ) end end class Mock def create_message(client_id, queue_name, body, ttl) queue = mock_queue!(queue_name) raise BadRequest.new if body.nil? || body.empty? # Ensure that any Symbol keys within +body+ are converted to Strings, just as being # round-tripped through the API will. converted = MockData.stringify(body) message = queue.add_message(client_id, converted, ttl) response = Excon::Response.new response.status = 201 response.body = { "partial" => false, "resources" => ["#{PATH_BASE}/#{queue_name}/messages/#{message.id}"] } response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/update_claim.rb0000644000004100000410000000241513411315054025665 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation posts the specified message or messages. # @note You can submit up to 10 messages in a single request. # # @param [String] queue_name Specifies the name of the queue. # @param [Integer] ttl The ttl attribute specifies how long the server waits before releasing the claim. The ttl value must be between 60 and 43200 seconds (12 hours). # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/PATCH_updateClaim__version__queues__queue_name__claims__claimId__claims-operations-dle001.html def update_claim(queue_name, claim_id, ttl) body = { :ttl => ttl } request( :body => Fog::JSON.encode(body), :expects => 204, :method => 'PATCH', :path => "queues/#{queue_name}/claims/#{claim_id}" ) end end class Mock def update_claim(queue_name, claim_id, ttl) queue = mock_queue!(queue_name) claim = queue.claim!(claim_id) claim.touch! claim.ttl = ttl response = Excon::Response.new response.status = 204 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/delete_claim.rb0000644000004100000410000000302713411315054025645 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation immediately releases a claim, making any remaining, undeleted) messages that are associated with the claim available to other workers. # Claims with malformed IDs or claims that are not found by ID are ignored. # # @param [String] queue_name Specifies the name of the queue. # @param [String] claim_id Specifies the claim ID. # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/DELETE_deleteClaim__version__queues__queue_name__claims__claimId__claims-operations-dle001.html def delete_claim(queue_name, claim_id) request( :expects => 204, :method => 'DELETE', :path => "queues/#{queue_name}/claims/#{claim_id}" ) end end class Mock def delete_claim(queue_name, claim_id) queue = mock_queue!(queue_name) claim = queue.claim!(claim_id) claim.messages.each do |message| message.claim = nil end queue.claims.delete(claim_id) response = Excon::Response.new response.status = 204 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/get_message.rb0000644000004100000410000000300113411315054025511 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation gets the specified message from the specified queue. # # @param [String] client_id UUID for the client instance. # @param [String] queue_name Specifies the name of the queue. # @param [Integer] message_id Specifies the message ID. # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_getSpecificMessage__version__queues__queue_name__messages__messageId__message-operations-dle001.html def get_message(client_id, queue_name, message_id) request( :expects => 200, :method => 'GET', :path => "queues/#{queue_name}/messages/#{message_id}", :headers => { 'Client-ID' => client_id } ) end end class Mock def get_message(client_id, queue_name, message_id) queue = mock_queue!(queue_name) message = queue.messages.find { |msg| msg.id == message_id } raise NotFound.new unless message response = Excon::Response.new response.status = 200 response.body = message.to_h response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/delete_message.rb0000644000004100000410000000434013411315054026203 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation immediately deletes the specified message. # @note If you do not specify claim_id, but the message is claimed, the operation fails. You can only delete claimed messages by providing an appropriate claim_id. # # @param [String] queue_name Specifies the name of the queue. # @param [String] message_id Specifies the message ID. # @param [Hash] options # @option options [Integer] :claim_id - Identifies the claim. # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/DELETE_deleteMessage__version__queues__queue_name__messages__messageId__message-operations-dle001.html def delete_message(queue_name, message_id, options = {}) query = {} query[:claim_id] = options[:claim_id] if options.key? :claim_id request( :expects => 204, :method => 'DELETE', :path => "queues/#{queue_name}/messages/#{message_id}", :query => query ) end end class Mock def delete_message(queue_name, message_id, options = {}) queue = mock_queue!(queue_name) claim_id = options[:claim_id] message = queue.messages.find { |m| m.id == message_id } perform_delete = true if message && message.claimed? unless message.claim.id == claim_id # Currently returns a 204 without deleting! perform_delete = false end else if claim_id # Currently returns a 204 without deleting! perform_delete = false end end if perform_delete queue.messages.reject! { |m| m.id == message_id } end response = Excon::Response.new response.status = 204 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/create_queue.rb0000644000004100000410000000243013411315054025702 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation creates a new queue. # The body of the request is empty. # # @param [String] queue_name Specifies the name of the queue. # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/PUT_createQueue__version__queues__queue_name__queue-operations-dle001.html def create_queue(queue_name) request( :body => Fog::JSON.encode({}), :expects => 201, :method => 'PUT', :path => "queues/#{queue_name}" ) end end class Mock def create_queue(queue_name) raise MethodNotAllowed.new if queue_name.nil? || queue_name.empty? existed = ! mock_queue(queue_name).nil? add_queue(queue_name) unless existed response = Excon::Response.new response.status = existed ? 201 : 204 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/get_claim.rb0000644000004100000410000000252213411315054025161 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation queries the specified claim for the specified queue. Claims with malformed IDs or claims that are not found by ID are ignored. # # @param [String] queue_name Specifies the name of the queue. # @param [Integer] claim_id Specifies the claim ID. # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_queryClaim__version__queues__queue_name__claims__claimId__claims-operations-dle001.html def get_claim(queue_name, claim_id) request( :expects => 200, :method => 'GET', :path => "queues/#{queue_name}/claims/#{claim_id}" ) end end class Mock def get_claim(queue_name, claim_id) queue = mock_queue!(queue_name) claim = queue.claim!(claim_id) response = Excon::Response.new response.status = 200 response.body = claim.to_h response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/get_queue.rb0000644000004100000410000000221213411315054025214 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation verifies whether the specified queue exists. # # @param [String] queue_name Specifies the name of the queue. # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_checkQueueExists__version__queues__queue_name__queue-operations-dle001.html def get_queue(queue_name) request( :expects => [200, 204], :method => 'GET', :path => "queues/#{queue_name}" ) end end class Mock def get_queue(queue_name) if mock_queue(queue_name).nil? raise NotFound.new else response = Excon::Response.new response.status = 204 response end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/create_claim.rb0000644000004100000410000000550413411315054025650 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation claims a set of messages (up to the value of the limit parameter) from oldest to newest and skips any messages that are already claimed. # If no unclaimed messages are available, the API returns a 204 No Content message. # # @param [String] queue_name Specifies the name of the queue. # @param [Integer] ttl The ttl attribute specifies how long the server waits before releasing the claim. The ttl value must be between 60 and 43200 seconds (12 hours). # @param [Integer] grace The grace attribute specifies the message grace period in seconds. The value of grace value must be between 60 and 43200 seconds (12 hours). # @param [Hash] options # @option options [Integer] :limit - Specifies the number of messages to return, up to 20 messages. If limit is not specified, limit defaults to 10. # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/POST_claimMessages__version__queues__queue_name__claims_claims-operations-dle001.html def create_claim(queue_name, ttl, grace, options = {}) body = { :ttl => ttl, :grace => grace } query = {} query[:limit] = options[:limit] if options.key? :limit request( :body => Fog::JSON.encode(body), :expects => [200, 201, 204], :method => 'POST', :path => "queues/#{queue_name}/claims", :query => query ) end end class Mock def create_claim(queue_name, ttl, grace, options = {}) queue = mock_queue!(queue_name) limit = options[:limit] || 10 claim = queue.add_claim(ttl, grace) claimed = queue.messages.select do |message| ! message.claimed? end.first(limit) if claimed.empty? response = Excon::Response.new response.status = 204 return response end claimed.each do |message| message.claim = claim # Extend the message's lifetime to include the lifetime of the claim, plus the claim's # grace period. message.extend_life end response = Excon::Response.new response.status = 201 response.body = claimed.map { |msg| msg.to_h } response.headers['Location'] = "#{PATH_BASE}/#{queue_name}/claims/#{claim.id}" response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/get_queue_stats.rb0000644000004100000410000000343613411315054026443 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation returns queue statistics, including how many messages are in the queue, categorized by status. # # @param [String] queue_name Specifies the name of the queue. # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_getQueueStats__version__queues__queue_name__stats_queue-operations-dle001.html def get_queue_stats(queue_name) request( :expects => 200, :method => 'GET', :path => "queues/#{queue_name}/stats" ) end end class Mock def get_queue_stats(queue_name) queue = mock_queue!(queue_name) payload = { "claimed" => queue.claimed, "total" => queue.total, "free" => queue.free } report_message(payload, "oldest", queue.oldest) report_message(payload, "newest", queue.newest) response = Excon::Response.new response.status = 200 response.body = { "messages" => payload } response end private def report_message(payload, description, element) return unless element ctime = Time.at(element.created).utc payload[description] = { "age" => element.age, "href" => element.href, "created" => ctime.strftime("%Y-%m-%dT%I:%M:%SZ") } end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/delete_queue.rb0000644000004100000410000000212213411315054025677 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation immediately deletes a queue and all of its existing messages. # # @param [String] queue_name Specifies the name of the queue. # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/DELETE_deleteQueue__version__queues__queue_name__queue-operations-dle001.html def delete_queue(queue_name) request( :expects => 204, :method => 'DELETE', :path => "queues/#{queue_name}" ) end end class Mock def delete_queue(queue_name) data.delete(queue_name) response = Excon::Response.new response.status = 204 response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/list_messages.rb0000644000004100000410000001004513411315054026076 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation gets the message or messages in the specified queue. # # A request to list messages when the queue is not found or when messages are not found returns 204, instead of 200, because there was no information to send back. # Messages with malformed IDs or messages that are not found by ID are ignored. # # @param [String] client_id UUID for the client instance. # @param [String] queue_name Specifies the name of the queue. # @param [Hash] options # @option options [String] :marker - Specifies an opaque string that the client can use to request the next batch of messages. The marker parameter communicates to the # server which messages the client has already received. If you do not specify a value, the API returns all messages at the head of the queue (up to the limit). # @option options [Integer] :limit - When more messages are available than can be returned in a single request, the client can pick up the next batch of messages # by simply using the URI template parameters returned from the previous call in the "next" field. Specifies up to 10 messages (the default value) to return. # If you do not specify a value for the limit parameter, the default value of 10 is used. # @option options [String] :echo - Determines whether the API returns a client's own messages. The echo parameter is a Boolean value (true or false) that determines # whether the API returns a client's own messages, as determined by the uuid portion of the User-Agent header. If you do not specify a value, echo uses the default # value of false. If you are experimenting with the API, you might want to set echo=true in order to see the messages that you posted. # @option options [String] :include_claimed - Determines whether the API returns claimed messages and unclaimed messages. The include_claimed parameter is a Boolean # value (true or false) that determines whether the API returns claimed messages and unclaimed messages. If you do not specify a value, include_claimed uses the # default value of false (only unclaimed messages are returned). # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_getMessages__version__queues__queue_name__messages_message-operations-dle001.html def list_messages(client_id, queue_name, options = {}) request( :expects => [200, 204], :method => 'GET', :path => "queues/#{queue_name}/messages", :headers => { 'Client-ID' => client_id }, :query => options ) end end class Mock def list_messages(client_id, queue_name, options = {}) queue = mock_queue!(queue_name) marker = (options[:marker] || "0").to_i limit = options[:limit] || 10 echo = options[:echo] || false include_claimed = options[:include_claimed] || false next_marker = marker + limit + 1 messages = queue.messages[marker...next_marker] messages.reject! { |m| m.producer_id == client_id } unless echo messages.reject! { |m| m.claimed? } unless include_claimed response = Excon::Response.new if queue.messages.empty? response.status = 204 else response.status = 200 response.body = { "messages" => messages.map { |m| m.to_h }, "links" => [{ "href" => "#{PATH_BASE}/#{queue_name}/messages?marker=#{next_marker}", "rel" => "next" }] } end response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/queues/list_queues.rb0000644000004100000410000000476113411315054025606 0ustar www-datawww-datamodule Fog module Rackspace class Queues class Real # This operation lists queues for the project. The queues are sorted alphabetically by name. # @note A request to list queues when you have no queues in your account returns 204, instead of 200, because there was no information to send back. # # @param [Hash] options # @option options [String] :marker - Specifies the name of the last queue received in a previous request, or none to get the first page of results. # @option options [Integer] :limit - Specifies the name of the last queue received in a previous request, or none to get the first page of results. # @option options [Boolean] :detailed - Determines whether queue metadata is included in the response. The default value for this parameter is false, which excludes t # @return [Excon::Response] response # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_listQueues__version__queues_.html def list_queues(options={}) request( :expects => [200, 204], :method => 'GET', :path => 'queues', :query => options ) end end class Mock def list_queues(options={}) limit = options[:limit] || 10 marker = options[:marker] detailed = options[:detailed] || false queue_names = data.keys.sort start_index = marker.nil? ? 0 : queue_names.count { |name| name <= marker } stop_index = start_index + limit queue_names = queue_names[start_index..stop_index] queue_data = queue_names.map do |qname| { "href" => "#{PATH_BASE}/#{qname}", "name" => qname } end if detailed queue_data.each { |d| d["metadata"] = data[d["name"]].metadata } end response = Excon::Response.new if data.empty? response.status = 204 else response.status = 200 response.body = { "queues" => queue_data, "links" => [{ "href" => "#{PATH_BASE}?marker=#{queue_names.last}", "rel" => "next" }] } end response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/0000755000004100000410000000000013411315054023517 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/create_policy.rb0000644000004100000410000000165713411315054026677 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def create_policy(group_id, options) data = [options] request( :method => 'POST', :body => Fog::JSON.encode(data), :path => "groups/#{group_id}/policies", :expects => 201 ) end end class Mock def create_policy(group_id, options) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end policy = { "id" => Fog::Rackspace::MockData.uuid, "name" => "set group to 5 servers", "desiredCapacity" => 5, "cooldown" => 1800, "type" => "webhook" } group['scalingPolicies'] << policy body = [policy] response(:body => body) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/delete_group.rb0000644000004100000410000000067113411315054026526 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def delete_group(group_id) request( :expects => [204], :method => 'DELETE', :path => "groups/#{group_id}" ) end end class Mock def delete_group(group_id) self.data[:autoscale_groups].delete(group_id) response(:status => 204) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/get_group.rb0000644000004100000410000000106013411315054026034 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def get_group(group_id) request( :expects => [200], :method => 'GET', :path => "groups/#{group_id}" ) end end class Mock def get_group(group_id) group = self.data[:autoscale_groups][group_id] if server.nil? raise Fog::Rackspace::AutoScale::NotFound else response(:body => {"group" => group}) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/execute_policy.rb0000644000004100000410000000067413411315054027074 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def execute_policy(group_id, policy_id) request( :expects => [202], :method => 'POST', :path => "groups/#{group_id}/policies/#{policy_id}/execute" ) end end class Mock def execute_policy(group_id, policy_id) response(:status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/get_launch_config.rb0000644000004100000410000000113413411315054027501 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def get_launch_config(group_id) request( :expects => [200], :method => 'GET', :path => "groups/#{group_id}/launch" ) end end class Mock def get_launch_config(group_id) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end response(:body => {"launchConfiguration" => group['launchConfiguration']}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/resume_group_state.rb0000644000004100000410000000063013411315054027757 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def resume_group_state(group_id) request( :expects => [204], :method => 'POST', :path => "groups/#{group_id}/resume" ) end end class Mock def resume_group_state(group_id) Fog::Mock.not_implemented end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/list_policies.rb0000644000004100000410000000075113411315054026711 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def list_policies(group_id) request( :expects => [200], :method => 'GET', :path => "groups/#{group_id}/policies" ) end end class Mock def list_policies(group_id) group = self.data[:autoscale_groups][group_id] response(:body => {'policies' => group['scalingPolicies']}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/update_launch_config.rb0000644000004100000410000000146613411315054030214 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def update_launch_config(group_id, options) body = options request( :expects => [204], :method => 'PUT', :path => "groups/#{group_id}/launch", :body => Fog::JSON.encode(body) ) end end class Mock def update_launch_config(group_id, options) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end config = group['launchConfiguration'] config['args'] = options['args'] if options['args'] config['type'] = options['type'] if options['type'] request(:body => config) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/delete_webhook.rb0000644000004100000410000000154513411315054027031 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def delete_webhook(group_id, policy_id, webhook_id) request( :expects => [204], :method => 'DELETE', :path => "groups/#{group_id}/policies/#{policy_id}/webhooks/#{webhook_id}" ) end end class Mock def delete_webhook(group_id, policy_id, webhook_id) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end policy = group['policies'].find { |p| p["id"] == policy_id } if policy.nil? raise Fog::Rackspace::AutoScale::NotFound end policy['webhooks'].delete_if { |w| w['id'] == webhook_id } response(:status => 204) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/get_group_state.rb0000644000004100000410000000312113411315054027234 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def get_group_state(group_id) request( :expects => [200], :method => 'GET', :path => "groups/#{group_id}/state" ) end end class Mock def get_group_state(group_id) instance_id_1 = Fog::Rackspace::AutoScale::MockData.uuid instance_id_2 = Fog::Rackspace::AutoScale::MockData.uuid state = { "id" => group_id, "links" => [ { "href" => "https://dfw.autoscale.api.rackspacecloud.com/v1.0/010101/groups/#{group_id}", "rel" => "self" } ], "active" => [ { "id" => "#{instance_id_1}", "links" => [ { "href" => "https://dfw.servers.api.rackspacecloud.com/v2/010101/servers/#{instance_id_1}", "rel" => "self" } ] }, { "id" => "#{instance_id_2}", "links" => [ { "href" => "https://dfw.servers.api.rackspacecloud.com/v2/010101/servers/#{instance_id_2}", "rel" => "self" } ] } ], "activeCapacity" => 2, "pendingCapacity" => 2, "desiredCapacity" => 4, "paused" => false } response(:body => {'group' => state}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/create_webhook.rb0000644000004100000410000000310413411315054027023 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def create_webhook(group_id, policy_id, options) body = [options] request( :method => 'POST', :body => Fog::JSON.encode(body), :path => "groups/#{group_id}/policies/#{policy_id}/webhooks", :expects => 201 ) end end class Mock def create_webhook(group_id, policy_id, options) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end policy = group['scalingPolicies'].find { |p| p["id"] == policy_id } if policy.nil? raise Fog::Rackspace::AutoScale::NotFound end webhook_id = Fog::Rackspace::MockData.uuid webhook = {} webhook['id'] = webhook_id webhook['name'] = options['name'] || 'new webhook' webhook['metadata'] = options['name'] || {} webhook["links"] = [ { "href" => "https://ord.autoscale.api.rackspacecloud.com/v1.0/829409/groups/#{group_id}/policies/#{policy_id}/webhooks/#{webhook_id}/", "rel" => "self" }, { "href" => "https://ord.autoscale.api.rackspacecloud.com/v1.0/829409/execute/1/sadfadsfasdfvcjsdfsjvreaigae5", "rel" => "capability" } ] policy['webhooks'] << webhook body = {'webhook' => webhook} response(:body => body) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/update_webhook.rb0000644000004100000410000000211113411315054027037 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def update_webhook(group_id, policy_id, webhook_id, options) body = options request( :expects => [204], :method => 'PUT', :path => "groups/#{group_id}/policies/#{policy_id}/webhooks/#{webhook_id}", :body => Fog::JSON.encode(body) ) end end class Mock def update_webhook(group_id, policy_id, webhook_id, options) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end policy = group['scalingPolicies'].find { |p| p["id"] == policy_id } if policy.nil? raise Fog::Rackspace::AutoScale::NotFound end webhook = policy['webhooks'].find { |w| w['id'] == webhook_id } if webhook.nil? raise Fog::Rackspace::AutoScale::NotFound end webhook.merge(options) response(:body => webhook) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/list_webhooks.rb0000644000004100000410000000143013411315054026716 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def list_webhooks(group_id, policy_id) request( :expects => [200], :method => 'GET', :path => "groups/#{group_id}/policies/#{policy_id}/webhooks" ) end end class Mock def list_webhooks(group_id, policy_id) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end policy = group['scalingPolicies'].find { |p| p["id"] == policy_id } if policy.nil? raise Fog::Rackspace::AutoScale::NotFound end response(:body => {'webhooks' => policy['webhooks']}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/delete_policy.rb0000644000004100000410000000121613411315054026665 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def delete_policy(group_id, policy_id) request( :expects => [204], :method => 'DELETE', :path => "groups/#{group_id}/policies/#{policy_id}" ) end end class Mock def delete_group(group_id, policy_id) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end group['policies'].delete_if { |p| p['id'] == policy_id } response(:status => 204) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/get_policy.rb0000644000004100000410000000137313411315054026206 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def get_policy(group_id, policy_id) request( :expects => [200], :method => 'GET', :path => "groups/#{group_id}/policies/#{policy_id}" ) end end class Mock def get_policy(group_id, policy_id) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end policy = group['scalingPolicies'].find { |p| p["id"] == policy_id } if policy.nil? raise Fog::Rackspace::AutoScale::NotFound end response(:body => {'policy' => policy}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/create_group.rb0000644000004100000410000000317713411315054026533 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def create_group(launch_config, group_config, policies) body = { 'launchConfiguration' => launch_config, 'groupConfiguration' => group_config, 'scalingPolicies' => policies } request( :expects => [201], :method => 'POST', :path => 'groups', :body => Fog::JSON.encode(body) ) end end class Mock def create_group(launch_config, group_config, policies) group_id = Fog::Rackspace::MockData.uuid # Construct group structure group = { 'launchConfiguration' => launch_config, 'groupConfiguration' => group_config, 'scalingPolicies' => policies, 'id' => group_id } # Add links for HTTP response group['scalingPolicies'][0]['links'] = [ { "href" => "https://ord.autoscale.api.rackspacecloud.com/v1.0/829409/groups/6791761b-821a-4d07-820d-0b2afc7dd7f6/policies/dceb14ac-b2b3-4f06-aac9-a5b6cd5d40e1/", "rel" => "self" } ] group['links'] = [ { "href" => "https://ord.autoscale.api.rackspacecloud.com/v1.0/829409/groups/6791761b-821a-4d07-820d-0b2afc7dd7f6/", "rel" => "self" } ] # Save for future use self.data[:autoscale_groups][group_id] = group # Response body = {'group' => group} response(:body => body) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/pause_group_state.rb0000644000004100000410000000070313411315054027575 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def pause_group_state(group_id) Fog::Real.not_implemented # request( # :expects => [204], # :method => 'POST', # :path => 'groups/#{group_id}/pause' # ) end end class Mock def pause_group_state(group_id) Fog::Mock.not_implemented end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/get_group_config.rb0000644000004100000410000000113013411315054027357 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def get_group_config(group_id) request( :expects => [200], :method => 'GET', :path => "groups/#{group_id}/config" ) end end class Mock def get_group_config(group_id) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end response(:body => {"groupConfiguration" => group['groupConfiguration']}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/update_group_config.rb0000644000004100000410000000205713411315054030073 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def update_group_config(group_id, options) body = options request( :expects => [204], :method => 'PUT', :path => "groups/#{group_id}/config", :body => Fog::JSON.encode(body) ) end end class Mock def update_group_config(group_id, options) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end config = group['groupConfiguration'] config['name'] = options['name'] if options['name'] config['cooldown'] = options['cooldown'] if options['cooldown'] config['minEntities'] = options['minEntities'] if options['minEntities'] config['maxEntities'] = options['maxEntities'] if options['maxEntities'] config['metadata'] = options['metadata'] if options['metadata'] request(:body => config) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/execute_anonymous_webhook.rb0000644000004100000410000000076213411315054031341 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def execute_anonymous_webhook(capability_version, capability_hash) request( :expects => [202], :method => 'POST', :path => "execute/#{capability_version}/#{capability_hash}" ) end end class Mock def execute_anonymous_webhook(capability_version, capability_hash) response(:status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/get_webhook.rb0000644000004100000410000000172713411315054026350 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def get_webhook(group_id, policy_id, webhook_id) request( :expects => [200], :method => 'GET', :path => "groups/#{group_id}/policies/#{policy_id}/webhooks/#{webhook_id}" ) end end class Mock def get_webhook(group_id, policy_id, webhook_id) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end policy = group['scalingPolicies'].find { |p| p["id"] == policy_id } if policy.nil? raise Fog::Rackspace::AutoScale::NotFound end webhook = policy['webhooks'].find { |w| w['id'] == webhook_id } if webhook.nil? raise Fog::Rackspace::AutoScale::NotFound end response(:body => {'webhook' => webhook}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/list_groups.rb0000644000004100000410000000205413411315054026417 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real # Retrieves a list of images # @return [Excon::Response] response: # * body [Hash]: # * images [Array]: # * [Hash]: # * id [String] - flavor id # * links [Array] - image links # * name [String] - image name # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Flavors-d1e4188.html def list_groups request( :expects => [200], :method => 'GET', :path => 'groups' ) end end class Mock def list_groups response(:body => {"groups" => self.data[:autoscale_groups]}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/auto_scale/update_policy.rb0000644000004100000410000000137013411315054026706 0ustar www-datawww-datamodule Fog module Rackspace class AutoScale class Real def update_policy(group_id, policy_id, options) request( :expects => [204], :method => 'PUT', :path => "groups/#{group_id}/policies/#{policy_id}", :body => Fog::JSON.encode(options) ) end end class Mock def update_policy(group_id, policy_id, options) group = self.data[:autoscale_groups][group_id] if group.nil? raise Fog::Rackspace::AutoScale::NotFound end policy = group['scalingPolicies'].find { |p| p["id"] == policy_id } policy.merge(options) request(:body => policy) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking/0000755000004100000410000000000013411315054023567 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/requests/networking/list_networks.rb0000644000004100000410000000060013411315054027017 0ustar www-datawww-datamodule Fog module Rackspace class Networking class Real def list_networks request(:method => 'GET', :path => 'os-networksv2', :expects => 200) end end class Mock def list_networks networks = self.data[:networks].values response(:body => { 'networks' => networks }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking/list_virtual_interfaces.rb0000644000004100000410000000140713411315054031042 0ustar www-datawww-datamodule Fog module Rackspace class Networking class Real # Lists virtual interfaces for a server # @param [String] server_id # @raise [Fog::Rackspace::Networking::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Networking::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Networking::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Networking::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/list_virt_interfaces.html def list_virtual_interfaces(server_id) request( :expects => [200], :method => 'GET', :path => "servers/#{server_id}/os-virtual-interfacesv2" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking/delete_network.rb0000644000004100000410000000071713411315054027134 0ustar www-datawww-datamodule Fog module Rackspace class Networking class Real def delete_network(id) request(:method => 'DELETE', :path => "os-networksv2/#{id}", :expects => 202) end end class Mock def delete_network(id) unless self.data[:networks].key?(id) raise Fog::Rackspace::Networking::NotFound end response(:body => '', :status => 202) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking/create_network.rb0000644000004100000410000000146013411315054027131 0ustar www-datawww-datamodule Fog module Rackspace class Networking class Real def create_network(label, cidr) data = { 'network' => { 'label' => label, 'cidr' => cidr } } request( :method => 'POST', :body => Fog::JSON.encode(data), :path => "os-networksv2", :expects => 200 ) end end class Mock def create_network(label, cidr) network_id = Fog::Rackspace::MockData.uuid self.data[:networks][network_id] = { 'id' => network_id, 'label' => label, 'cidr' => cidr } response(:body => { 'network' => self.data[:networks][network_id] }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking/get_network.rb0000644000004100000410000000073513411315054026451 0ustar www-datawww-datamodule Fog module Rackspace class Networking class Real def get_network(id) request(:method => 'GET', :path => "os-networksv2/#{id}", :expects => 200) end end class Mock def get_network(id) unless self.data[:networks].key?(id) raise Fog::Rackspace::Networking::NotFound end response(:body => { 'network' => self.data[:networks][id] }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking/create_virtual_interface.rb0000644000004100000410000000211513411315054031144 0ustar www-datawww-datamodule Fog module Rackspace class Networking class Real # Creates virtual interface for a server # @param [String] server_id The server id to create the virtual interface on # @param [String] network_id The network id to attach the virtual interface to # @raise [Fog::Rackspace::Networking::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Networking::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Networking::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Networking::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/api_create_virtual_interface.html def create_virtual_interface(server_id, network_id) data = { :virtual_interface => { :network_id => network_id } } request( :expects => [200], :method => 'POST', :path => "servers/#{server_id}/os-virtual-interfacesv2", :body => Fog::JSON.encode(data) ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/requests/networking/delete_virtual_interface.rb0000644000004100000410000000164713411315054031154 0ustar www-datawww-datamodule Fog module Rackspace class Networking class Real # Deletes virtual interface from server # @param [String] server_id The server id that contains the virtual interface # @param [String] interface_id The id of the virtual interface # @raise [Fog::Rackspace::Networking::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Networking::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Networking::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Networking::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/delete_virt_interface_api.html def delete_virtual_interface(server_id, interface_id) request( :expects => [200], :method => 'DELETE', :path => "servers/#{server_id}/os-virtual-interfacesv2/#{interface_id}" ) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/compute.rb0000644000004100000410000002255713411315054021541 0ustar www-datawww-data module Fog module Compute class Rackspace < Fog::Service include Fog::Rackspace::Errors class ServiceError < Fog::Rackspace::Errors::ServiceError; end class InternalServerError < Fog::Rackspace::Errors::InternalServerError; end class BadRequest < Fog::Rackspace::Errors::BadRequest; end requires :rackspace_api_key, :rackspace_username recognizes :rackspace_auth_url, :rackspace_servicenet, :persistent recognizes :rackspace_auth_token, :rackspace_management_url, :rackspace_compute_v1_url, :rackspace_region model_path 'fog/rackspace/models/compute' model :flavor collection :flavors model :image collection :images model :server collection :servers request_path 'fog/rackspace/requests/compute' request :confirm_resized_server request :create_image request :create_server request :delete_image request :delete_server request :get_flavor_details request :get_image_details request :get_server_details request :list_addresses request :list_private_addresses request :list_public_addresses request :list_flavors request :list_flavors_detail request :list_images request :list_images_detail request :list_servers request :list_servers_detail request :reboot_server request :revert_resized_server request :resize_server request :server_action request :update_server class Mock < Fog::Rackspace::Service def self.data @data ||= Hash.new do |hash, key| hash[key] = { :last_modified => { :images => {}, :servers => {} }, :servers => {}, :images => { 112 => {'id' => 112, 'status' => "ACTIVE", 'updated' => "2011-04-21T10:24:01-05:00", 'name' => "Ubuntu 10.04 LTS"}, 100 => {'id' => 100, 'status' => "ACTIVE", 'updated' => "2011-09-12T09:09:23-05:00", 'name' => "Arch 2011.10"}, 31 => {'id' => 31, 'status' => "ACTIVE", 'updated' => "2010-01-26T12:07:44-06:00", 'name' => "Windows Server 2008 SP2 x86"}, 108 => {'id' => 108, 'status' => "ACTIVE", 'updated' => "2011-11-01T08:32:30-05:00", 'name' => "Gentoo 11.0"}, 109 => {'id' => 109, 'status' => "ACTIVE", 'updated' => "2011-11-03T06:28:56-05:00", 'name' => "openSUSE 12"}, 89 => {'id' => 89, 'status' => "ACTIVE", 'updated' => "2011-10-04T08:39:34-05:00", 'name' => "Windows Server 2008 R2 x64 - SQL2K8R2 Web"}, 24 => {'id' => 24, 'status' => "ACTIVE", 'updated' => "2010-01-26T12:07:04-06:00", 'name' => "Windows Server 2008 SP2 x64"}, 110 => {'id' => 110, 'status' => "ACTIVE", 'updated' => "2011-08-17T05:11:30-05:00", 'name' => "Red Hat Enterprise Linux 5.5"}, 57 => {'id' => 57, 'status' => "ACTIVE", 'updated' => "2010-09-17T07:16:25-05:00", 'name' => "Windows Server 2008 SP2 x64 - MSSQL2K8R2"}, 85 => {'id' => 85, 'status' => "ACTIVE", 'updated' => "2010-01-26T12:07:17-06:00", 'name' => "Windows Server 2008 R2 x64"}, 111 => {'id' => 111, 'status' => "ACTIVE", 'updated' => "2011-09-12T10:53:12-05:00", 'name' => "Red Hat Enterprise Linux 6"}, 120 => {'id' => 120, 'status' => "ACTIVE", 'updated' => "2012-01-03T04:39:05-06:00", 'name' => "Fedora 16"}, 119 => {'id' => 119, 'status' => "ACTIVE", 'updated' => "2011-11-03T08:55:15-05:00", 'name' => "Ubuntu 11.10"}, 116 => {'id' => 116, 'status' => "ACTIVE", 'updated' => "2011-08-17T05:11:30-05:00", 'name' => "Fedora 15"}, 56 => {'id' => 56, 'status' => "ACTIVE", 'updated' => "2010-09-17T07:12:56-05:00", 'name' => "Windows Server 2008 SP2 x86 - MSSQL2K8R2"}, 114 => {'id' => 114, 'status' => "ACTIVE", 'updated' => "2011-08-17T05:11:30-05:00", 'name' => "CentOS 5.6"}, 86 => {'id' => 86, 'status' => "ACTIVE", 'updated' => "2010-09-17T07:19:20-05:00", 'name' => "Windows Server 2008 R2 x64 - MSSQL2K8R2"}, 115 => {'id' => 115, 'status' => "ACTIVE", 'updated' => "2011-08-17T05:11:30-05:00", 'name' => "Ubuntu 11.04"}, 103 => {'id' => 103, 'status' => "ACTIVE", 'updated' => "2011-08-17T05:11:30-05:00", 'name' => "Debian 5 (Lenny)"}, 104 => {'id' => 104, 'status' => "ACTIVE", 'updated' => "2011-08-17T05:11:30-05:00", 'name' => "Debian 6 (Squeeze)"}, 118 => {'id' => 118, 'status' => "ACTIVE", 'updated' => "2011-08-17T05:11:30-05:00", 'name' => "CentOS 6.0"} } } end end def self.reset @data = nil end def initialize(options={}) @rackspace_username = options[:rackspace_username] end def data self.class.data[@rackspace_username] end def reset_data self.class.data.delete(@rackspace_username) end end class Real < Fog::Rackspace::Service def initialize(options={}) @rackspace_api_key = options[:rackspace_api_key] @rackspace_username = options[:rackspace_username] @rackspace_auth_url = options[:rackspace_auth_url] @rackspace_servicenet = options[:rackspace_servicenet] @rackspace_auth_token = options[:rackspace_auth_token] @rackspace_endpoint = Fog::Rackspace.normalize_url(options[:rackspace_compute_v1_url] || options[:rackspace_management_url]) @connection_options = options[:connection_options] || {} authenticate Excon.defaults[:ssl_verify_peer] = false if service_net? @persistent = options[:persistent] || false @connection = Fog::Core::Connection.new(endpoint_uri.to_s, @persistent, @connection_options) end def reload @connection.reset end def request(params, parse_json = true) super rescue Excon::Errors::NotFound => error raise NotFound.slurp(error, self) rescue Excon::Errors::BadRequest => error raise BadRequest.slurp(error, self) rescue Excon::Errors::InternalServerError => error raise InternalServerError.slurp(error, self) rescue Excon::Errors::HTTPStatusError => error raise ServiceError.slurp(error, self) end def service_net? @rackspace_servicenet == true end def authenticate(options={}) super({ :rackspace_api_key => @rackspace_api_key, :rackspace_username => @rackspace_username, :rackspace_auth_url => @rackspace_auth_url, :connection_options => @connection_options }) end def service_name :cloudServers end def region @rackspace_region end def endpoint_uri(service_endpoint_url=nil) return @uri if @uri super(@rackspace_endpoint || service_endpoint_url, :rackspace_compute_v1_url) end private def deprecation_warnings(options) Fog::Logger.deprecation("The :rackspace_management_url option is deprecated. Please use :rackspace_compute_v1_url for custom endpoints") if options[:rackspace_management_url] end def authenticate_v1(options) credentials = Fog::Rackspace.authenticate(options, @connection_options) endpoint_uri credentials['X-Server-Management-Url'] @auth_token = credentials['X-Auth-Token'] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/networking_v2.rb0000644000004100000410000001641313411315054022655 0ustar www-datawww-data module Fog module Rackspace class NetworkingV2 < Fog::Service include Fog::Rackspace::Errors class ServiceError < Fog::Rackspace::Errors::ServiceError; end class InternalServerError < Fog::Rackspace::Errors::InternalServerError; end class BadRequest < Fog::Rackspace::Errors::BadRequest; end NETWORKS_DFW_URL = "https://dfw.networks.api.rackspacecloud.com/v2.0" NETWORKS_LON_URL = "https://lon.networks.api.rackspacecloud.com/v2.0" NETWORKS_IAD_URL = "https://iad.networks.api.rackspacecloud.com/v2.0" NETWORKS_ORD_URL = "https://ord.networks.api.rackspacecloud.com/v2.0" class InvalidStateException < ::RuntimeError attr_reader :desired_state attr_reader :current_state def initialize(desired_state, current_state) @desired_state = desired_state @current_state = current_state end end class InvalidServerStateException < InvalidStateException def to_s "Server should have transitioned to '#{desired_state}' not '#{current_state}'" end end class InvalidImageStateException < InvalidStateException def to_s "Image should have transitioned to '#{desired_state}' not '#{current_state}'" end end requires :rackspace_username, :rackspace_api_key recognizes :rackspace_endpoint recognizes :rackspace_auth_url recognizes :rackspace_auth_token recognizes :rackspace_region recognizes :rackspace_networking_v2_url model_path 'fog/rackspace/models/networking_v2' model :network collection :networks model :subnet collection :subnets model :port collection :ports model :security_group collection :security_groups model :security_group_rule collection :security_group_rules request_path 'fog/rackspace/requests/networking_v2' request :list_networks request :create_network request :show_network request :update_network request :delete_network request :list_subnets request :create_subnet request :show_subnet request :update_subnet request :delete_subnet request :list_ports request :create_port request :show_port request :update_port request :delete_port request :list_security_groups request :create_security_group request :show_security_group request :update_security_group request :delete_security_group request :list_security_group_rules request :create_security_group_rule request :show_security_group_rule request :delete_security_group_rule class Mock < Fog::Rackspace::Service include Fog::Rackspace::MockData def initialize(options) @rackspace_api_key = options[:rackspace_api_key] end def request(params) Fog::Mock.not_implemented end def response(params={}) body = params[:body] || {} status = params[:status] || 200 headers = params[:headers] || {} response = Excon::Response.new(:body => body, :headers => headers, :status => status) if params.key?(:expects) && ![*params[:expects]].include?(response.status) raise(Excon::Errors.status_error(params, response)) else response end end end class Real < Fog::Rackspace::Service def initialize(options = {}) @rackspace_api_key = options[:rackspace_api_key] @rackspace_username = options[:rackspace_username] @rackspace_auth_url = options[:rackspace_auth_url] setup_custom_endpoint(options) @rackspace_must_reauthenticate = false @connection_options = options[:connection_options] || {} authenticate deprecation_warnings(options) @persistent = options[:persistent] || false @connection = Fog::Core::Connection.new(endpoint_uri.to_s, @persistent, @connection_options) end def request(params, parse_json = true) super rescue Excon::Errors::NotFound => error raise NotFound.slurp(error, self) rescue Excon::Errors::BadRequest => error raise BadRequest.slurp(error, self) rescue Excon::Errors::InternalServerError => error raise InternalServerError.slurp(error, self) rescue Excon::Errors::HTTPStatusError => error raise ServiceError.slurp(error, self) end def authenticate(options={}) super({ :rackspace_api_key => @rackspace_api_key, :rackspace_username => @rackspace_username, :rackspace_auth_url => @rackspace_auth_url, :connection_options => @connection_options }) end def service_name :cloudNetworks end def request_id_header "x-networks-request-id" end def region @rackspace_region end def endpoint_uri(service_endpoint_url=nil) @uri = super(@rackspace_endpoint || service_endpoint_url, :rackspace_networking_v2_url) end private def setup_custom_endpoint(options) @rackspace_endpoint = Fog::Rackspace.normalize_url(options[:rackspace_networking_v2_url] || options[:rackspace_endpoint]) if v2_authentication? case @rackspace_endpoint when NETWORKS_DFW_URL @rackspace_endpoint = nil @rackspace_region = :dfw when NETWORKS_ORD_URL @rackspace_endpoint = nil @rackspace_region = :ord when NETWORKS_LON_URL @rackspace_endpoint = nil @rackspace_region = :lon else # we are actually using a custom endpoint @rackspace_region = options[:rackspace_region] end else #if we are using auth1 and the endpoint is not set, default to NETWORKS_DFW_URL for historical reasons @rackspace_endpoint ||= NETWORKS_DFW_URL end end def deprecation_warnings(options) Fog::Logger.deprecation("The :rackspace_endpoint option is deprecated. Please use :rackspace_networking_v2_url for custom endpoints") if options[:rackspace_endpoint] if [NETWORKS_DFW_URL, NETWORKS_ORD_URL, NETWORKS_LON_URL].include?(@rackspace_endpoint) && v2_authentication? regions = @identity_service.service_catalog.display_service_regions(service_name) Fog::Logger.deprecation("Please specify region using :rackspace_region rather than :rackspace_endpoint. Valid regions for :rackspace_region are #{regions}.") end end def append_tenant_v1(credentials) account_id = credentials['X-Server-Management-Url'].match(/.*\/([\d]+)$/)[1] endpoint = @rackspace_endpoint || credentials['X-Server-Management-Url'] || NETWORKS_DFW_URL @uri = URI.parse(endpoint) @uri.path = "#{@uri.path}/#{account_id}" end def authenticate_v1(options) credentials = Fog::Rackspace.authenticate(options, @connection_options) append_tenant_v1 credentials @auth_token = credentials['X-Auth-Token'] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/monitoring.rb0000644000004100000410000001347213411315054022246 0ustar www-datawww-data # This class originally came from the rackspace-monitoring gem located here: # https://github.com/racker/rackspace-monitoring-rb # It has been heavily modified for import into Fog master. module Fog module Rackspace class Monitoring < Fog::Service include Fog::Rackspace::Errors class IdentifierTaken < Fog::Errors::Error; end class ServiceError < Fog::Rackspace::Errors::ServiceError; end class InternalServerError < Fog::Rackspace::Errors::InternalServerError; end class Conflict < Fog::Rackspace::Errors::Conflict; end class ServiceUnavailable < Fog::Rackspace::Errors::ServiceUnavailable; end class BadRequest < Fog::Rackspace::Errors::BadRequest attr_reader :validation_errors def self.slurp(error, service=nil) new_error = super(error) if new_error.response_data && new_error.response_data['details'] new_error.instance_variable_set(:@validation_errors, new_error.response_data['details']) end status_code = error.response ? error.response.status : nil new_error.instance_variable_set(:@status_code, status_code) new_error.set_transaction_id(error, service) new_error end end requires :rackspace_api_key, :rackspace_username recognizes :rackspace_auth_url recognizes :persistent recognizes :rackspace_monitoring_url recognizes :rackspace_region model_path 'fog/rackspace/models/monitoring' model :entity collection :entities model :check collection :checks model :alarm collection :alarms model :alarm_example collection :alarm_examples model :agent_token collection :agent_tokens model :metric collection :metrics model :data_point collection :data_points model :check_type collection :check_types model :notification collection :notifications request_path 'fog/rackspace/requests/monitoring' request :list_agent_tokens request :list_agents request :list_alarms request :list_alarm_examples request :list_checks request :list_entities request :list_metrics request :list_data_points request :list_check_types request :list_overview request :list_notification_plans request :list_notifications request :get_agent request :get_agent_token request :get_alarm request :get_alarm_example request :get_check request :get_entity request :get_notification request :get_cpus_info request :get_disks_info request :get_filesystems_info request :get_memory_info request :get_network_interfaces_info request :get_processes_info request :get_system_info request :get_logged_in_user_info request :create_agent_token request :create_alarm request :create_check request :create_entity request :create_notification request :update_check request :update_entity request :update_alarm request :update_notification request :delete_agent_token request :delete_alarm request :delete_check request :delete_entity request :delete_notification request :evaluate_alarm_example request :list_monitoring_zones request :get_monitoring_zone class Mock < Fog::Rackspace::Service def initialize(options={}) end def request(params) Fog::Mock.not_implemented end end class Real < Fog::Rackspace::Service def service_name :cloudMonitoring end def region @rackspace_region end def initialize(options={}) @rackspace_api_key = options[:rackspace_api_key] @rackspace_username = options[:rackspace_username] @rackspace_auth_url = options[:rackspace_auth_url] @connection_options = options[:connection_options] || {} @rackspace_endpoint = Fog::Rackspace.normalize_url(options[:rackspace_monitoring_url]) authenticate @persistent = options[:persistent] || false @connection = Fog::Core::Connection.new(endpoint_uri.to_s, @persistent, @connection_options) end def reload @connection.reset end def endpoint_uri(service_endpoint_url=nil) @uri = super(@rackspace_endpoint || service_endpoint_url, :rackspace_monitoring_url) end def request_id_header "X-Response-Id" end private def request(params, parse_json = true) super rescue Excon::Errors::BadRequest => error raise BadRequest.slurp(error, self) rescue Excon::Errors::Conflict => error raise Conflict.slurp(error, self) rescue Excon::Errors::NotFound => error raise NotFound.slurp(error, self) rescue Excon::Errors::ServiceUnavailable => error raise ServiceUnavailable.slurp(error, self) rescue Excon::Errors::InternalServerError => error raise InternalServerError.slurp(error, self) rescue Excon::Errors::HTTPStatusError => error raise ServiceError.slurp(error, self) end def authenticate options = { :rackspace_api_key => @rackspace_api_key, :rackspace_username => @rackspace_username, :rackspace_auth_url => @rackspace_auth_url, :connection_options => @connection_options } super(options) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/0000755000004100000410000000000013411315054021010 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/0000755000004100000410000000000013411315054023606 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/subnet.rb0000644000004100000410000000143313411315054025434 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Subnet < Fog::Model identity :id attribute :name attribute :enable_dhcp attribute :network_id attribute :tenant_id attribute :dns_nameservers attribute :allocation_pools attribute :host_routes attribute :ip_version attribute :gateway_ip attribute :cidr def save data = unless self.id.nil? service.update_subnet(self) else service.create_subnet(self) end merge_attributes(data.body['subnet']) true end def destroy requires :identity service.delete_subnet(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/security_group_rule.rb0000644000004100000410000000152213411315054030245 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class SecurityGroupRule < Fog::Model identity :id attribute :direction attribute :ethertype attribute :port_range_max attribute :port_range_min attribute :protocol attribute :remote_group_id attribute :remote_ip_prefix attribute :security_group_id attribute :tenant_id def save data = unless self.id.nil? service.update_security_group_rule(self) else service.create_security_group_rule(self) end merge_attributes(data.body['security_group_rule']) true end def destroy requires :identity service.delete_security_group_rule(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/security_group_rules.rb0000644000004100000410000000111713411315054030430 0ustar www-datawww-datarequire 'fog/rackspace/models/networking_v2/security_group_rule' module Fog module Rackspace class NetworkingV2 class SecurityGroupRules < Fog::Collection model Fog::Rackspace::NetworkingV2::SecurityGroupRule def all data = service.list_security_group_rules.body['security_group_rules'] load(data) end def get(id) data = service.show_security_group_rule(id).body['security_group_rule'] new(data) rescue Fog::Rackspace::NetworkingV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/security_group.rb0000644000004100000410000000115313411315054027216 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class SecurityGroup < Fog::Model identity :id attribute :name attribute :description attribute :tenant_id def save data = unless self.id.nil? service.update_security_group(self) else service.create_security_group(self) end merge_attributes(data.body['security_group']) true end def destroy requires :identity service.delete_security_group(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/subnets.rb0000644000004100000410000000077013411315054025622 0ustar www-datawww-datarequire 'fog/rackspace/models/networking_v2/subnet' module Fog module Rackspace class NetworkingV2 class Subnets < Fog::Collection model Fog::Rackspace::NetworkingV2::Subnet def all data = service.list_subnets.body['subnets'] load(data) end def get(id) data = service.show_subnet(id).body['subnet'] new(data) rescue Fog::Rackspace::NetworkingV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/network.rb0000644000004100000410000000126413411315054025627 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Network < Fog::Model identity :id attribute :admin_state_up attribute :label attribute :name attribute :shared attribute :status attribute :subnets attribute :tenant_id def save data = unless self.id.nil? service.update_network(self) else service.create_network(self) end merge_attributes(data.body['network']) true end def destroy requires :identity service.delete_network(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/port.rb0000644000004100000410000000142113411315054025115 0ustar www-datawww-datamodule Fog module Rackspace class NetworkingV2 class Port < Fog::Model identity :id attribute :admin_state_up attribute :device_id attribute :device_owner attribute :fixed_ips attribute :mac_address attribute :name attribute :network_id attribute :security_groups attribute :status attribute :tenant_id def save data = unless self.id.nil? service.update_port(self) else service.create_port(self) end merge_attributes(data.body['port']) true end def destroy requires :identity service.delete_port(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/security_groups.rb0000644000004100000410000000105613411315054027403 0ustar www-datawww-datarequire 'fog/rackspace/models/networking_v2/security_group' module Fog module Rackspace class NetworkingV2 class SecurityGroups < Fog::Collection model Fog::Rackspace::NetworkingV2::SecurityGroup def all data = service.list_security_groups.body['security_groups'] load(data) end def get(id) data = service.show_security_group(id).body['security_group'] new(data) rescue Fog::Rackspace::NetworkingV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/ports.rb0000644000004100000410000000075213411315054025306 0ustar www-datawww-datarequire 'fog/rackspace/models/networking_v2/port' module Fog module Rackspace class NetworkingV2 class Ports < Fog::Collection model Fog::Rackspace::NetworkingV2::Port def all data = service.list_ports.body['ports'] load(data) end def get(id) data = service.show_port(id).body['port'] new(data) rescue Fog::Rackspace::NetworkingV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking_v2/networks.rb0000644000004100000410000000077713411315054026022 0ustar www-datawww-datarequire 'fog/rackspace/models/networking_v2/network' module Fog module Rackspace class NetworkingV2 class Networks < Fog::Collection model Fog::Rackspace::NetworkingV2::Network def all data = service.list_networks.body['networks'] load(data) end def get(id) data = service.show_network(id).body['network'] new(data) rescue Fog::Rackspace::NetworkingV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/identity/0000755000004100000410000000000013411315054022641 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/identity/tenants.rb0000644000004100000410000000104213411315054024637 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/identity/tenant' module Fog module Rackspace class Identity class Tenants < Fog::Collection model Fog::Rackspace::Identity::Tenant def all load(retrieve_tenants) end def get(id) data = retrieve_tenants.find{ |tenant| tenant['id'] == id } data && new(data) end private def retrieve_tenants data = service.list_tenants.body['tenants'] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/identity/credentials.rb0000644000004100000410000000137713411315054025473 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/identity/credential' module Fog module Rackspace class Identity class Credentials < Fog::Collection model Fog::Rackspace::Identity::Credential attr_accessor :user def all requires :user load(retrieve_credentials) end def get(id) requires :user data = retrieve_credentials.find { |credential| credential['apiKey'] == id } data && new(data) end private def retrieve_credentials raw_credentials = service.list_credentials(user.identity).body['credentials'] raw_credentials.map { |c| c['RAX-KSKEY:apiKeyCredentials'] } end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/identity/users.rb0000644000004100000410000000145013411315054024327 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/identity/user' module Fog module Rackspace class Identity class Users < Fog::Collection model Fog::Rackspace::Identity::User def all data = service.list_users.body['users'] load(data) end def get(user_id) data = service.get_user_by_id(user_id).body['user'] new(data) rescue Excon::Errors::NotFound nil rescue Excon::Errors::Unauthorized nil end def get_by_name(user_name) data = service.get_user_by_name(user_name).body['user'] new(data) rescue Excon::Errors::NotFound nil rescue Excon::Errors::Unauthorized nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/identity/user.rb0000644000004100000410000000236013411315054024145 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Identity class User < Fog::Model identity :id attribute :username attribute :password, :alias => 'OS-KSADM:password' attribute :email attribute :enabled attribute :created attribute :updated def save requires :username, :email, :enabled unless persisted? data = service.create_user(username, email, enabled, :password => password) else data = service.update_user(identity, username, email, enabled, :password => password) end merge_attributes(data.body['user']) true end def destroy requires :identity service.delete_user(identity) true end def roles @roles ||= begin Fog::Rackspace::Identity::Roles.new({ :service => service, :user => self }) end end def credentials @credentials ||= begin Fog::Rackspace::Identity::Credentials.new({ :service => service, :user => self }) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/identity/tenant.rb0000644000004100000410000000035713411315054024464 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Identity class Tenant < Fog::Model identity :id attribute :name attribute :description attribute :enabled end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/identity/roles.rb0000644000004100000410000000116113411315054024311 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/identity/role' module Fog module Rackspace class Identity class Roles < Fog::Collection model Fog::Rackspace::Identity::Role attr_accessor :user def all requires :user load(retrieve_roles) end def get(id) requires :user data = retrieve_roles.find{ |role| role['id'] == id } data && new(data) end private def retrieve_roles data = service.list_user_roles(user.identity).body['roles'] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/identity/service_catalog.rb0000644000004100000410000000526613411315054026331 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Identity class ServiceCatalog < Fog::Model attr_reader :catalog def initialize(attributes) @service = attributes.delete(:service) @catalog = attributes.delete(:catalog) || {} end def services catalog.map {|s| s["name"]} end def get_endpoints(service_name, service_net=false) h = catalog.find {|service| service["name"] == service_name.to_s} return {} unless h key = network_type_key(service_net) h["endpoints"].select {|e| e[key]} end def display_service_regions(service_name, service_net=false) endpoints = get_endpoints(service_name, service_net) regions = endpoints.map do |e| e["region"] ? ":#{e["region"].downcase}" : ":global" end regions.join(", ") end def get_endpoint(service_name, region=nil, service_net=false) service_region = region_key(region) network_type = network_type_key(service_net) endpoints = get_endpoints(service_name, service_net) raise "Unable to locate endpoint for service #{service_name}" if endpoints.empty? if endpoints.size > 1 && region.nil? raise "There are multiple endpoints available for #{service_name}. Please specify one of the following regions: #{display_service_regions(service_name)}." end # select multiple endpoints endpoint = endpoints.find {|e| matching_region?(e, service_region) } return endpoint[network_type] if endpoint && endpoint[network_type] # endpoint doesnt have region if endpoints.size == 1 && matching_region?(endpoints[0], "GLOBAL") return endpoints[0][network_type] end raise "Unknown region :#{region} for service #{service_name}. Please use one of the following regions: #{display_service_regions(service_name)}" end def reload @service.authenticate @catalog = @service.service_catalog.catalog self end def self.from_response(service, hash) ServiceCatalog.new :service => service, :catalog => hash["access"]["serviceCatalog"] end private def network_type_key(service_net) service_net ? "internalURL" : "publicURL" end def matching_region?(h, region) region_key(h["region"]) == region end def region_key(region) return region.to_s.upcase if region.is_a? Symbol (region.nil? || region.empty?) ? "GLOBAL" : region.to_s.upcase end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/identity/role.rb0000644000004100000410000000032213411315054024124 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Identity class Role < Fog::Model identity :id attribute :name attribute :description end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/identity/credential.rb0000644000004100000410000000030113411315054025272 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Identity class Credential < Fog::Model identity :apiKey attribute :username end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/dns/0000755000004100000410000000000013411315054021574 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/dns/zone.rb0000644000004100000410000000313413411315054023075 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/dns/records' module Fog module DNS class Rackspace class Zone < Fog::Model include Fog::DNS::Rackspace::Callback identity :id attribute :email, :aliases => 'emailAddress' attribute :domain, :aliases => 'name' attribute :created attribute :updated attribute :account_id, :aliases => 'accountId' attribute :ttl attribute :nameservers attribute :comment def destroy response = service.remove_domain(identity) wait_for_job response.body['jobId'], Fog.timeout true end def records @records ||= begin Fog::DNS::Rackspace::Records.new( :zone => self, :service => service ) end end def save if persisted? update else create end true end private def create requires :domain, :email data = { :name => domain, :email => email } response = service.create_domains([data]) response = wait_for_job response.body['jobId'] merge_attributes(response.body['response']['domains'].select {|domain| domain['name'] == self.domain}.first) end def update requires :ttl, :email response = service.modify_domain(identity, { :ttl => ttl, :comment => comment, :email => email}) wait_for_job response.body['jobId'] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/dns/records.rb0000644000004100000410000000262113411315054023563 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/dns/record' module Fog module DNS class Rackspace class Records < Fog::Collection attribute :zone attribute :total_entries, :aliases => 'totalEntries' model Fog::DNS::Rackspace::Record def all requires :zone data = service.list_records(zone.identity) load(data.body['records']) end alias_method :each_record_this_page, :each def each requires :zone return self unless block_given? entries = 0 begin body = service.list_records(zone.id, :offset => entries).body entries += body['records'].size self.merge_attributes(body) subset = dup.load(body['records']) subset.each_record_this_page {|record| yield record } end while entries < total_entries self end def get(record_id) requires :zone data = service.list_record_details(zone.identity, record_id).body new(data) #nil or empty string will trigger an argument error rescue ArgumentError nil rescue Fog::DNS::Rackspace::NotFound nil end def new(attributes = {}) requires :zone super({ :zone => zone }.merge!(attributes)) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/dns/callback.rb0000644000004100000410000000135713411315054023663 0ustar www-datawww-datamodule Fog module DNS class Rackspace module Callback protected def wait_for_job(job_id, timeout=Fog.timeout, interval=1) retries = 5 response = nil Fog.wait_for(timeout, interval) do response = service.callback job_id if response.body['status'] == 'COMPLETED' true elsif response.body['status'] == 'ERROR' raise Fog::DNS::Rackspace::CallbackError.new(response) elsif retries == 0 raise Fog::Errors::Error.new("Wait on job #{job_id} took too long") else retries -= 1 false end end response end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/dns/zones.rb0000644000004100000410000000445113411315054023263 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/dns/zone' module Fog module DNS class Rackspace class Zones < Fog::Collection attribute :total_entries, :aliases => "totalEntries" model Fog::DNS::Rackspace::Zone # List all domains. Return by default a maximum of 100 items # @param [Hash] options Options to pass to the underlying API call # @option options [String] :name search for domains containing the given substring # @option options [Integer] :limit number of records to return # @option options [Integer] :offset starting offset of records to return def all(options={}) clear body = service.list_domains(options).body merge_attributes(body) load(body['domains']) end alias_method :each_zone_this_page, :each def each return self unless block_given? params = { :limit => 100} # prime loop (100 Records is default page size for Rackspace Cloud) while params body = service.list_domains(params).body subset = dup.load(body["domains"]) self.merge_attributes(body) params = next_params(body) subset.each_zone_this_page {|zone| yield zone} end self end def get(zone_id) if zone_id.nil? or zone_id.to_s.empty? return nil end data = service.list_domain_details(zone_id).body new(data) rescue Fog::DNS::Rackspace::NotFound # if we can't find it by id, go back and find it via domain find{|z| z.domain == zone_id} #Accessing a valid (but other customer's) id returns a 503 error rescue Fog::Rackspace::Errors::ServiceUnavailable nil end private def next_params(body) # return if we don't have any links return nil unless body && body['links'] #return if links don't contain a href for the next page next_link = body['links'].find {|h| h['rel'] == 'next'} return nil unless next_link && next_link['href'] url = next_link['href'] uri = URI.parse url return nil unless uri.query CGI.parse uri.query end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/dns/record.rb0000644000004100000410000000464613411315054023411 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/dns/callback' require 'ipaddr' module Fog module DNS class Rackspace class Record < Fog::Model include Fog::DNS::Rackspace::Callback extend Fog::Deprecation deprecate :ip, :value deprecate :ip=, :value= identity :id attribute :name attribute :value, :aliases => 'data' attribute :ttl attribute :type attribute :priority attribute :created attribute :updated def destroy requires :zone, :identity wait_for_job service.remove_record(@zone.identity, identity).body['jobId'] true end def zone @zone end def save if persisted? update else create end end private def create requires :name, :type, :value, :zone options = { :name => name, :type => type, :data => value } if ttl options[:ttl] = ttl end if priority options[:priority] = priority end response = wait_for_job service.add_records(@zone.identity, [options]).body['jobId'] matching_record = response.body['response']['records'].find do |record| if ['A', 'AAAA'].include?(self.type.upcase) # If this is an A or AAAA record, match by normalized IP address value. (record['name'] == self.name) && (record['type'] == self.type) && (IPAddr.new(record['data']) == IPAddr.new(self.value)) else # Other record types are matched by the raw value. (record['name'] == self.name) && (record['type'] == self.type) && (record['data'] == self.value) end end merge_attributes(matching_record) true end def update requires :identity, :zone options = {} options[:name] = name if name options[:type] = type if type options[:data] = value if value options[:priority] = priority if priority options[:ttl] = ttl if ttl wait_for_job service.modify_record(@zone.identity, identity, options).body['jobId'] true end def zone=(new_zone) @zone = new_zone end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/databases/0000755000004100000410000000000013411315054022737 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/databases/users.rb0000644000004100000410000000117313411315054024427 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/databases/user' module Fog module Rackspace class Databases class Users < Fog::Collection model Fog::Rackspace::Databases::User attr_accessor :instance def all load(retrieve_users) end def get(user_name) data = retrieve_users.find { |database| database['name'] == user_name } data && new(data) end private def retrieve_users requires :instance data = service.list_users(instance.identity).body['users'] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/databases/user.rb0000644000004100000410000000124013411315054024237 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Databases class User < Fog::Model identity :name attribute :password attribute :databases attribute :host def save requires :identity, :instance, :password service.create_user(instance.identity, identity, password, :databases => databases, :host => host) true end def destroy requires :identity, :instance service.delete_user(instance.identity, identity) true end private def instance collection.instance end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/databases/instance.rb0000644000004100000410000000473113411315054025075 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Databases class Instance < Fog::Model # States ACTIVE = 'ACTIVE' BUILD = 'BUILD' BLOCKED = 'BLOCKED' REBOOT = 'REBOOT' RESIZE = 'RESIZE' SHUTDOWN = 'SHUTDOWN' identity :id attribute :name attribute :created attribute :updated attribute :state, :aliases => 'status' attribute :hostname attribute :links attribute :flavor_id, :aliases => 'flavor', :squash => 'id' attribute :volume_size, :aliases => 'volume', :squash => 'size' attr_accessor :root_user, :root_password def save requires :name, :flavor_id, :volume_size data = service.create_instance(name, flavor_id, volume_size) merge_attributes(data.body['instance']) true end def destroy requires :identity service.delete_instance(identity) true end def flavor requires :flavor_id @flavor ||= service.flavors.get(flavor_id) end def databases @databases ||= begin Fog::Rackspace::Databases::Databases.new({ :service => service, :instance => self }) end end def users @users ||= begin Fog::Rackspace::Databases::Users.new({ :service => service, :instance => self }) end end def ready? state == ACTIVE end def root_user_enabled? requires :identity service.check_root_user(identity).body['rootEnabled'] end def enable_root_user requires :identity data = service.enable_root_user(identity).body['user'] @root_user = data['name'] @root_password = data['password'] true end def restart requires :identity service.restart_instance(identity) self.state = REBOOT true end def resize(flavor_id) requires :identity service.resize_instance(identity, flavor_id) self.state = RESIZE true end def resize_volume(volume_size) requires :identity service.resize_instance_volume(identity, volume_size) self.state = RESIZE true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/databases/flavor.rb0000644000004100000410000000034613411315054024560 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Databases class Flavor < Fog::Model identity :id attribute :name attribute :ram attribute :links end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/databases/database.rb0000644000004100000410000000171113411315054025030 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Databases class Database < Fog::Model identity :name attribute :character_set attribute :collate def save requires :identity, :instance service.create_database(instance.identity, identity, :character_set => character_set, :collate => collate) true end def destroy requires :identity, :instance service.delete_database(instance.identity, identity) true end def grant_access_for(user) requires :identity, :instance service.grant_user_access(instance.identity, user, name) end def revoke_access_for(user) requires :identity, :instance service.revoke_user_access(instance.identity, user, name) end private def instance collection.instance end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/databases/flavors.rb0000644000004100000410000000102613411315054024737 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/databases/flavor' module Fog module Rackspace class Databases class Flavors < Fog::Collection model Fog::Rackspace::Databases::Flavor def all data = service.list_flavors.body['flavors'] load(data) end def get(flavor_id) data = service.get_flavor(flavor_id).body['flavor'] new(data) rescue Fog::Rackspace::Databases::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/databases/instances.rb0000644000004100000410000000105013411315054025247 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/databases/instance' module Fog module Rackspace class Databases class Instances < Fog::Collection model Fog::Rackspace::Databases::Instance def all data = service.list_instances.body['instances'] load(data) end def get(instance_id) data = service.get_instance(instance_id).body['instance'] new(data) rescue Fog::Rackspace::Databases::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/databases/databases.rb0000644000004100000410000000123513411315054025214 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/databases/database' module Fog module Rackspace class Databases class Databases < Fog::Collection model Fog::Rackspace::Databases::Database attr_accessor :instance def all load(retrieve_databases) end def get(database_name) data = retrieve_databases.find { |database| database['name'] == database_name } data && new(data) end private def retrieve_databases requires :instance data = service.list_databases(instance.id).body['databases'] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/0000755000004100000410000000000013411315054023073 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/virtual_interfaces.rb0000644000004100000410000000341613411315054027315 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute_v2/virtual_interface' require 'fog/rackspace/models/compute_v2/server' module Fog module Compute class RackspaceV2 class VirtualInterfaces < Fog::Collection model Fog::Compute::RackspaceV2::VirtualInterface attr_reader :server def server=(obj) if obj.is_a?(Server) @server = obj else @server = Fog::Compute::RackspaceV2::Server.new :id => obj, :service => service end end # Returns list of virtual interfaces for a server # @return [Fog::Compute::RackspaceV2::Servers] Retrieves a list virtual interfaces for server. # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note Fog's current implementation only returns 1000 servers # @note The filter parameter on the method is just to maintain compatability with other providers that support filtering. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Servers-d1e2078.html # @see Fog::Compute::RackspaceV2::Server#virtual_interfaces def all raise "Please access this collection via Server#virtual_interfaces" unless self.server data = service.list_virtual_interfaces(server.id).body['virtual_interfaces'] objects = load(data) objects.each {|obj| obj.attributes[:server] = self.server} objects end def new(attributes = {}) super({ :server => server }.merge(attributes)) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/key_pairs.rb0000644000004100000410000000257413411315054025416 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute_v2/key_pair' module Fog module Compute class RackspaceV2 class KeyPairs < Fog::Collection model Fog::Compute::RackspaceV2::KeyPair # Fetch the list of known keypairs # @return [Fog::Compute::RackspaceV2::Keypairs] the retreived keypairs # @raise [Fog::Compute::RackspaceV2::NotFound] # @raise [Fog::Compute::RackspaceV2::BadRequest] # @raise [Fog::Compute::RackspaceV2::InternalServerError] # @raise [Fog::Compute::RackspaceV2::ServiceError] def all data = [] service.list_keypairs.body['keypairs'].each do |kp| data << kp['keypair'] if kp['keypair'] end load(data) end # Fetch keypair details # @param [String] key_name name of the key to request # @return [Fog::Compute::RackspaceV2::Keypair] the requested keypair or 'nil' when not found # @raise [Fog::Compute::RackspaceV2::BadRequest] # @raise [Fog::Compute::RackspaceV2::InternalServerError] # @raise [Fog::Compute::RackspaceV2::ServiceError] def get(key_name) begin new(service.get_keypair(key_name).body['keypair']) rescue Fog::Compute::RackspaceV2::NotFound nil end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/virtual_interface.rb0000644000004100000410000000660213411315054027132 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute_v2/virtual_interface' module Fog module Compute class RackspaceV2 class VirtualInterface < Fog::Model # @!attribute [r] id # @return [String] The virtual interface id identity :id # @!attribute [r] mac_address # @return [String] The Media Access Control (MAC) address for the virtual interface. # A MAC address is a unique identifier assigned to network interfaces for communications on the physical network segment. attribute :mac_address # @!attribute [r] ip_addresses # @return [Array] returns an array of hashes containing information about allocated ip addresses and their associated networks # @example # [ # { # "address": "2001:4800:7810:0512:d87b:9cbc:ff04:850c", # "network_id": "ba122b32-dbcc-4c21-836e-b701996baeb3", # "network_label": "public" # }, # { # "address": "64.49.226.149", # "network_id": "ba122b32-dbcc-4c21-836e-b701996baeb3", # "network_label": "public" # } # ] attribute :ip_addresses # Saves the virtual interface. # This method can only create a virtual interface. Attempting to update interface will result an exception # @return [Boolean] true if virtual interface has been saved def save(attributes = {}) if persisted? raise Fog::Errors::Error.new("This virtual interface has already been created and it cannot be updated") else create end true end # Creates Virtual interface for server # * requires attributes: :network # @return [Boolean] returns true if virtual network interface is being created # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @example To create a virtual interface; # my_server.virtual_interfaces.create :network => my_network # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/api_create_virtual_interface.html def create data = service.create_virtual_interface(server_id, network_id) merge_attributes(data.body['virtual_interfaces'].first) end # Destroy the virtual interface # @return [Boolean] returns true if virtual interface has been destroyed # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/delete_virt_interface_api.html def destroy service.delete_virtual_interface(server_id, id) true end private def server_id attributes[:server].is_a?(Server) ? attributes[:server].id : attributes[:server] end def network_id attributes[:network].is_a?(Network) ? attributes[:network].id : attributes[:network] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/image.rb0000644000004100000410000001060213411315054024501 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class RackspaceV2 class Image < Fog::Model UNKNOWN = 'UNKNOWN' ACTIVE = 'ACTIVE' SAVING = 'SAVING' ERROR = 'ERROR' DELETED = 'DELETED' # @!attribute [r] id # @return [String] The server id identity :id # @!attribute [r] name # @return [String] The image name. attribute :name # @!attribute [r] created # @return [String] The time stamp for the creation date. attribute :created # @!attribute [r] updated # @return [String] The time stamp for the last update. attribute :updated # @!attribute [r] state # @return [String] image status. attribute :state, :aliases => 'status' # @!attribute [r] user_id # @return [String] The user Id. attribute :user_id # @!attribute [r] tenant_id # @return [String] The tenant Id. attribute :tenant_id # @!attribute [r] progress # @return [Fixnum] The build completion progress, as a percentage. Value is from 0 to 100. attribute :progress attribute :minDisk attribute :minRam # @!attribute [rw] disk_config # @return [String] The disk configuration value. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#diskconfig_attribute # # The disk configuration value. # * AUTO - The server is built with a single partition the size of the target flavor disk. The file system is automatically adjusted to fit the entire partition. # This keeps things simple and automated. AUTO is valid only for images and servers with a single partition that use the EXT3 file system. # This is the default setting for applicable Rackspace base images. # # * MANUAL - The server is built using whatever partition scheme and file system is in the source image. If the target flavor disk is larger, # the remaining disk space is left unpartitioned. This enables images to have non-EXT3 file systems, multiple partitions, # and so on, and enables you to manage the disk configuration. attribute :disk_config, :aliases => 'OS-DCF:diskConfig' # @!attribute [r] links # @return [Array] image links. attribute :links def initialize(attributes={}) @service = attributes[:service] super end # Image metadata # @return [Fog::Compute::RackspaceV2::Metadata] Collection of Fog::Compute::RackspaceV2::Metadatum objects containing metadata key value pairs. def metadata @metadata ||= begin Fog::Compute::RackspaceV2::Metadata.new({ :service => service, :parent => self }) end end # Set server metadata # @param [Hash] hash contains key value pairs def metadata=(hash={}) metadata.from_hash(hash) end # Is image is in ready state # @param [String] ready_state By default state is ACTIVE # @param [Array,String] error_states By default state is ERROR # @return [Boolean] returns true if server is in a ready state # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @raise [Fog::Compute::RackspaceV2::InvalidImageStateException] if server state is an error state def ready?(ready_state = ACTIVE, error_states=[ERROR]) if error_states error_states = Array(error_states) raise InvalidImageStateException.new(ready_state, state) if error_states.include?(state) end state == ready_state end # Destroy image # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def destroy requires :identity service.delete_image(identity) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/metadatum.rb0000644000004100000410000000250013411315054025376 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/compute_v2/meta_parent' module Fog module Compute class RackspaceV2 class Metadatum < Fog::Model include Fog::Compute::RackspaceV2::MetaParent identity :key attribute :value # Remove metadatum from server # @return [Boolean] return true if metadatum is deleting # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def destroy requires :identity service.delete_metadata_item(collection_name, parent.id, key) true end # Save metadatum on server # @return [Boolean] return true if metadatum is saving # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def save requires :identity, :value service.set_metadata_item(collection_name, parent.id, key, value) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/key_pair.rb0000644000004100000410000000326113411315054025225 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class RackspaceV2 class KeyPair < Fog::Model # @!attribute [rw] name # @return [String] the keypair name identity :name # @!attribute [r] public_key # @return [String] the public key attribute :public_key # @!attribute [r] private_key # @return [String] the private key attribute :private_key # @!attribute [r] user_id # @return [String] the user_id associated to attribute :user_id # @!attribute [r] fingerprint # @return [String] unique fingerprint attribute :fingerprint # Creates a keypair # @return [Boolean] true if the keypair is successfully created # @raise [Fog::Compute::RackspaceV2::NotFound] # @raise [Fog::Compute::RackspaceV2::BadRequest] # @raise [Fog::Compute::RackspaceV2::InternalServerError] # @raise [Fog::Compute::RackspaceV2::ServiceError] def save requires :name data = service.create_keypair(name, attributes) merge_attributes(data.body['keypair']) data.body['keypair']['name'] == name end # Destroys a keypair # @return [Boolean] true if the keypair is successfully deleted # @raise [Fog::Compute::RackspaceV2::NotFound] # @raise [Fog::Compute::RackspaceV2::BadRequest] # @raise [Fog::Compute::RackspaceV2::InternalServerError] # @raise [Fog::Compute::RackspaceV2::ServiceError] def destroy requires :identity service.delete_keypair(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/network.rb0000644000004100000410000000074413411315054025116 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 class Network < Fog::Model identity :id attribute :label attribute :cidr def save requires :label, :cidr data = service.create_network(label, cidr) merge_attributes(data.body['network']) true end def destroy requires :identity service.delete_network(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/metadata.rb0000644000004100000410000001017013411315054025177 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute_v2/meta_parent' require 'fog/rackspace/models/compute_v2/metadatum' require 'fog/rackspace/models/compute_v2/image' require 'fog/rackspace/models/compute_v2/server' module Fog module Compute class RackspaceV2 class Metadata < Fog::Collection model Fog::Compute::RackspaceV2::Metadatum include Fog::Compute::RackspaceV2::MetaParent # Retrieves all of the metadata from server # @return [Fog::Compute::RackspaceV2::Metadatum] list of metadatum # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def all requires :parent return unless parent.identity data = service.list_metadata(collection_name, parent.id).body['metadata'] from_hash(data) end # Retrieves specific metadata from server # @param [String] key for metadatum # @return [Fog::Compute::RackspaceV2::Metadatum] metadatum # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def get(key) requires :parent data = service.get_metadata_item(collection_name, parent.id, key).body["meta"] datum = data.first new(:key => datum[0], :value => datum[1]) rescue Fog::Compute::RackspaceV2::NotFound nil end # Retrieve specific value for key from Metadata. # * If key is of type String, this method will return the value of the metadatum # * If key is of type Fixnum, this method will return a Fog::Compute::RackspaceV2::Metadatum object (legacy) # @param [#key] key # @return [#value] def [](key) return super(key) if key.is_a?(Integer) return nil unless key datum = self.find {|datum| datum.key == key || datum.key == key.to_sym } datum ? datum.value : nil end # Set value for key. # * If key is of type String, this method will set/add the value to Metadata # * If key is of type Fixnum, this method will set a Fog::Compute::RackspaceV2::Metadatum object (legacy) # @param [#key] key # @return [String] def []=(key, value) return super(key,value) if key.is_a?(Integer) return nil unless key datum = self.find {|datum| datum.key == key || datum.key == key.to_sym } if datum datum.value = value else self << Fog::Compute::RackspaceV2::Metadatum.new(:key => key, :value => value, :service => service, :parent => parent) end value end # Saves the current metadata on server # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def save requires :parent service.set_metadata(collection_name, parent.id, to_hash) end # Creates new metadata def new(attributes = {}) super({ :parent => parent }.merge!(attributes)) end # Resets metadata using data from hash # @param hash hash containing key value pairs used to populate metadata. # @note This will remove existing data def from_hash(hash) return unless hash metas = [] hash.each_pair {|k,v| metas << {:key => k, :value => v} } load(metas) end # Converts metadata object to hash # @return [Hash] hash of metadata key value pairs def to_hash h = {} self.each { |datum| h[datum.key] = datum.value } h end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/attachment.rb0000644000004100000410000000425013411315054025551 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class RackspaceV2 class Attachment < Fog::Model # @!attribute [r] server_id # @return [String] The server id attribute :server_id, :aliases => 'serverId' # @!attribute [r] volume_id # @return [String] The volume id attribute :volume_id, :aliases => 'volumeId' # @!attribute [r] device # @return [String]device name of the device /dev/xvd[a-p] attribute :device def initialize(new_attributes = {}) super(new_attributes) server_id = server.id if server #server id should come from collection self end # Attaches volume to volume to server. # Requires :server_id, :volume_id, and device to be populated # @return [Boolean] true if volume is attaching # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Attach_Volume_to_Server.html def save requires :server_id, :volume_id, :device data = service.attach_volume(server_id, volume_id, device) merge_attributes(data.body['volumeAttachment']) true end # Detaches volume from server # @return [Boolean] true if volume is detaching # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Delete_Volume_Attachment.html def destroy requires :server_id, :volume_id service.delete_attachment(server_id, volume_id) true end alias_method :detach, :destroy private def server collection.server end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/flavor.rb0000644000004100000410000000132013411315054024705 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class RackspaceV2 class Flavor < Fog::Model # @!attribute [r] id # @return [String] The flavor id identity :id # @!attribute [r] name # @return [String] flavor name attribute :name # @!attribute [r] rame # @return [Fixnum] ram in MB attribute :ram # @!attribute [r] disk # @return [String] disk space in GB attribute :disk # @!attribute [r] vcpus # @return [Fixnum] number of virtual CPUs attribute :vcpus # @!attribute [r] links # @return [Array] flavor links. attribute :links end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/meta_parent.rb0000644000004100000410000000214613411315054025722 0ustar www-datawww-datamodule Fog module Compute class RackspaceV2 module MetaParent # Parent of metadata # @return [#parent] parent of metadata def parent @parent end # Sets parent of metadata # @param [#parent] new_parent of metadata def parent=(new_parent) @parent = new_parent end # Collection type for parent # @return [String] collection type # @raise [RuntimeError] raises excpetion if collection type for parent is unknown def collection_name if parent.class == Fog::Compute::RackspaceV2::Image return "images" elsif parent.class == Fog::Compute::RackspaceV2::Server return "servers" else raise "Metadata is not supported for this model type." end end # Converts metadata to hash # @return [Hash] hash containing key value pairs for metadata def metas_to_hash(metas) hash = {} metas.each { |meta| hash[meta.key] = meta.value } hash end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/flavors.rb0000644000004100000410000000276713411315054025110 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute_v2/flavor' module Fog module Compute class RackspaceV2 class Flavors < Fog::Collection model Fog::Compute::RackspaceV2::Flavor # Retrieves information for all available flavors # @return [Fog::Compute::RackspaceV2::Flavors] list of flavors # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note Fog's currentl implementation only returns 1000 flavors. def all data = service.list_flavors_detail.body['flavors'] load(data) end # Retrieve image # @param [String] flavor_id id of flavor # @return [Fog::Compute::RackspaceV2::Flavor] flavor # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Get_Flavor_Details-d1e4317.html def get(flavor_id) data = service.get_flavor(flavor_id).body['flavor'] new(data) rescue Fog::Compute::RackspaceV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/servers.rb0000644000004100000410000000601613411315054025114 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute_v2/server' module Fog module Compute class RackspaceV2 class Servers < Fog::Collection model Fog::Compute::RackspaceV2::Server # Returns list of servers # @return [Fog::Compute::RackspaceV2::Servers] Retrieves a list servers. # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note Fog's current implementation only returns 1000 servers # @note The filter parameter on the method is just to maintain compatability with other providers that support filtering. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Servers-d1e2078.html def all(filters = {}) data = service.list_servers.body['servers'] load(data) end # Creates a new server and populates ssh keys # @return [Fog::Compute::RackspaceV2::Server] # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note This method is incompatible with Cloud Servers utlizing RackConnect ***if and only if*** # provided the attribute "passwd_lock" left at *false*. # @example # service.servers.bootstrap :name => 'bootstrap-server', # :flavor_id => service.flavors.first.id, # :image_id => service.images.find {|img| img.name =~ /Ubuntu/}.id, # :public_key_path => '~/.ssh/fog_rsa.pub', # :private_key_path => '~/.ssh/fog_rsa' # # @raise [Fog::Compute::RackspaceV2::InvalidServerStateException] if server state is an error state def bootstrap(new_attributes = {}) server = create(new_attributes) server.wait_for { ready? && !public_ip_address.empty? } server.setup(:password => server.password) server end # Retrieves server # @param [String] server_id for server to be returned # @return [Fog::Compute::RackspaceV2:Server] # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Get_Server_Details-d1e2623.html def get(server_id) data = service.get_server(server_id).body['server'] new(data) rescue Fog::Compute::RackspaceV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/attachments.rb0000644000004100000410000000264613411315054025743 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute_v2/attachment' module Fog module Compute class RackspaceV2 class Attachments < Fog::Collection model Fog::Compute::RackspaceV2::Attachment attr_accessor :server # Retrieves attachments belonging to server # @return [Fog::Compute::RackspaceV2::Attachments] list of attachments # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see Server#attachments def all data = service.list_attachments(server.id).body['volumeAttachments'] load(data) end # Retrieves attachment belonging to server # @param [String] volume_id # @return [Fog::Compute::RackspaceV2::Attachment] attachment for volume id # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def get(volume_id) data = service.get_attachment(server.id, volume_id).body['volumeAttachment'] data && new(data) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/server.rb0000644000004100000410000007674313411315054024747 0ustar www-datawww-data# -*- coding: utf-8 -*- require 'fog/compute/models/server' require 'fog/rackspace/models/compute_v2/metadata' module Fog module Compute class RackspaceV2 class Server < Fog::Compute::Server # States ACTIVE = 'ACTIVE' BUILD = 'BUILD' DELETED = 'DELETED' ERROR = 'ERROR' HARD_REBOOT = 'HARD_REBOOT' MIGRATING = 'MIGRATING' PASSWORD = 'PASSWORD' REBOOT = 'REBOOT' REBUILD = 'REBUILD' RESCUE = 'RESCUE' RESIZE = 'RESIZE' REVERT_RESIZE = 'REVERT_RESIZE' SUSPENDED = 'SUSPENDED' UNKNOWN = 'UNKNOWN' VERIFY_RESIZE = 'VERIFY_RESIZE' # @!attribute [r] id # @return [String] The server id identity :id # @!attribute [rw] name # @return [String] The server name. attribute :name # @!attribute [r] created # @return [String] The time stamp for the creation date. attribute :created # @!attribute [r] updated # @return [String] The time stamp for the last update. attribute :updated # @!attribute [r] host Id # The host Id. # The compute provisioning algorithm has an anti-affinity property that attempts to spread customer VMs across hosts. # Under certain situations, VMs from the same customer might be placed on the same host. # hostId represents the host your server runs on and can be used to determine this scenario if it is relevant to your application. # HostId is unique per account and is not globally unique. # @return [String] host id. attribute :host_id, :aliases => 'hostId' # @!attribute [r] state # @return [String] server status. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Servers-d1e2078.html#server_status attribute :state, :aliases => 'status' # @!attribute [r] state_ext # @return [String] server (extended) status. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Servers-d1e2078.html#server_status attribute :state_ext, :aliases => 'OS-EXT-STS:task_state' # @!attribute [r] progress # @return [Fixnum] The build completion progress, as a percentage. Value is from 0 to 100. attribute :progress # @!attribute [r] user_id # @return [String] The user Id. attribute :user_id # @!attribute [r] tenant_id # @return [String] The tenant Id. attribute :tenant_id # @!attribute [r] links # @return [Array] Server links. attribute :links # @!attribute [rw] personality # @note This attribute is only used for server creation. This field will be nil on subsequent retrievals. # @return [Hash] Hash containing data to inject into the file system of the cloud server instance during server creation. # @example To inject fog.txt into file system # :personality => [{ :path => '/root/fog.txt', # :contents => Base64.encode64('Fog was here!') # }] # @see #create # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Personality-d1e2543.html attribute :personality # @!attribute [rw] ipv4_address # @return [String] The public IP version 4 access address. # @note This field will populate once the server is ready to use. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Primary_Addresses-d1e2558.html attribute :ipv4_address, :aliases => 'accessIPv4' # @!attribute [rw] ipv6_address # @return [String] The public IP version 6 access address. # @note This field will populate once the server is ready to use. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Primary_Addresses-d1e2558.html attribute :ipv6_address, :aliases => 'accessIPv6' # @!attribute [rw] disk_config # @return [String] The disk configuration value. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#diskconfig_attribute # # The disk configuration value. # * AUTO - The server is built with a single partition the size of the target flavor disk. The file system is automatically adjusted to fit the entire partition. # This keeps things simple and automated. AUTO is valid only for images and servers with a single partition that use the EXT3 file system. # This is the default setting for applicable Rackspace base images. # # * MANUAL - The server is built using whatever partition scheme and file system is in the source image. If the target flavor disk is larger, # the remaining disk space is left unpartitioned. This enables images to have non-EXT3 file systems, multiple partitions, # and so on, and enables you to manage the disk configuration. attribute :disk_config, :aliases => 'OS-DCF:diskConfig' # @!attribute [rw] config_drive_ext # @return [Boolean] whether a read-only configuration drive is attached # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/config_drive_ext.html attribute :config_drive # @!attribute [rw] user_data # @return [Boolean] User-data # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/config_drive_ext.html attribute :user_data # @!attribute [r] bandwidth # @return [Array] The amount of bandwidth used for the specified audit period. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#bandwidth_extension attribute :bandwidth, :aliases => 'rax-bandwidth:bandwidth' # @!attribute [r] address # @return [Hash] IP addresses allocated for server by network # @example # { # "public" => [ # {"version"=>4, "addr"=>"166.78.105.63"}, # {"version"=>6, "addr"=>"2001:4801:7817:0072:0fe1:75e8:ff10:61a9"} # ], # "private"=> [{"version"=>4, "addr"=>"10.177.18.209"}] # } attribute :addresses # @!attribute [r] flavor_id # @return [String] The flavor Id. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Flavors-d1e4188.html attribute :flavor_id, :aliases => 'flavor', :squash => 'id' # @!attribute [r] image_id # @return [String] The image Id. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Images-d1e4435.html attribute :image_id, :aliases => 'image', :squash => 'id' # @!attribute [w] boot_volume_id # @return [String] The ID of a bootable volume from the BlockStorage service. # @see http://developer.openstack.org/api-ref-compute-v2-ext.html#ext-os-block-device-mapping-v2-boot attribute :boot_volume_id # @!attribute [w] boot_volume_size # @return [Integer] The Size of the boot volume to be created by the BlockStorage service. # @see http://developer.openstack.org/api-ref-compute-v2-ext.html#ext-os-block-device-mapping-v2-boot attribute :boot_volume_size # @!attribute [w] boot_image_id # @return [String] The ID of an image to create a bootable volume from. # @see http://developer.openstack.org/api-ref-compute-v2-ext.html#ext-os-block-device-mapping-v2-boot attribute :boot_image_id # @!attribute [rw] password # @return [String] Password for system adminstrator account. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Passwords-d1e2510.html # @note Can be set while creating a server, but use change_admin_password instead of save/update for changes. attribute :password # @!attribute [rw] key_name # @return [String] The name of the key_pair used for server. # @note The key_pair/key_name is used to specify the keypair used for server creation. It is not populated by cloud servers. attribute :key_name def initialize(attributes={}) @service = attributes[:service] super end alias_method :access_ipv4_address, :ipv4_address alias_method :access_ipv4_address=, :ipv4_address= alias_method :access_ipv6_address, :ipv6_address alias_method :access_ipv6_address=, :ipv6_address= # Server metadata # @return [Fog::Compute::RackspaceV2::Metadata] metadata key value pairs. def metadata @metadata ||= begin Fog::Compute::RackspaceV2::Metadata.new({ :service => service, :parent => self }) end end # Set server metadata # @param [Hash] hash contains key value pairs def metadata=(hash={}) metadata.from_hash(hash) end # Returns the key pair based on the key_name of the server # @return [KeyPair] # @note The key_pair/key_name is used to specify the keypair used for server creation. It is not populated by cloud servers. def key_pair requires :key_name service.key_pairs.get(key_name) end # Sets the key_pair used by the server. # @param new_keypair [KeyPair] key_pair object for server # @note The key_pair/key_name is used to specify the keypair used for server creation. It is not populated by cloud servers. def key_pair=(new_keypair) if new_keypair.is_a?(String) Fog::Logger.deprecation("#key_pair= should be used to set KeyPair objects. Please use #key_name method instead") self.key_name = new_keypair else self.key_name = new_keypair && new_keypair.name end end # Saves the server. # Creates server if it is new, otherwise it will update server attributes name, accessIPv4, and accessIPv6. # @return [Boolean] true if server has started saving def save(options = {}) if persisted? update else create(options) end true end # Creates server # * requires attributes: service:, :name, :image_id, and :flavor_id # * optional attributes :disk_config, :metadata, :personality, :config_drive, :boot_volume_id, :boot_image_id # * :image_id should be "" if :boot_volume_id or :boot_image_id are provided. # @return [Boolean] returns true if server is being created # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note You should use servers.create to create servers instead calling this method directly # @see Servers#create # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/CreateServers.html # # * State Transitions # * BUILD -> ACTIVE # * BUILD -> ERROR (on error) def create(options) requires :name, :image_id, :flavor_id modified_options = Marshal.load(Marshal.dump(options)) if attributes[:keypair] Fog::Logger.deprecation(":keypair has been depreciated. Please use :key_name instead.") modified_options[:key_name] = attributes[:keypair] end modified_options[:password] ||= attributes[:password] unless password.nil? modified_options[:networks] ||= attributes[:networks] modified_options[:disk_config] = disk_config unless disk_config.nil? modified_options[:metadata] = metadata.to_hash unless @metadata.nil? modified_options[:personality] = personality unless personality.nil? modified_options[:config_drive] = config_drive unless config_drive.nil? modified_options[:user_data] = user_data_encoded unless user_data_encoded.nil? modified_options[:key_name] ||= attributes[:key_name] modified_options[:boot_volume_id] ||= attributes[:boot_volume_id] modified_options[:boot_image_id] ||= attributes[:boot_image_id] modified_options[:boot_volume_size] ||= attributes[:boot_volume_size] if mn = modified_options[:networks] # If we've already processed it into the correct form don't process again. unless mn.first.is_a?(Hash) modified_options[:networks].map! { |id| { :uuid => id } } end end data = service.create_server(name, image_id, flavor_id, 1, 1, modified_options) merge_attributes(data.body['server']) true end # Updates server # This will update :name, :accessIPv4, and :accessIPv6 attributes. # @note If you edit the server name, the server host name does not change. Also, server names are not guaranteed to be unique. # @return true if update has started updating # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ServerUpdate.html # # * State Transition # * ACTIVE -> ACTIVE def update requires :identity options = { 'name' => name, 'accessIPv4' => ipv4_address, 'accessIPv6' => ipv6_address } data = service.update_server(identity, options) merge_attributes(data.body['server']) true end # Destroy the server # @return [Boolean] returns true if server has started deleting # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Delete_Server-d1e2883.html # # * Status Transition: # * ACTIVE -> DELETED # * ERROR -> DELETED def destroy requires :identity service.delete_server(identity) true end # Server flavor # @return [Fog::Compute::RackspaceV2::Flavor] server flavor # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def flavor requires :flavor_id @flavor ||= service.flavors.get(flavor_id) end # Server image # @return [Fog::Compute::RackspaceV2::Image] server image # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] def image requires :image_id @image ||= service.images.get(image_id) end # Creates Image from server. Once complete, a new image is available that you can use to rebuild or create servers. # @param name [String] name of image to create # @param options [Hash]: # @option options [Hash] metadata hash of containing metadata key value pairs. # @return [Fog::ComputeRackspaceV2::Image] image being created # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Create_Image-d1e4655.html # # * State Transition: # * SAVING -> ACTIVE # * SAVING -> ERROR (on error) def create_image(name, options = {}) requires :identity response = service.create_image(identity, name, options) begin image_id = response.headers["Location"].match(/\/([^\/]+$)/)[1] Fog::Compute::RackspaceV2::Image.new(:collection => service.images, :service => service, :id => image_id) rescue nil end end # Attached Cloud Block Volumes # @return [Fog::Compute::RackspaceV2::Attachments] attached Cloud Block Volumes # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Volume_Attachments.html def attachments @attachments ||= begin Fog::Compute::RackspaceV2::Attachments.new({ :service => service, :server => self }) end end # Attaches Cloud Block Volume # @param [Fog::Rackspace::BlockStorage::Volume, String] volume object or the volume id of volume to mount # @param [String] device name of the device /dev/xvd[a-p] (optional) # @return [Fog::Compute::RackspaceV2::Attachment] resulting attachment object # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Attach_Volume_to_Server.html def attach_volume(volume, device=nil) requires :identity volume_id = volume.is_a?(String) ? volume : volume.id attachments.create(:server_id => identity, :volume_id => volume_id, :device => device) end # Server's private IPv4 address # @return [String] private IPv4 address def private_ip_address addresses['private'].select{|a| a["version"] == 4}[0]["addr"] rescue '' end # Server's public IPv4 address # @return [String] public IPv4 address def public_ip_address ipv4_address end # Is server is in ready state # @param [String] ready_state By default state is ACTIVE # @param [Array,String] error_states By default state is ERROR # @return [Boolean] returns true if server is in a ready state # @raise [Fog::Compute::RackspaceV2::InvalidServerStateException] if server state is an error state def ready?(ready_state = ACTIVE, error_states=[ERROR]) if error_states error_states = Array(error_states) raise InvalidServerStateException.new(ready_state, state) if error_states.include?(state) end state == ready_state end # Reboot server # @param [String] type 'SOFT' will do a soft reboot. 'HARD' will do a hard reboot. # @return [Boolean] returns true if server is being rebooted # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Reboot_Server-d1e3371.html # # * State transition: # * ACTIVE -> REBOOT -> ACTIVE (soft reboot) # * ACTIVE -> HARD_REBOOT -> ACTIVE (hard reboot) def reboot(type = 'SOFT') requires :identity service.reboot_server(identity, type) self.state = type == 'SOFT' ? REBOOT : HARD_REBOOT true end # Rebuild removes all data on the server and replaces it with the specified image. The id and all IP addresses remain the same. # @param [String] image_id image to use for rebuild # @return [Boolean] returns true if rebuild is in process # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Rebuild_Server-d1e3538.html # # * Status Transition: # * ACTIVE -> REBUILD -> ACTIVE # * ACTIVE -> REBUILD -> ERROR (on error) def rebuild(image_id, options={}) requires :identity service.rebuild_server(identity, image_id, options) self.state = REBUILD true end # Resize existing server to a different flavor, in essence, scaling the server up or down. The original server is saved for a period of time to allow rollback if there is a problem. All resizes should be tested and explicitly confirmed, at which time the original server is removed. All resizes are automatically confirmed after 24 hours if they are not confirmed or reverted. # @param [String] flavor_id to resize # @return [Boolean] returns true if resize is in process # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note All resizes are automatically confirmed after 24 hours if you do not explicitly confirm or revert the resize. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Resize_Server-d1e3707.html # @see #confirm_resize # @see #revert_resize # # * Status Transition: # * ACTIVE -> QUEUE_RESIZE -> PREP_RESIZE -> VERIFY_RESIZE # * ACTIVE -> QUEUE_RESIZE -> ACTIVE (on error) def resize(flavor_id) requires :identity service.resize_server(identity, flavor_id) self.state = RESIZE true end # Confirms server resize operation # @return [Boolean] returns true if resize has been confirmed # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note All resizes are automatically confirmed after 24 hours if you do not explicitly confirm or revert the resize. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Confirm_Resized_Server-d1e3868.html # @see #resize # # * Status Transition: # * VERIFY_RESIZE -> ACTIVE # * VERIFY_RESIZE -> ERROR (on error)å def confirm_resize requires :identity service.confirm_resize_server(identity) true end # Reverts server resize operation # @return [Boolean] returns true if resize is being reverted # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note All resizes are automatically confirmed after 24 hours if you do not explicitly confirm or revert the resize. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Revert_Resized_Server-d1e4024.html # @see #resize # # * Status Transition: # * VERIFY_RESIZE -> ACTIVE # * VERIFY_RESIZE -> ERROR (on error) def revert_resize requires :identity service.revert_resize_server(identity) true end # This operation starts a stopped server, and changes its status to ACTIVE. # Prior to running this command, the server status must be SHUTTOFF # @param [String] server_id id of server to rescue # @return [Boolean] returns true if call to put server in ACTIVE mode reports success # @raise [Fog::Rackspace::Errors::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Errors::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Errors::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Errors::ServiceError] # @note Rescue mode is only guaranteed to be active for 90 minutes # @see https://developer.rackspace.com/docs/cloud-servers/v2/api-reference/svr-basic-operations/#start-specified-server def start requires :identity service.start_server(identity) true end # This operation stops a running server, and changes the server status to SHUTOFF # and changes the clean_shutdown parameter to TRUE. # Prior to running this command, the server status must be ACTIVE or ERROR. # @param [String] server_id id of server to rescue # @return [Boolean] returns true if call to put server in SHUTOFF mode reports success # @raise [Fog::Rackspace::Errors::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Errors::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Errors::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Errors::ServiceError] # @note Rescue mode is only guaranteed to be active for 90 minutes # @see https://developer.rackspace.com/docs/cloud-servers/v2/api-reference/svr-basic-operations/#stop-specified-server def stop requires :identity service.stop_server(identity) true end # Place existing server into rescue mode, allowing for offline editing of configuration. The original server's disk is attached to a new instance of the same base image for a period of time to facilitate working within rescue mode. The original server will be automatically restored after 90 minutes. # @return [Boolean] returns true if call to put server in rescue mode reports success # @raise [Fog::Rackspace::Errors::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Errors::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Errors::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Errors::ServiceError] # @note Rescue mode is only guaranteed to be active for 90 minutes. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/rescue_mode.html # @see #unrescue # # * Status Transition: # * ACTIVE -> PREP_RESCUE -> RESCUE def rescue requires :identity data = service.rescue_server(identity) merge_attributes(data.body) true end # Remove existing server from rescue mode. # @return [Boolean] returns true if call to remove server from rescue mode reports success # @raise [Fog::Rackspace::Errors::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Errors::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Errors::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Errors::ServiceError] # @note Rescue mode is only guaranteed to be active for 90 minutes. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/exit_rescue_mode.html # @see #rescue # # * Status Transition: # * PREP_UNRESCUE -> ACTIVE def unrescue requires :identity service.unrescue_server(identity) self.state = ACTIVE true end # Change admin password # @param [String] password The administrator password. # @return [Boolean] returns true if operation was scheduled # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note Though Rackspace does not enforce complexity requirements for the password, the operating system might. If the password is not complex enough, the server might enter an ERROR state. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Change_Password-d1e3234.html # # * Status Transition: # * ACTIVE -> PASSWORD -> ACTIVE # * ACTIVE -> PASSWORD -> ERROR (on error) def change_admin_password(password) requires :identity service.change_server_password(identity, password) self.state = PASSWORD self.password = password true end # Setup server for SSH access # @see Servers#bootstrap def setup(credentials = {}) requires :ssh_ip_address, :identity, :public_key, :username retried_disconnect = false commands = [ %{mkdir .ssh}, %{echo "#{public_key}" >> ~/.ssh/authorized_keys}, password_lock, %{echo "#{Fog::JSON.encode(attributes)}" >> ~/attributes.json}, %{echo "#{Fog::JSON.encode(metadata)}" >> ~/metadata.json} ] commands.compact self.password = nil if password_lock Fog::SSH.new(ssh_ip_address, username, credentials).run(commands) rescue Errno::ECONNREFUSED sleep(1) retry # Ubuntu 12.04 images seem to be disconnecting during the ssh setup process. # This rescue block is an effort to address that issue. rescue Net::SSH::Disconnect unless retried_disconnect retried_disconnect = true sleep(1) retry end end def virtual_interfaces @virtual_interfaces ||= Fog::Compute::RackspaceV2::VirtualInterfaces.new :server => self, :service => service end # VNC Console URL # @param [String] Type of vnc console to get ('novnc' or 'xvpvnc') # @return [String] returns URL to vnc console # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note This URL will time out due to inactivity def get_vnc_console(console_type = "xvpvnc") requires :identity data = service.get_vnc_console(identity, console_type) data.body['console']['url'] end private def adminPass=(new_admin_pass) self.password = new_admin_pass end def password_lock if !attributes[:no_passwd_lock].nil? Fog::Logger.warning("Rackspace[:no_passwd_lock] is deprecated since it is now the default behavior, use Rackspace[:passwd_lock] instead") end "passwd -l #{username}" if attributes[:passwd_lock] end def user_data_encoded self.user_data.nil? ? nil : [self.user_data].pack('m') end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/networks.rb0000644000004100000410000000076213411315054025301 0ustar www-datawww-datarequire 'fog/rackspace/models/compute_v2/network' module Fog module Compute class RackspaceV2 class Networks < Fog::Collection model Fog::Compute::RackspaceV2::Network def all data = service.list_networks.body['networks'] load(data) end def get(id) data = service.get_network(id).body['network'] new(data) rescue Fog::Compute::RackspaceV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute_v2/images.rb0000644000004100000410000000573613411315054024700 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute_v2/image' module Fog module Compute class RackspaceV2 class Images < Fog::Collection # @!attribute [rw] name # @return [String] Given a string value x, filters the list of images by image name. attribute :name # @!attribute [rw] status # @return [String] Given a string value x, filters the list of images by status. # @note Possible values are ACTIVE, DELETED, ERROR, SAVING, and UNKNOWN. attribute :status # @!attribute [rw] marker # @return [String] Given a string value x, return object names greater in value than the specified marker. # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/List_Large_Number_of_Objects-d1e1521.html attribute :marker # @!attribute [rw] limit # @return [Integer] For an integer value n, limits the number of results to at most n values. # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/List_Large_Number_of_Objects-d1e1521.html attribute :limit # @!attribute [rw] type # @return [String] Given a string value x, filters the list of images by type. # @note Valid values are BASE and SNAPSHOT attribute :type model Fog::Compute::RackspaceV2::Image # Returns list of images # @return [Fog::Compute::RackspaceV2::Images] Retrieves a list images. # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @note Fog's current implementation only returns 1000 images. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Images-d1e4435.html def all(options = {}) options = { 'name' => name, 'status' => status, 'marker' => marker, 'limit' => limit, 'type' => type }.merge!(options) merge_attributes(options) data = service.list_images_detail(options).body['images'] load(data) end # Retrieve image # @param [String] image_id id of image # @return [Fog::Compute::RackspaceV2:Image] image # @raise [Fog::Compute::RackspaceV2::NotFound] - HTTP 404 # @raise [Fog::Compute::RackspaceV2::BadRequest] - HTTP 400 # @raise [Fog::Compute::RackspaceV2::InternalServerError] - HTTP 500 # @raise [Fog::Compute::RackspaceV2::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Get_Image_Details-d1e4848.html def get(image_id) data = service.get_image(image_id).body['image'] new(data) rescue Fog::Compute::RackspaceV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/cdn_v2/0000755000004100000410000000000013411315054022163 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/cdn_v2/services.rb0000644000004100000410000000103113411315054024326 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/cdn_v2/service' module Fog module Rackspace class CDNV2 < Fog::Service class Services < Fog::Collection model Fog::Rackspace::CDNV2::Service def all(options={}) data = service.list_services(options).body['services'] load(data) end def get(id) data = service.get_service(id).body new(data) rescue Fog::Rackspace::CDNV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/cdn_v2/flavor.rb0000644000004100000410000000033713411315054024004 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class CDNV2 < Fog::Service class Flavor < Fog::Model identity :id attribute :providers attribute :links end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/cdn_v2/flavors.rb0000644000004100000410000000100213411315054024155 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/cdn_v2/flavor' module Fog module Rackspace class CDNV2 < Fog::Service class Flavors < Fog::Collection model Fog::Rackspace::CDNV2::Flavor def all data = service.list_flavors.body['flavors'] load(data) end def get(name) data = service.get_flavor(name).body new(data) rescue Fog::Rackspace::CDNV2::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/cdn_v2/service.rb0000644000004100000410000000272313411315054024154 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class CDNV2 < Fog::Service class Service < Fog::Model attr_accessor :operations UUID_REGEX = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ identity :id attribute :name attribute :domains attribute :origins attribute :caching attribute :restrictions attribute :flavor_id attribute :status attribute :links def initialize(options={}) self.operations = [] super end def add_domain(domain, options={}) self.domains ||= [] self.domains << {domain: domain}.merge(options) self.domains end def add_origin(origin, options={}) self.origins ||= [] self.origins << {origin: origin}.merge(options) self.origins end def add_operation(options={}) self.operations << options end def save if id.nil? data = service.create_service(self) loc = data.headers["Location"] id = UUID_REGEX.match(loc)[0] merge_attributes(id: id) else service.update_service(self) end end def destroy service.delete_service(self) end def destroy_assets(options={}) service.delete_assets(self, options) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/load_balancers/0000755000004100000410000000000013411315054023741 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/load_balancers/virtual_ips.rb0000644000004100000410000000160313411315054026627 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/load_balancers/virtual_ip' module Fog module Rackspace class LoadBalancers class VirtualIps < Fog::Collection model Fog::Rackspace::LoadBalancers::VirtualIp attr_accessor :load_balancer def all data = all_raw load(data) end #HACK - This method is somewhat hacky since there isn't a way to retrieve a single virtual IP. Hopefully long term a method will # be added that allows a single virtual IP to be returned def get(virtual_ip_id) data = all_raw.select { |virtual_ip| virtual_ip['id'] == virtual_ip_id }.first data && new(data) end private def all_raw requires :load_balancer service.list_virtual_ips(load_balancer.id).body['virtualIps'] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/load_balancers/access_rules.rb0000644000004100000410000000126013411315054026740 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/load_balancers/access_rule' module Fog module Rackspace class LoadBalancers class AccessRules < Fog::Collection model Fog::Rackspace::LoadBalancers::AccessRule attr_accessor :load_balancer def all load(all_raw) end def get(access_rule_id) data = all_raw.select { |access_rule| access_rule['id'] == access_rule_id }.first data && new(data) end private def all_raw requires :load_balancer data = service.list_access_rules(load_balancer.id).body['accessList'] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/load_balancers/node.rb0000644000004100000410000000271313411315054025216 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class LoadBalancers class Node < Fog::Model identity :id attribute :address attribute :status attribute :weight attribute :port attribute :type attribute :condition def destroy requires :identity, :load_balancer service.delete_node(load_balancer.identity, identity) true end def save if persisted? update else create end true end private def load_balancer collection.load_balancer end def create requires :load_balancer, :address, :condition, :port options = {} unless weight.nil? options[:weight] = weight end unless type.nil? options[:type] = type end data = service.create_node(load_balancer.id, address, port, condition, options) merge_attributes(data.body['nodes'][0]) end def update requires :load_balancer, :identity options = { :condition => condition } unless weight.nil? options[:weight] = weight end unless type.nil? options[:type] = type end service.update_node(load_balancer.id, identity, options) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/load_balancers/virtual_ip.rb0000644000004100000410000000146613411315054026453 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class LoadBalancers class VirtualIp < Fog::Model identity :id attribute :address attribute :type attribute :ip_version, :aliases => 'ipVersion' def destroy requires :identity, :load_balancer service.delete_virtual_ip(load_balancer.identity, identity) true end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :load_balancer, :type data = service.create_virtual_ip(load_balancer.id, type) merge_attributes(data.body) true end private def load_balancer collection.load_balancer end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/load_balancers/load_balancer.rb0000644000004100000410000002052413411315054027037 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class LoadBalancers class LoadBalancer < Fog::Model #States ACTIVE = 'ACTIVE' ERROR = 'ERROR' PENDING_UPDATE = 'PENDING_UPDATE' PENDING_DELTE = 'PENDING_DELETE' SUSPENDED = 'SUSPENDED' DELETED = 'DELETED' BUILD = 'BUILD' identity :id attribute :cluster attribute :connection_logging, :aliases => 'connectionLogging' attribute :port attribute :protocol attribute :algorithm attribute :virtual_ips, :aliases => 'virtualIps' attribute :created attribute :updated attribute :name attribute :state, :aliases => 'status' attribute :timeout attribute :nodes attribute :https_redirect, :aliases => 'httpsRedirect' def initialize(attributes) #HACK - Since we are hacking how sub-collections work, we have to make sure the service is valid first. # Old 'connection' is renamed as service and should be used instead @service = attributes[:service] || attributes[:connection] super end def access_rules unless @access_rules @access_rules = Fog::Rackspace::LoadBalancers::AccessRules.new({ :service => service, :load_balancer => self}) # prevents loading access rules from non-existent load balancers @access_rules.clear unless persisted? end @access_rules end def access_rules=(new_access_rules=[]) access_rules.load(new_access_rules) end def nodes if @nodes.nil? @nodes = Fog::Rackspace::LoadBalancers::Nodes.new({ :service => service, :load_balancer => self}) # prevents loading nodes from non-existent load balancers @nodes.clear unless persisted? end @nodes end def nodes=(new_nodes=[]) nodes.load(new_nodes) end def https_redirect if @https_redirect.nil? requires :identity @https_redirect = begin service.get_load_balancer(identity).body['loadBalancer']['httpsRedirect'] rescue => e nil end end @https_redirect end def ssl_termination requires :identity ssl_termination = service.get_ssl_termination(identity).body['sslTermination'] rescue Fog::Rackspace::LoadBalancers::NotFound nil end def enable_ssl_termination(securePort, privatekey, certificate, options = {}) requires :identity service.set_ssl_termination(identity, securePort, privatekey, certificate, options) end def disable_ssl_termination requires :identity service.remove_ssl_termination(identity) end def virtual_ips if @virtual_ips.nil? @virtual_ips = Fog::Rackspace::LoadBalancers::VirtualIps.new({ :service => service, :load_balancer => self}) @virtual_ips.clear unless persisted? end @virtual_ips end def virtual_ips=(new_virtual_ips=[]) virtual_ips.load(new_virtual_ips) end def enable_content_caching requires :identity service.set_content_caching identity, true true end def disable_content_caching requires :identity service.set_content_caching identity, false true end def content_caching requires :identity service.get_content_caching(identity).body['contentCaching']['enabled'] end def enable_connection_logging requires :identity service.set_connection_logging identity, true attributes[:connection_logging] = true end def disable_connection_logging requires :identity service.set_connection_logging identity, false attributes[:connection_logging] = false end def health_monitor requires :identity monitor = service.get_monitor(identity).body['healthMonitor'] monitor.count == 0 ? nil : monitor end def enable_health_monitor(type, delay, timeout, attempsBeforeDeactivation, options = {}) requires :identity service.set_monitor(identity, type, delay, timeout, attempsBeforeDeactivation, options) true end def disable_health_monitor requires :identity service.remove_monitor(identity) true end def connection_throttling requires :identity throttle = service.get_connection_throttling(identity).body['connectionThrottle'] throttle.count == 0 ? nil : throttle end def enable_connection_throttling(max_connections, min_connections, max_connection_rate, rate_interval) requires :identity service.set_connection_throttling(identity, max_connections, min_connections, max_connection_rate, rate_interval) true end def disable_connection_throttling requires :identity service.remove_connection_throttling(identity) true end def session_persistence requires :identity persistence = service.get_session_persistence(identity).body['sessionPersistence'] persistence.count == 0 ? nil : persistence end def enable_session_persistence(type) requires :identity service.set_session_persistence(identity, type) true end def disable_session_persistence requires :identity service.remove_session_persistence(identity) true end def destroy requires :identity service.delete_load_balancer(identity) true end def ready? state == ACTIVE end def save if persisted? update else create end true end def usage(options = {}) requires :identity service.get_load_balancer_usage(identity, options).body end def stats requires :identity service.get_stats(identity).body end def error_page requires :identity service.get_error_page(identity).body['errorpage']['content'] end def error_page=(content) requires :identity service.set_error_page identity, content end def reset_error_page requires :identity service.remove_error_page identity end private def create requires :name, :protocol, :virtual_ips options = {} options[:algorithm] = algorithm if algorithm options[:timeout] = timeout if timeout data = service.create_load_balancer(name, protocol, port, virtual_ips, nodes, options) merge_attributes(data.body['loadBalancer']) end def update requires :name, :protocol, :port, :algorithm, :timeout, :https_redirect options = { :name => name, :algorithm => algorithm, :protocol => protocol, :port => port, :timeout => timeout, :https_redirect => !!https_redirect } service.update_load_balancer(identity, options) # TODO - Should this bubble down to nodes? Without tracking changes this would be very inefficient. # For now, individual nodes will have to be saved individually after saving an LB end def connection_logging=(new_value) if !new_value.nil? and new_value.is_a?(Hash) attributes[:connection_logging] = case new_value['enabled'] when true,'true' true when false,'false' false end else attributes[:connection_logging] = new_value end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/load_balancers/access_rule.rb0000644000004100000410000000205713411315054026562 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class LoadBalancers class AccessRule < Fog::Model identity :id attribute :address attribute :type def destroy requires :identity, :load_balancer service.delete_access_rule(load_balancer.identity, identity) true end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :load_balancer, :address, :type service.create_access_rule(load_balancer.id, address, type) #Unfortunately, access rules creation doesn't return an ID, we require a subsequent list call and comparison data = service.list_access_rules(load_balancer.id).body['accessList'].select do |ar| ar['address'] == address && ar['type'] == type end.first merge_attributes(data) true end private def load_balancer collection.load_balancer end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/load_balancers/load_balancers.rb0000644000004100000410000000120713411315054027217 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/load_balancers/load_balancer' module Fog module Rackspace class LoadBalancers class LoadBalancers < Fog::Collection model Fog::Rackspace::LoadBalancers::LoadBalancer def all data = service.list_load_balancers.body['loadBalancers'] load(data) end def get(load_balancer_id) if load_balancer = service.get_load_balancer(load_balancer_id).body['loadBalancer'] new(load_balancer) end rescue Fog::Rackspace::LoadBalancers::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/load_balancers/nodes.rb0000644000004100000410000000126613411315054025403 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/load_balancers/node' module Fog module Rackspace class LoadBalancers class Nodes < Fog::Collection model Fog::Rackspace::LoadBalancers::Node attr_accessor :load_balancer def all requires :load_balancer data = service.list_nodes(load_balancer.id).body['nodes'] load(data) end def get(node_id) requires :load_balancer if node = service.get_node(load_balancer.id, node_id).body['node'] new(node) end rescue Fog::Rackspace::LoadBalancers::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/block_storage/0000755000004100000410000000000013411315054023626 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/block_storage/snapshot.rb0000644000004100000410000000674713411315054026030 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class BlockStorage class Snapshot < Fog::Model AVAILABLE = 'available' CREATING = 'creating' DELETING = 'deleting' ERROR = 'error' ERROR_DELETING = 'error_deleting' # @!attribute [r] id # @return [String] The snapshot id identity :id # @!attribute [r] created_at # @return [String] snapshot creation time attribute :created_at, :aliases => 'createdAt' # @!attribute [r] state # @return [String] snapshot status attribute :state, :aliases => 'status' # @!attribute [rw] display_name # @return [String] display name of snapshot attribute :display_name # @!attribute [rw] display_description # @return [String] display description of snapshot attribute :display_description # @!attribute [rw] size # @return [String] size of snapshot attribute :size # @!attribute [rw] volume_id # @return [String] the volume_id of the snapshot attribute :volume_id # @!attribute [r] availability_zone # @return [String] region of the snapshot attribute :availability_zone # @!attribute [r] force # @return [Boolean] `force` creation flag attribute :force # Returns true if the snapshot is in a ready state # @return [Boolean] returns true if snapshot is in a ready state def ready? state == AVAILABLE end # Creates the snapshot # @param force [Boolean] Set to true to force service to create snapshot # @raise [Fog::Rackspace::BlockStorage::IdentifierTaken] if the snapshot has been previously saved. # @return [Boolean] returns true if snapshot is being created # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @note A snapshot object cannot be updated # @note All writes to the volume should be flushed before creating the snapshot, either by un-mounting any file systems on the volume or by detaching the volume. # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/POST_createSnapshot__v1__tenant_id__snapshots.html def save requires :volume_id raise IdentifierTaken.new('Resaving may cause a duplicate snapshot to be created') if persisted? data = service.create_snapshot(volume_id, { :display_name => display_name, :display_description => display_description, :force => force }) merge_attributes(data.body['snapshot']) true end # Destroys snapshot # @return [Boolean] returns true if snapshot was deleted # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/DELETE_deleteSnapshot__v1__tenant_id__snapshots.html def destroy requires :identity service.delete_snapshot(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/block_storage/volumes.rb0000644000004100000410000000311613411315054025646 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/block_storage/volume' module Fog module Rackspace class BlockStorage class Volumes < Fog::Collection model Fog::Rackspace::BlockStorage::Volume # Returns list of volumes # @return [Fog::Rackspace::BlockStorage::Volumes] Retrieves a volumes # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getVolumesSimple__v1__tenant_id__volumes.html def all data = service.list_volumes.body['volumes'] load(data) end # Retrieves volume # @param [String] volume_id for snapshot to be returned # @return [Fog::Rackspace::BlockStorage::Volume] # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getVolume__v1__tenant_id__volumes.html def get(volume_id) data = service.get_volume(volume_id).body['volume'] new(data) rescue Fog::Rackspace::BlockStorage::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/block_storage/volume_type.rb0000644000004100000410000000057613411315054026533 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class BlockStorage class VolumeType < Fog::Model # @!attribute [r] id # @return [String] The volume type id identity :id # @!attribute [r] name # @return [String] The name of the volume type attribute :name attribute :extra_specs end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/block_storage/volume_types.rb0000644000004100000410000000323413411315054026710 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/block_storage/volume_type' module Fog module Rackspace class BlockStorage class VolumeTypes < Fog::Collection model Fog::Rackspace::BlockStorage::VolumeType # Returns list of volume types # @return [Fog::Rackspace::BlockStorage::VolumeTypes] Retrieves a list volume types. # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getVolumeTypes__v1__tenant_id__types.html def all data = service.list_volume_types.body['volume_types'] load(data) end # Retrieves volume type # @param [String] volume_type_id for volume_type to be returned # @return [Fog::Rackspace::BlockStorage::VolumeType] # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getVolumeType__v1__tenant_id__types.html def get(volume_type_id) data = service.get_volume_type(volume_type_id).body['volume_type'] new(data) rescue Fog::Rackspace::BlockStorage::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/block_storage/snapshots.rb0000644000004100000410000000316213411315054026177 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/block_storage/snapshot' module Fog module Rackspace class BlockStorage class Snapshots < Fog::Collection model Fog::Rackspace::BlockStorage::Snapshot # Returns list of snapshots # @return [Fog::Rackspace::BlockStorage::Snapshots] Retrieves a snapshots # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getSnapshotsSimple__v1__tenant_id__snapshots.html def all data = service.list_snapshots.body['snapshots'] load(data) end # Retrieves snapshot # @param [String] snapshot_id for snapshot to be returned # @return [Fog::Rackspace::BlockStorage::Volume] # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/GET_getSnapshot__v1__tenant_id__snapshots.html def get(snapshot_id) data = service.get_snapshot(snapshot_id).body['snapshot'] new(data) rescue Fog::Rackspace::BlockStorage::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/block_storage/volume.rb0000644000004100000410000001311013411315054025456 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class BlockStorage class Volume < Fog::Model AVAILABLE = 'available' ATTACHING = 'attaching' CREATING = 'creating' DELETING = 'deleting' ERROR = 'error' ERROR_DELETING = 'error_deleting' IN_USE = 'in-use' # @!attribute [r] id # @return [String] The volume id identity :id # @!attribute [r] created_at # @return [String] volume creation date attribute :created_at, :aliases => 'createdAt' # @!attribute [r] state # @return [String] volume status attribute :state, :aliases => 'status' # @!attribute [rw] display_name # @return [String] display name of volume attribute :display_name # @!attribute [rw] display_description # @return [String] display description of volume attribute :display_description # @!attribute [rw] size # @return [String] size of the volume in GB (100 GB minimum) attribute :size # @!attribute [r] attachments # @return [Array] returns an array of hashes containing attachment information attribute :attachments # @!attribute [rw] volume_type # @return [String] type of volume attribute :volume_type # @!attribute [r] availability_zone # @return [String] region of the volume attribute :availability_zone # @!attribute [rw] image_id # @return [String] The ID of an image used to create a bootable volume. attribute :image_id, :aliases => ['image', 'imageRef'], :squash => 'id' # Returns true if the volume is in a ready state # @return [Boolean] returns true if volume is in a ready state def ready? state == AVAILABLE end # Returns true if the volume is attached # @return [Boolean] true if the volume is attached def attached? state == IN_USE end # Returns a list of snapshots associated with the volume # @return [Fog::Rackspace::BlockStorage::Snapshots] # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] def snapshots service.snapshots.select { |s| s.volume_id == identity } end # Creates a snapshot from the current volume # @param [Hash] options # @option options [String] :display_name of snapshot # @option options [String] :display_description of snapshot # @option options [Boolean] :force - If set to true, snapshot will be taken even if volume is still mounted. # @return [Fog::Rackspace::BlockStorage::Snapshot] # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @note All writes to the volume should be flushed before creating the snapshot, either by un-mounting any file systems on the volume or by detaching the volume. # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/POST_createSnapshot__v1__tenant_id__snapshots.html def create_snapshot(options={}) requires :identity service.snapshots.create(options.merge(:volume_id => identity)) end # Creates volume # @raise [Fog::Rackspace::BlockStorage::IdentifierTaken] if the volume has been previously saved. # @return [Boolean] returns true if volume was successfully created # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @note A volume object cannot be updated # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/POST_createVolume__v1__tenant_id__volumes.html def save requires :size raise IdentifierTaken.new('Resaving may cause a duplicate volume to be created') if persisted? data = service.create_volume(size, { :display_name => display_name, :display_description => display_description, :volume_type => volume_type, :availability_zone => availability_zone, :snapshot_id => attributes[:snapshot_id], :image_id => attributes[:image_id], :source_volid => attributes[:source_volid] }) merge_attributes(data.body['volume']) true end # Destroys Volume # @return [Boolean] returns true if volume was deleted # @raise [Fog::Rackspace::BlockStorage::NotFound] - HTTP 404 # @raise [Fog::Rackspace::BlockStorage::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::BlockStorage::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::BlockStorage::ServiceError] # @note You cannot delete a volume until all of its dependent snaphosts have been deleted. # @see http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/DELETE_deleteVolume__v1__tenant_id__volumes.html def destroy requires :identity service.delete_volume(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute/0000755000004100000410000000000013411315054022464 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/compute/image.rb0000644000004100000410000000171113411315054024073 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Rackspace class Image < Fog::Model identity :id attribute :name attribute :created_at, :aliases => 'created' attribute :updated_at, :aliases => 'updated' attribute :progress attribute :status attribute :server_id, :aliases => 'serverId' def server=(new_server) requires :id self.server_id = new_server.id end def destroy requires :id service.delete_image(id) true end def ready? status == 'ACTIVE' end def save raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :server_id data = service.create_image(server_id, 'name' => name) merge_attributes(data.body['image']) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute/flavor.rb0000644000004100000410000000135113411315054024302 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Compute class Rackspace class Flavor < Fog::Model identity :id attribute :disk attribute :name attribute :ram def bits 64 end def cores # Each server is assigned 4 virtual cores and # given a percentage of CPU cycles based on size 4 * case ram when 256 1/64.0 when 512 1/32.0 when 1024 1/16.0 when 2048 1/8.0 when 4096 1/4.0 when 8192 1/2.0 when 15872 1 when 30720 2 end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute/flavors.rb0000644000004100000410000000103513411315054024464 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute/flavor' module Fog module Compute class Rackspace class Flavors < Fog::Collection model Fog::Compute::Rackspace::Flavor def all data = service.list_flavors_detail.body['flavors'] load(data) end def get(flavor_id) data = service.get_flavor_details(flavor_id).body['flavor'] new(data) rescue Fog::Compute::Rackspace::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute/servers.rb0000644000004100000410000000140113411315054024476 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute/server' module Fog module Compute class Rackspace class Servers < Fog::Collection model Fog::Compute::Rackspace::Server def all data = service.list_servers_detail.body['servers'] load(data) end def bootstrap(new_attributes = {}) server = create(new_attributes) server.wait_for { ready? } server.setup(:password => server.password) server end def get(server_id) if server = service.get_server_details(server_id).body['server'] new(server) end rescue Fog::Compute::Rackspace::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute/server.rb0000644000004100000410000000523413411315054024323 0ustar www-datawww-datarequire 'fog/compute/models/server' module Fog module Compute class Rackspace class Server < Fog::Compute::Server identity :id attribute :addresses attribute :flavor_id, :aliases => 'flavorId', :type => :integer attribute :host_id, :aliases => 'hostId' attribute :image_id, :aliases => 'imageId', :type => :integer attribute :metadata attribute :name attribute :personality attribute :progress attribute :state, :aliases => 'status' attr_reader :password def initialize(attributes={}) self.flavor_id ||= 1 # 256 server self.image_id ||= 49 # Ubuntu 10.04 LTS 64bit super end def destroy requires :id service.delete_server(id) true end def flavor requires :flavor_id service.flavors.get(flavor_id) end def image requires :image_id service.images.get(image_id) end def images requires :id service.images(:server => self) end def private_ip_address addresses['private'].first end def public_ip_address addresses['public'].first end def ready? self.state == 'ACTIVE' end def reboot(type = 'SOFT') requires :id service.reboot_server(id, type) true end def save(options = {}) raise Fog::Errors::Error.new('Resaving an existing object may create a duplicate') if persisted? requires :flavor_id, :image_id options = { 'metadata' => metadata, 'name' => name, 'personality' => personality } options = options.reject {|key, value| value.nil?} data = service.create_server(flavor_id, image_id, options) merge_attributes(data.body['server']) true end def setup(credentials = {}) requires :ssh_ip_address, :identity, :public_key, :username Fog::SSH.new(ssh_ip_address, username, credentials).run([ %{mkdir .ssh}, %{echo "#{public_key}" >> ~/.ssh/authorized_keys}, %{passwd -l #{username}}, %{echo "#{Fog::JSON.encode(attributes)}" >> ~/attributes.json}, %{echo "#{Fog::JSON.encode(metadata)}" >> ~/metadata.json} ]) rescue Errno::ECONNREFUSED sleep(1) retry end private def adminPass=(new_admin_pass) @password = new_admin_pass end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/compute/images.rb0000644000004100000410000000131113411315054024252 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/compute/image' module Fog module Compute class Rackspace class Images < Fog::Collection model Fog::Compute::Rackspace::Image attribute :server def all data = service.list_images_detail.body['images'] models = load(data) if server self.replace(self.select {|image| image.server_id == server.id}) else models end end def get(image_id) data = service.get_image_details(image_id).body['image'] new(data) rescue Fog::Compute::Rackspace::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/0000755000004100000410000000000013411315054023674 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/resources.rb0000644000004100000410000000175513411315054026243 0ustar www-datawww-datarequire 'fog/rackspace/models/orchestration/resource' module Fog module Rackspace class Orchestration class Resources < Fog::Collection model Fog::Rackspace::Orchestration::Resource def types service.list_resource_types.body['resource_types'].sort end def all(stack, options={}) data = service.list_resources(stack, options).body['resources'] load(data) end def get(resource_name, stack=nil) stack = self.first.stack if stack.nil? data = service.show_resource_data(stack.stack_name, stack.id, resource_name).body['resource'] new(data) rescue Fog::Rackspace::Orchestration::NotFound nil end def metadata(stack_name, stack_id, resource_name) service.show_resource_metadata(stack_name, stack_id, resource_name).body['resource'] rescue Fog::Rackspace::Orchestration::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/template.rb0000644000004100000410000000035613411315054026040 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Template < Fog::Model %w{description heat_template_version parameters resources}.each do |a| attribute a.to_sym end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/events.rb0000644000004100000410000000133513411315054025527 0ustar www-datawww-datarequire 'fog/rackspace/models/orchestration/event' module Fog module Rackspace class Orchestration class Events < Fog::Collection model Fog::Rackspace::Orchestration::Event def all(obj, options={}) data = if obj.is_a?(Stack) service.list_stack_events(obj, options).body['events'] else service.list_resource_events(obj.stack, obj, options).body['events'] end load data end def get(stack, resource, event_id) data = service.show_event_details(stack, resource, event_id).body['event'] new(data) rescue Fog::Rackspace::Orchestration::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/resource_schemas.rb0000644000004100000410000000045613411315054027560 0ustar www-datawww-data module Fog module Rackspace class Orchestration class ResourceSchemas < Fog::Collection def get(resource_type) service.show_resource_schema(resource_type).body rescue Fog::Rackspace::Orchestration::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/event.rb0000644000004100000410000000054213411315054025343 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Event < Fog::Model include Reflectable identity :id %w{resource_name event_time links logical_resource_id resource_status resource_status_reason physical_resource_id}.each do |a| attribute a.to_sym end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/stacks.rb0000644000004100000410000000163313411315054025514 0ustar www-datawww-datarequire 'fog/rackspace/models/orchestration/stack' module Fog module Rackspace class Orchestration class Stacks < Fog::Collection model Fog::Rackspace::Orchestration::Stack def all(options={}) data = service.list_stack_data(options).body['stacks'] load(data) end def get(name, id) data = service.show_stack_details(name, id).body['stack'] new(data) rescue Fog::Rackspace::Orchestration::NotFound nil end def adopt(options={}) service.create_stack(options) end def create(options={}) service.create_stack(options).body['stack'] end def preview(options={}) data = service.preview_stack(options).body['stack'] new(data) end def build_info service.build_info.body end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/resource.rb0000644000004100000410000000126713411315054026056 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Resource < Fog::Model include Reflectable identity :id %w{resource_name description links logical_resource_id resource_status updated_time required_by resource_status_reason resource_type}.each do |a| attribute a.to_sym end def events(options={}) @events ||= service.events.all(self, options) end def metadata @metadata ||= service.show_resource_metadata(stack, self.resource_name).body['metadata'] end def template @template ||= service.templates.get(self) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/templates.rb0000644000004100000410000000140513411315054026217 0ustar www-datawww-datarequire 'fog/rackspace/models/orchestration/template' module Fog module Rackspace class Orchestration class Templates < Fog::Collection model Fog::Rackspace::Orchestration::Template def get(obj) data = if obj.is_a?(Stack) service.get_stack_template(obj).body else service.show_resource_template(obj.resource_name).body end new(data) rescue Fog::Rackspace::Orchestration::NotFound nil end def validate(options={}) data = service.validate_template(options).body temp = new temp.parameters = data['Parameters'] temp.description = data['Description'] temp end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/orchestration/stack.rb0000644000004100000410000000205613411315054025331 0ustar www-datawww-datamodule Fog module Rackspace class Orchestration class Stack < Fog::Model identity :id %w{description links stack_status_reason stack_name creation_time updated_time}.each do |a| attribute a.to_sym end def details service.show_stack_details(self.stack_name, self.id).body['stack'] rescue Fog::Rackspace::Orchestration::NotFound nil end def resources @resources ||= service.resources.all(self) end def events(options={}) @events ||= service.events.all(self, options) end def template @template ||= service.templates.get(self) end def save(options={}) if persisted? service.update_stack(self, options).body['stack'] else service.stacks.create(options) end end def abandon service.abandon_stack(self) end def delete service.delete_stack(self) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/0000755000004100000410000000000013411315054023175 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/alarm.rb0000644000004100000410000000311213411315054024613 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/monitoring/base' module Fog module Rackspace class Monitoring class Alarm < Fog::Rackspace::Monitoring::Base identity :id attribute :entity, :aliases => 'entity_id' attribute :check, :aliases => 'check_id' attribute :disabled, :type => :boolean attribute :label attribute :criteria attribute :check_type attribute :notification_plan_id def entity=(obj) attributes[:entity] = obj.is_a?(String) ? Entity.new(:id => obj) : obj end def check=(obj) attributes[:check] = obj.is_a?(String) ? Check.new(:id => obj) : obj end def params(options={}) h = { 'disabled' => disabled, 'label' => label, 'criteria' => criteria, 'notification_plan_id' => notification_plan_id, }.merge(options) h.reject {|key, value| value.nil?} end def save requires :notification_plan_id requires :entity requires :check if identity service.update_alarm(entity.id, identity, params) else options = params('check_type' => check_type, 'check_id' => check.id) data = service.create_alarm(entity.id, options) self.id = data.headers['X-Object-ID'] end true end def destroy requires :id service.delete_alarm(entity.id, id) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/alarm_examples.rb0000644000004100000410000000134213411315054026514 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/monitoring/alarm_example' module Fog module Rackspace class Monitoring class AlarmExamples < Fog::Collection model Fog::Rackspace::Monitoring::AlarmExample def all data = service.list_alarm_examples.body['values'] load(data) end def get(alarm_example_id) data = service.get_alarm_example(alarm_example_id).body new(data) rescue Fog::Rackspace::Monitoring::NotFound nil end def evaluate(alarm_example_id, options={}) data = service.evaluate_alarm_example(alarm_example_id, options).body new(data) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/checks.rb0000644000004100000410000000204213411315054024760 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/monitoring/check' module Fog module Rackspace class Monitoring class Checks < Fog::Collection attribute :entity attribute :marker model Fog::Rackspace::Monitoring::Check def all(options={}) requires :entity data = service.list_checks(entity.identity, options).body self.marker = data['metadata']['next_marker'] load(data['values']) end def get(check_id) requires :entity data = service.get_check(entity.identity, check_id).body new(data) rescue Fog::Rackspace::Monitoring::NotFound nil end def new(attributes = {}) requires :entity unless attributes[:entity] super({ :entity => entity }.merge!(attributes)) end def create(attributes = {}) requires :entity unless attributes[:entity] super({ :entity => entity }.merge!(attributes)) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/data_points.rb0000644000004100000410000000304113411315054026025 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/monitoring/data_point' module Fog module Rackspace class Monitoring class DataPoints < Fog::Collection attribute :metric model Fog::Rackspace::Monitoring::DataPoint def all self.fetch(:resolution => :full) end # Fetch the datapoints for a metric # ==== Parameters # # * options<~Hash> - optional paramaters # * from<~Integer> - timestamp in milliseconds # * to<~Integer> - timestamp in milliseconds # * points<~Integer> - Number of points to fetch # * resolution<~String> - Should be one of :full, :min5, :min20, :min60, :min240, :min1440 # * select<~Array> - Should be an array of :average, :max, :min, :variance # # ==== Returns # * datapoints<~Fog::Rackspace::Monitoring::Datapoints>: def fetch(options={}) requires :metric options[:from] ||= (Time.now.to_i * 1000) - (3600 * 1000) options[:to] ||= Time.now.to_i * 1000 options[:points] ||= 1 unless options[:resolution] if options[:resolution] options[:resolution] = options[:resolution].upcase end data = service.list_data_points(metric.check.entity.id, metric.check.id, metric.name, options).body['values'] load(data) end def new(attributes = {}) requires :metric super({ :metric => metric }.merge!(attributes)) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/metric.rb0000644000004100000410000000076113411315054025011 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/monitoring/base' module Fog module Rackspace class Monitoring class Metric < Fog::Rackspace::Monitoring::Base identity :name attribute :check def datapoints(options={}) @datapoints ||= begin Fog::Rackspace::Monitoring::DataPoints.new( :metric => self, :service => service ) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/check_type.rb0000644000004100000410000000046313411315054025643 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/monitoring/base' module Fog module Rackspace class Monitoring class CheckType < Fog::Rackspace::Monitoring::Base identity :id attribute :type attribute :fields attribute :channel end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/check_types.rb0000644000004100000410000000070113411315054026021 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/monitoring/check_type' module Fog module Rackspace class Monitoring class CheckTypes < Fog::Collection model Fog::Rackspace::Monitoring::CheckType def all data = service.list_check_types.body['values'] load(data) end def new(attributes = {}) super({ }.merge!(attributes)) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/metrics.rb0000644000004100000410000000105413411315054025170 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/monitoring/metric' module Fog module Rackspace class Monitoring class Metrics < Fog::Collection attribute :check model Fog::Rackspace::Monitoring::Metric def all requires :check data = service.list_metrics(check.entity.id, check.id).body['values'] load(data) end def new(attributes = {}) requires :check super({ :check => check }.merge!(attributes)) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/alarm_example.rb0000644000004100000410000000073013411315054026331 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/monitoring/base' module Fog module Rackspace class Monitoring class AlarmExample < Fog::Rackspace::Monitoring::Base identity :id attribute :label attribute :description attribute :check_type attribute :criteria attribute :fields attribute :bound_criteria def bound? !bound_criteria.nil? end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/base.rb0000644000004100000410000000144213411315054024435 0ustar www-datawww-datarequire 'digest/md5' module Fog module Rackspace class Monitoring class Base < Fog::Model attribute :created_at attribute :updated_at # Back to drawing board on this one I think def hash attrs = attributes.dup attrs.delete_if {|key, value| [:created_at, :updated_at, :id].include?(key)} attrs.delete_if {|key, value| value.kind_of?(Base) } keys = attrs.keys.map{|sym| sym.to_s}.sort.join '' values = attrs.values.map{|sym| sym.to_s}.sort.join '' Digest::MD5.hexdigest(keys + values) end def compare?(b) a_o = params b_o = b.params remain = a_o.reject {|key, value| b_o[key] === value} remain.empty? end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/alarms.rb0000644000004100000410000000175413411315054025010 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/monitoring/alarm' module Fog module Rackspace class Monitoring class Alarms < Fog::Collection attribute :entity attribute :marker model Fog::Rackspace::Monitoring::Alarm def all(options={}) requires :entity data = service.list_alarms(entity.identity, options).body self.marker = data['metadata']['next_marker'] load(data['values']) end def get(alarm_id) requires :entity data = service.get_alarm(entity.identity, alarm_id).body new(data) rescue Fog::Rackspace::Monitoring::NotFound nil end def new(attributes = {}) requires :entity super({ :entity => entity }.merge!(attributes)) end def create(attributes = {}) requires :entity super({ :entity => entity }.merge!(attributes)) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/entities.rb0000644000004100000410000000217113411315054025347 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/monitoring/entity' require 'fog/rackspace/models/monitoring/check' module Fog module Rackspace class Monitoring class Entities < Fog::Collection model Fog::Rackspace::Monitoring::Entity attribute :marker def all(options={}) data = service.list_entities(options).body self.marker = data['metadata']['next_marker'] load(data['values']) end def get(entity_id) data = service.get_entity(entity_id).body new(data) rescue Fog::Rackspace::Monitoring::NotFound nil end def overview(options={}) body = service.list_overview(options).body self.marker = body['metadata']['next_marker'] load_all(body['values']) end def load_all(objects) clear for object in objects en = new(object['entity']) self << en en.checks.load(object['checks']) en.alarms.load(object['alarms']) end self end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/notifications.rb0000644000004100000410000000123513411315054026374 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/monitoring/notification' module Fog module Rackspace class Monitoring class Notifications < Fog::Collection model Fog::Rackspace::Monitoring::Notification attribute :marker def all(options={}) data = service.list_notifications(options).body marker = data['metadata']['next_marker'] load(data['values']) end def get(notification_id) data = service.get_notification(notification_id).body new(data) rescue Fog::Rackspace::Monitoring::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/agent_tokens.rb0000644000004100000410000000122113411315054026177 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/monitoring/agent_token' module Fog module Rackspace class Monitoring class AgentTokens < Fog::Collection attribute :marker model Fog::Rackspace::Monitoring::AgentToken def all(options={}) clear body = service.list_agent_tokens(options).body self.marker = body['metadata']['next_marker'] load(body['values']) end def get(id) data = service.get_agent_token(id).body new(data) rescue Fog::Rackspace::Monitoring::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/entity.rb0000644000004100000410000000264713411315054025047 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/monitoring/base' module Fog module Rackspace class Monitoring class Entity < Fog::Rackspace::Monitoring::Base identity :id attribute :label attribute :metadata attribute :ip_addresses attribute :agent_id attribute :managed, :default => false attribute :uri def params options = { 'label' => label, 'metadata' => metadata, 'ip_addresses'=> ip_addresses, 'agent_id' => agent_id } options.reject {|key, value| value.nil?} end def save if identity data = service.update_entity(identity, params) else data = service.create_entity(params) self.id = data.headers['X-Object-ID'] end true end def checks @checks ||= begin Fog::Rackspace::Monitoring::Checks.new( :entity => self, :service => service ) end end def alarms @alarms ||= begin Fog::Rackspace::Monitoring::Alarms.new( :entity => self, :service => service ) end end def destroy requires :id service.delete_entity(id) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/agent_token.rb0000644000004100000410000000156013411315054026022 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/monitoring/base' module Fog module Rackspace class Monitoring class AgentToken < Fog::Rackspace::Monitoring::Base identity :id attribute :label attribute :token def params options = { 'label' => label, 'token' => token } options.reject {|key, value| value.nil?} end def save if identity raise NotImplementedError.new "Updating Agent Tokens is not currently implemented" else data = service.create_agent_token(params) self.id = data.headers['X-Object-ID'] end true end def destroy requires :id service.delete_agent_token(id) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/check.rb0000644000004100000410000000356313411315054024606 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/monitoring/base' module Fog module Rackspace class Monitoring class Check < Fog::Rackspace::Monitoring::Base identity :id attribute :entity attribute :label attribute :metadata attribute :target_alias attribute :target_resolver attribute :target_hostname attribute :period attribute :timeout attribute :type attribute :details attribute :disabled attribute :monitoring_zones_poll def entity=(obj) attributes[:entity] = obj.is_a?(String) ? Entity.new(:id => obj) : obj end def params(options={}) h = { 'label' => label, 'metadata' => metadata, 'target_alias'=> target_alias, 'target_resolver' => target_resolver, 'target_hostname' => target_hostname, 'period' => period, 'timeout'=> timeout, 'details'=> details, 'monitoring_zones_poll'=> monitoring_zones_poll, 'disabled'=> disabled }.merge(options) h.reject {|key, value| value.nil?} end def save if identity data = service.update_check(entity.id, identity, params) else requires :type options = params('type' => type) data = service.create_check(entity.id, options) self.id = data.headers['X-Object-ID'] end true end def destroy requires :id service.delete_check(entity.id, id) end def metrics @metrics ||= begin Fog::Rackspace::Monitoring::Metrics.new( :check => self, :service => service ) end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/data_point.rb0000644000004100000410000000064413411315054025650 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/monitoring/base' module Fog module Rackspace class Monitoring class DataPoint < Fog::Rackspace::Monitoring::Base attribute :num_points, :aliases => "numPoints" attribute :average attribute :variance attribute :min attribute :max attribute :timestamp attribute :metric end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/monitoring/notification.rb0000644000004100000410000000157613411315054026221 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/monitoring/base' module Fog module Rackspace class Monitoring class Notification < Fog::Rackspace::Monitoring::Base identity :id attribute :label attribute :details attribute :type def params options = { 'label' => label, 'details' => details, 'type' => type, } options.reject {|key, value| value.nil?} end def save if identity data = service.update_notification(identity, params) else data = service.create_notification(params) self.id = data.headers['X-Object-ID'] end true end def destroy requires :id service.delete_notification(id) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/storage/0000755000004100000410000000000013411315054022454 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/storage/account.rb0000644000004100000410000000415513411315054024442 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Storage class Rackspace class Account < Fog::Model # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/View_Account_Info-d1e11995.html # @!attribute [rw] meta_temp_url_key # @return [String] The temporary URL key used to generate temporary access to files # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Create_TempURL-d1a444.html attribute :meta_temp_url_key, :aliases => 'X-Account-Meta-Temp-Url-Key' # @!attribute [r] container_count # @return [Integer] The number of containers in account attribute :container_count, :aliases => 'X-Account-Container-Count', :type => :integer # @!attribute [r] bytes_used # @return [Integer] The total number of bytes used by the account attribute :bytes_used, :aliases => 'X-Account-Bytes-Used', :type => :integer # @!attribute [r] object_count # @return [Integer] The total number of objects in the account attribute :object_count, :aliases => 'X-Account-Object-Count', :type => :integer # Saves account settings (meta_temp_url_key) # @return [Boolean] returns true if successfully updated # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def save service.post_set_meta_temp_url_key meta_temp_url_key true end # Reload account with latest data from Cloud Files # @return [Fog::Storage::Rackspace::Account] returns itself # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def reload response = service.head_containers merge_attributes response.headers end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/storage/directories.rb0000644000004100000410000000475713411315054025332 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/storage/directory' module Fog module Storage class Rackspace class Directories < Fog::Collection model Fog::Storage::Rackspace::Directory # Returns list of directories # @return [Fog::Storage::Rackspace::Directories] Retrieves a list directories. # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @note Fog's current implementation only returns 10,000 directories # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/View_List_of_Containers-d1e1100.html def all data = service.get_containers.body load(data) end # Retrieves directory # @param [String] key of directory # @param options [Hash]: # @option options [String] cdn_cname CDN CNAME used when calling Directory#public_url # @return [Fog::Storage::Rackspace::Directory] # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @example # directory = fog.directories.get('video', :cdn_cname => 'http://cdn.lunenburg.org') # files = directory.files # files.first.public_url # # @see Directory#public_url # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/View-Container_Info-d1e1285.html def get(key, options = {}) data = service.get_container(key, options) directory = new(:key => key, :cdn_cname => options[:cdn_cname]) for key, value in data.headers if ['X-Container-Bytes-Used', 'X-Container-Object-Count'].include?(key) directory.merge_attributes(key => value) end end directory.metadata = Metadata.from_headers(directory, data.headers) directory.files.merge_attributes(options) directory.files.instance_variable_set(:@loaded, true) data.body.each do |file| directory.files << directory.files.new(file) end directory rescue Fog::Storage::Rackspace::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/storage/metadata.rb0000644000004100000410000001211413411315054024560 0ustar www-datawww-datamodule Fog module Storage class Rackspace class Metadata OBJECT_META_PREFIX = "X-Object-Meta-" OBJECT_REMOVE_META_PREFIX = "X-Remove-Object-Meta-" CONTAINER_META_PREFIX = "X-Container-Meta-" CONTAINER_REMOVE_META_PREFIX = "X-Remove-Container-Meta-" # Cloud Files will ignore headers without a value DUMMY_VALUE = 1 CONTAINER_KEY_REGEX = /^#{CONTAINER_META_PREFIX}(.*)/ OBJECT_KEY_REGEX = /^#{OBJECT_META_PREFIX}(.*)/ # @!attribute [rw] data # @return [Hash] underlying data store for metadata class attr_reader :data # @!attribute [rw] parent # @return [Fog::Storage::Rackspace::Directory,Fog::Storage::Rackspace::File] the parent object of the metadata attr_reader :parent # Initialize # @param [Fog::Storage::Rackspace::Directory,Fog::Storage::Rackspace::File] parent object of the metadata # @param [Hash] hash containing initial metadata values def initialize(parent, hash={}) @data = hash || {} @deleted_hash = {} @parent = parent end # Delete key value pair from metadata # @param [String] key to be deleted # @return [Object] returns value for key # @note Metadata must be deleted using this method in order to properly remove it from Cloud Files def delete(key) data.delete(key) @deleted_hash[key] = nil end # Returns metadata in a format expected by Cloud Files # @return [Hash] Metadata in a format expected by Cloud Files def to_headers headers = {} h = data.merge(@deleted_hash) h.each_pair do |k,v| key = to_header_key(k,v) headers[key] = v || DUMMY_VALUE end headers end # Retrieve specific value for key from Metadata. # * If key is of type String, this method will return the value of the metadatum # @param [#key] key # @return [#value] def [](key) return nil unless key @data[key.to_s] || @data[key.to_sym] end # Set value for key. # * If key is of type String, this method will set/add the value to Metadata # @param [#key] key # @return [String] def []=(key, value) return nil unless key if @data[key.to_s] @data[key.to_s] = value elsif @data[key.to_sym] @data[key.to_sym] = value else @data[key] = value end end # Creates metadata object from Cloud File Headers # @param [Fog::Storage::Rackspace::Directory,Fog::Storage::Rackspace::File] parent object of the metadata # @param [Hash] headers Cloud File headers def self.from_headers(parent, headers) metadata = Metadata.new(parent) headers.each_pair do |k, v| key = metadata.send(:to_key, k) next unless key metadata.data[key] = v end metadata end # Returns true if method is implemented by Metadata class # @param [Symbol] method_sym # @param [Boolean] include_private def respond_to?(method_sym, include_private = false) super(method_sym, include_private) || data.respond_to?(method_sym, include_private) end # Invoked by Ruby when obj is sent a message it cannot handle. def method_missing(method, *args, &block) data.send(method, *args, &block) end private def directory? [Fog::Storage::Rackspace::Directory, Fog::Storage::Rackspace::Directories].include? parent_class end def file? [Fog::Storage::Rackspace::File, Fog::Storage::Rackspace::Files].include? parent_class end def parent_class parent.is_a?(Class) ? parent : parent.class end def meta_prefix if directory? CONTAINER_META_PREFIX elsif file? OBJECT_META_PREFIX else raise "Metadata prefix is unknown for #{parent_class}" end end def remove_meta_prefix if directory? CONTAINER_REMOVE_META_PREFIX elsif file? OBJECT_REMOVE_META_PREFIX else raise "Remove Metadata prefix is unknown for #{parent_class}" end end def meta_prefix_regex if directory? CONTAINER_KEY_REGEX elsif file? OBJECT_KEY_REGEX else raise "Metadata prefix is unknown for #{parent_class}" end end def to_key(key) m = key.match meta_prefix_regex return nil unless m && m[1] a = m[1].split('-') a.map!(&:downcase) str = a.join('_') str.to_sym end def to_header_key(key, value) prefix = value.nil? ? remove_meta_prefix : meta_prefix prefix + key.to_s.split(/[-_]/).map(&:capitalize).join('-') end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/storage/files.rb0000644000004100000410000001767513411315054024123 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/storage/file' module Fog module Storage class Rackspace class Files < Fog::Collection # @!attribute [rw] directory # @return [String] The name of the directory # @note Methods in this class require this attribute to be set attribute :directory # @!attribute [rw] limit # @return [Integer] For an integer value n, limits the number of results to at most n values. # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/List_Large_Number_of_Objects-d1e1521.html attribute :limit # @!attribute [rw] marker # @return [String] Given a string value x, return object names greater in value than the specified marker. # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/List_Large_Number_of_Objects-d1e1521.html attribute :marker # @!attribute [rw] path # @return [String] For a string value x, return the object names nested in the pseudo path. # Equivalent to setting delimiter to '/' and prefix to the path with a '/' on the end. attribute :path # @!attribute [rw] prefix # @return [String] For a string value x, causes the results to be limited to object names beginning with the substring x. attribute :prefix model Fog::Storage::Rackspace::File # Returns list of files # @return [Fog::Storage::Rackspace::Files] Retrieves a list files. # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/List_Objects-d1e1284.html def all(options = {}) requires :directory options = { 'limit' => limit, 'marker' => marker, 'path' => path, 'prefix' => prefix }.merge!(options) merge_attributes(options) parent = directory.collection.get( directory.key, options ) if parent load(parent.files.map {|file| file.attributes}) else nil end end # Calls block for each file in the directory # @yieldparam [Fog::Storage::Rackspace::File] # @return [Fog::Storage::Rackspace::Directory] returns itself # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @note This method retrieves files in pages. Page size is defined by the limit attribute alias_method :each_file_this_page, :each def each if !block_given? self else subset = dup.all subset.each_file_this_page {|f| yield f} while subset.length == (subset.limit || 10000) subset = subset.all(:marker => subset.last.key) subset.each_file_this_page {|f| yield f} end self end end # Retrieves file # @param [String] key of file # @yield get yields to block after chunk of data has been received (Optional) # @yieldparam [String] data # @yieldparam [Integer] remaining # @yieldparam [Integer] content_length # @return [Fog::Storage::Rackspace:File] # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @note If a block is provided, the body attribute will be empty. By default chunk size is 1 MB. This value can be changed by passing the parameter :chunk_size # into the :connection_options hash in the service constructor. # @example Download an image from Cloud Files and save it to file # # File.open('download.jpg', 'w') do | f | # my_directory.files.get("europe.jpg") do |data, remaing, content_length| # f.syswrite data # end # end # # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Retrieve_Object-d1e1856.html def get(key, &block) requires :directory data = service.get_object(directory.key, key, &block) metadata = Metadata.from_headers(self, data.headers) file_data = data.headers.merge({ :body => data.body, :key => key, :metadata => metadata }) new(file_data) rescue Fog::Storage::Rackspace::NotFound nil end # Returns the public_url for the given object key # @param key of the object # @return [String] url for object # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @see Directory#public_url def get_url(key) requires :directory if self.directory.public_url Files::file_url directory.public_url, key end end # Get a temporary http url for a file. # # required attributes: key # @param key [String] the key of the file within the directory # @param expires [String] number of seconds (since 1970-01-01 00:00) before url expires # @param options [Hash] # @return [String] url # @note This URL does not use the Rackspace CDN def get_http_url(key, expires, options = {}) requires :directory service.get_object_http_url(directory.key, key, expires, options) end # Get a temporary https url for a file. # # required attributes: key # @param key [String] the key of the file within the directory # @param expires [String] number of seconds (since 1970-01-01 00:00) before url expires # @param options [Hash] # @return [String] url # @note This URL does not use the Rackspace CDN def get_https_url(key, expires, options = {}) service.get_object_https_url(directory.key, key, expires, options) end # View directory detail without loading file contents # @param key of the object # @param options Required for compatibility with other Fog providers. Not Used. # @return [Fog::Storage::Rackspace::File] # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def head(key, options = {}) requires :directory data = service.head_object(directory.key, key) file_data = data.headers.merge({ :key => key }) new(file_data) rescue Fog::Storage::Rackspace::NotFound nil end # Create a new file object # @param [Hash] attributes of object # @return [Fog::Storage::Rackspace::File] def new(attributes = {}) requires :directory super({ :directory => directory }.merge!(attributes)) end # Returns an escaped object url # @param [String] path of the url # @param [String] key of the object # @return [String] escaped file url def self.file_url(path, key) return nil unless path "#{path}/#{Fog::Rackspace.escape(key, '/')}" end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/storage/file.rb0000644000004100000410000003206313411315054023724 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Storage class Rackspace class File < Fog::Model # @!attribute [r] key # @return [String] The name of the file identity :key, :aliases => 'name' # @!attribute [r] content_length # @return [Integer] The content length of the file attribute :content_length, :aliases => ['bytes', 'Content-Length'], :type => :integer # @!attribute [rw] content_type # @return [String] The MIME Media Type of the file # @see http://www.iana.org/assignments/media-types attribute :content_type, :aliases => ['content_type', 'Content-Type'] attribute :content_disposition, :aliases => 'Content-Disposition' # @!attribute [rw] etag # The MD5 checksum of file. If included file creation request, will ensure integrity of the file. # @return [String] MD5 checksum of file. attribute :etag, :aliases => ['hash', 'Etag'] # @!attribute [r] last_modified # The last time the file was modified # @return [Time] The last time the file was modified attribute :last_modified, :aliases => ['last_modified', 'Last-Modified'], :type => :time # @!attribute [rw] access_control_allow_origin # A space delimited list of URLs allowed to make Cross Origin Requests. Format is http://www.example.com. An asterisk (*) allows all. # @return [String] string containing a list of space delimited URLs # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/CORS_Container_Header-d1e1300.html attribute :access_control_allow_origin, :aliases => ['Access-Control-Allow-Origin'] # @!attribute [rw] origin # @return [String] The origin is the URI of the object's host. # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/CORS_Container_Header-d1e1300.html attribute :origin, :aliases => ['Origin'] # @!attribute [rw] content_encoding # @return [String] The content encoding of the file # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Enabling_File_Compression_with_the_Content-Encoding_Header-d1e2198.html attribute :content_encoding, :aliases => 'Content-Encoding' # @!attribute [rw] delete_at # A Unix Epoch Timestamp, in integer form, representing the time when this object will be automatically deleted. # @return [Integer] the unix epoch timestamp of when this object will be automatically deleted # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Expiring_Objects-e1e3228.html attribute :delete_at, :aliases => ['X-Delete-At'] # @!attribute [rw] delete_after # A number of seconds representing how long from now this object will be automatically deleted. # @return [Integer] the number of seconds until this object will be automatically deleted # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Expiring_Objects-e1e3228.html attribute :delete_after, :aliases => ['X-Delete-After'] # @!attribute [r] directory # @return [Fog::Storage::Rackspace::Directory] directory containing file attr_accessor :directory # @!attribute [w] public # @note Required for compatibility with other Fog providers. Not Used. attr_writer :public # Returns the body/contents of file # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @example Retrieve and download contents of Cloud Files object to file system # file_object = directory.files.get('germany.jpg') # File.open('germany.jpg', 'w') {|f| f.write(file_object.body) } # @see Fog::Storage::Rackspace::Files#get def body attributes[:body] ||= if last_modified collection.get(identity).body else '' end end # Sets the body/contents of file # @param [String,File] new_body contents of file def body=(new_body) attributes[:body] = new_body end # Copy file to another directory or directory # @param [String] target_directory_key # @param [String] target_file_key # @param options [Hash] used to pass in file attributes # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Copy_Object-d1e2241.html def copy(target_directory_key, target_file_key, options={}) requires :directory, :key options['Content-Type'] ||= content_type if content_type options['Access-Control-Allow-Origin'] ||= access_control_allow_origin if access_control_allow_origin options['Origin'] ||= origin if origin options['Content-Encoding'] ||= content_encoding if content_encoding service.copy_object(directory.key, key, target_directory_key, target_file_key, options) target_directory = service.directories.new(:key => target_directory_key) target_directory.files.get(target_file_key) end # Destroy the file # @return [Boolean] returns true if file is destroyed # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Delete_Object-d1e2264.html def destroy requires :directory, :key service.delete_object(directory.key, key) true end # Set file metadata # @param [Hash,Fog::Storage::Rackspace::Metadata] hash contains key value pairs def metadata=(hash) if hash.is_a? Fog::Storage::Rackspace::Metadata attributes[:metadata] = hash else attributes[:metadata] = Fog::Storage::Rackspace::Metadata.new(self, hash) end attributes[:metadata] end # File metadata # @return [Fog::Storage::Rackspace::Metadata] metadata key value pairs. def metadata attributes[:metadata] ||= Fog::Storage::Rackspace::Metadata.new(self) end # Required for compatibility with other Fog providers. Not Used. def owner=(new_owner) if new_owner attributes[:owner] = { :display_name => new_owner['DisplayName'], :id => new_owner['ID'] } end end # Set last modified # @param [String, Fog::Time] obj def last_modified=(obj) if obj.nil? || obj == "" || obj.is_a?(Time) attributes[:last_modified] = obj return obj end # This is a work around for swift bug that has existed for 4+ years. The is that fixing the swift bug would cause more problems than its worth. # For more information refer to https://github.com/fog/fog/pull/1811 d = Date._strptime(obj,"%Y-%m-%dT%H:%M:%S") if d attributes[:last_modified] = Time.utc(d[:year], d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:leftover], d[:zone]) else attributes[:last_modified] = Time.parse(obj) end end # Is file published to CDN # @return [Boolean] return true if published to CDN # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def public? directory.public? end # Get a url for file. # # required attributes: key # # @param expires [String] number of seconds (since 1970-01-01 00:00) before url expires # @param options [Hash] # @return [String] url # @note This URL does not use the Rackspace CDN # def url(expires, options = {}) requires :key if service.ssl? service.get_object_https_url(directory.key, key, expires, options) else service.get_object_http_url(directory.key, key, expires, options) end end # Returns the public url for the file. # If the file has not been published to the CDN, this method will return nil as it is not publically accessible. This method will return the approprate # url in the following order: # # 1. If the service used to access this file was created with the option :rackspace_cdn_ssl => true, this method will return the SSL-secured URL. # 2. If the directory's cdn_cname attribute is populated this method will return the cname. # 3. return the default CDN url. # # @return [String] public url for file # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def public_url Files::file_url directory.public_url, key end # URL used to stream video to iOS devices without needing to convert your video # @return [String] iOS URL # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/iOS-Streaming-d1f3725.html def ios_url Files::file_url directory.ios_url, key end # URL used to stream resources # @return [String] streaming url # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Streaming-CDN-Enabled_Containers-d1f3721.html def streaming_url Files::file_url directory.streaming_url, key end # Immediately purge file from the CDN network # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @note You may only PURGE up to 25 objects per day. Any attempt to purge more than this will result in a 498 status code error (Rate Limited). # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Purge_CDN-Enabled_Objects-d1e3858.html def purge_from_cdn if public? service.cdn.purge(self) else false end end # Create or updates file and associated metadata # @param options [Hash] additional parameters to pass to Cloud Files # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Create_Update_Object-d1e1965.html def save(options = {}) requires :body, :directory, :key options['Content-Type'] = content_type if content_type options['Access-Control-Allow-Origin'] = access_control_allow_origin if access_control_allow_origin options['Origin'] = origin if origin options['Content-Disposition'] = content_disposition if content_disposition options['Etag'] = etag if etag options['Content-Encoding'] = content_encoding if content_encoding options['X-Delete-At'] = delete_at if delete_at options['X-Delete-After'] = delete_after if delete_after options.merge!(metadata.to_headers) data = service.put_object(directory.key, key, body, options) update_attributes_from(data) self.content_length = Fog::Storage.get_body_size(body) self.content_type ||= Fog::Storage.get_content_type(body) true end private def update_attributes_from(data) merge_attributes(data.headers.reject {|key, value| ['Content-Length', 'Content-Type'].include?(key)}) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/storage/directory.rb0000644000004100000410000001763413411315054025020 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/storage/files' require 'fog/rackspace/models/storage/metadata' module Fog module Storage class Rackspace class Directory < Fog::Model # @!attribute [r] key # @return [String] The name of the directory identity :key, :aliases => 'name' # @!attribute [r] bytes # @return [Integer] The number of bytes used by the directory attribute :bytes, :aliases => 'X-Container-Bytes-Used', :type => :integer # @!attribute [r] count # @return [Integer] The number of objects in the directory attribute :count, :aliases => 'X-Container-Object-Count', :type => :integer # @!attribute [rw] cdn_name # @return [String] The CDN CNAME to be used instead of the default CDN directory URI. The CDN CNAME will need to be setup setup in DNS and # point to the default CDN directory URI. # @note This value does not persist and will need to be specified each time a directory is created or retrieved # @see Directories#get attribute :cdn_cname # @!attribute [w] public # Required for compatibility with other Fog providers. Not Used. attr_writer :public # @!attribute [w] public_url # Required for compatibility with other Fog providers. Not Used. attr_writer :public_url # Set directory metadata # @param [Hash,Fog::Storage::Rackspace::Metadata] hash contains key value pairs def metadata=(hash) if hash.is_a? Fog::Storage::Rackspace::Metadata attributes[:metadata] = hash else attributes[:metadata] = Fog::Storage::Rackspace::Metadata.new(self, hash) end attributes[:metadata] end # Retrieve directory metadata # @return [Fog::Storage::Rackspace::Metadata] metadata key value pairs. def metadata unless attributes[:metadata] response = service.head_container(key) attributes[:metadata] = Fog::Storage::Rackspace::Metadata.from_headers(self, response.headers) end attributes[:metadata] end # Destroy the directory and remove it from CDN # @return [Boolean] returns true if directory was deleted # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @note Directory must be empty before it is destroyed. # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Delete_Container-d1e1765.html def destroy requires :key service.delete_container(key) service.cdn.publish_container(self, false) if cdn_enabled? true rescue Excon::Errors::NotFound false end # Returns collection of files in directory # @return [Fog::Storage::Rackspace::Files] collection of files in directory # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def files @files ||= begin Fog::Storage::Rackspace::Files.new( :directory => self, :service => service ) end end # Is directory published to CDN # @return [Boolean] return true if published to CDN # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def public? if @public.nil? @public ||= (key && public_url) ? true : false end @public end # Reload directory with latest data from Cloud Files # @return [Fog::Storage::Rackspace::Directory] returns itself # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def reload @public = nil @urls = nil @files = nil super end # Returns the public url for the directory. # If the directory has not been published to the CDN, this method will return nil as it is not publically accessible. This method will return the approprate # url in the following order: # # 1. If the service used to access this directory was created with the option :rackspace_cdn_ssl => true, this method will return the SSL-secured URL. # 2. If the cdn_cname attribute is populated this method will return the cname. # 3. return the default CDN url. # # @return [String] public url for directory # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def public_url return nil if urls.empty? return urls[:ssl_uri] if service.ssl? cdn_cname || urls[:uri] end # URL used to stream video to iOS devices. Cloud Files will auto convert to the approprate format. # @return [String] iOS URL # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/iOS-Streaming-d1f3725.html def ios_url urls[:ios_uri] end # URL used to stream resources # @return [String] streaming url # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Streaming-CDN-Enabled_Containers-d1f3721.html def streaming_url urls[:streaming_uri] end # Create or update directory and associated metadata # @return [Boolean] returns true if directory was saved # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @note If public attribute is true, directory will be CDN enabled # @see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Create_Container-d1e1694.html def save requires :key create_or_update_container if cdn_enabled? @urls = service.cdn.publish_container(self, public?) else raise Fog::Storage::Rackspace::Error.new("Directory can not be set as :public without a CDN provided") if public? end true end private def cdn_enabled? service.cdn && service.cdn.enabled? end def urls requires :key return {} unless cdn_enabled? @urls ||= service.cdn.urls(self) end def create_or_update_container headers = attributes[:metadata].nil? ? {} : metadata.to_headers service.put_container(key, headers) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/queues/0000755000004100000410000000000013411315054022317 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/queues/messages.rb0000644000004100000410000001013413411315054024452 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/queues/message' module Fog module Rackspace class Queues class Messages < Fog::Collection model Fog::Rackspace::Queues::Message # @!attribute [r] client_id # @return [String] UUID for the client instance. attr_accessor :client_id # @!attribute [r] queue # @return [String] The name of the queue associated with the message. attr_accessor :queue # @!attribute [rw] echo # @return [Boolean] Determines whether the API returns a client's own messages. The echo parameter is a Boolean value (true or false) that determines whether the API # returns a client's own messages, as determined by the uuid portion of the User-Agent header. If you do not specify a value, echo uses the default value of false. # If you are experimenting with the API, you might want to set echo=true in order to see the messages that you posted. attr_accessor :echo # @!attribute [rw] limit # @return [String] When more messages are available than can be returned in a single request, the client can pick up the next batch of messages by simply using the URI # template parameters returned from the previous call in the "next" field. Specifies up to 10 messages (the default value) to return. If you do not specify a value # for the limit parameter, the default value of 10 is used. attr_accessor :limit # @!attribute [rw] marker # @return [String] Specifies an opaque string that the client can use to request the next batch of messages. The marker parameter communicates to the server which # messages the client has already received. If you do not specify a value, the API returns all messages at the head of the queue (up to the limit). attr_accessor :marker # @!attribute [rw] include_claimed # @return [String] Determines whether the API returns claimed messages and unclaimed messages. The include_claimed parameter is a Boolean value (true or false) # that determines whether the API returns claimed messages and unclaimed messages. If you do not specify a value, include_claimed uses the default value of false # (only unclaimed messages are returned). attr_accessor :include_claimed # Returns list of messages # # @return [Fog::Rackspace::Queues::Messages] Retrieves a collection of messages. # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 def all requires :client_id, :queue response = service.list_messages(client_id, queue.name, options) if response.status == 204 data = [] else data = response.body['messages'] end load(data) end # Returns the specified message from the queue. # # @param [Integer] message_id id of the message to be retrieved # @return [Fog::Rackspace::Queues::Claim] Returns a claim # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] def get(message_id) requires :client_id, :queue data = service.get_message(client_id, queue.name, message_id).body new(data) rescue Fog::Rackspace::Queues::NotFound nil # HACK - This has been escalated to the Rackspace Queues team, as this # behavior is not normal HTTP behavior. rescue Fog::Rackspace::Queues::ServiceError nil end private def options data = {} data[:echo] = echo.to_s unless echo.nil? data[:limit] = limit.to_s unless limit.nil? data[:marker] = marker.to_s unless marker.nil? data[:include_claimed] = include_claimed.to_s unless include_claimed.nil? data end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/queues/message.rb0000644000004100000410000000655213411315054024300 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Queues class Message < Fog::Model # @!attribute [r] age # @return [Integer] The number of seconds relative to the server's clock. attribute :age # @!attribute [rw] ttl # @return [Integer] specifies how long the server waits before marking the message as expired and removing it from the queue. # @note The value of ttl must be between 60 and 1209600 seconds (14 days). Note that the server might not actually delete the message until its # age has reached up to (ttl + 60) seconds, to allow for flexibility in storage implementations. attribute :ttl # @!attribute [rw] body # @return [String, Hash, Array] specifies an arbitrary document that constitutes the body of the message being sent. The size of this body is limited to 256 KB, excluding whitespace. The document must be valid JSON. attribute :body # @!attribute [r] href # @return [String] location of the message attribute :href # @!attribute [r] claim_id # @return [String] the id of the claim attribute :claim_id # @!attribute [r] identity # @return [String] The messages identity def identity return nil unless href match = href.match(/\A.*\/queues\/[a-zA-Z0-9_-]{0,64}\/messages\/(.+?)(?:\?|\z)/i) match ? match[1] : nil end alias_method :id, :identity # Creates messages # Requires queue, client_id, body, and ttl attributes to be populated # @note messages cannot be updated # # @return [Boolean] returns true if message has been succesfully saved # # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/POST_postMessage__version__queues__queue_name__messages_message-operations-dle001.html def save requires :queue, :client_id, :body, :ttl raise "Message has already been created and may not be updated." unless identity.nil? data = service.create_message(client_id, queue.name, body, ttl).body self.href = data['resources'][0] true end # Destroys Message # # @return [Boolean] returns true if message is deleted # # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/DELETE_deleteMessage__version__queues__queue_name__messages__messageId__message-operations-dle001.html def destroy requires :identity, :queue options = {} options[:claim_id] = claim_id unless claim_id.nil? service.delete_message(queue.name, identity, options) true end private def queue collection.queue end def client_id collection.client_id end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/queues/claims.rb0000644000004100000410000000546613411315054024127 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/queues/claim' module Fog module Rackspace class Queues class Claims < Fog::Collection model Fog::Rackspace::Queues::Claim # @!attribute [rw] queue # @return [String] The queue associated with the claim collection attr_accessor :queue # Returns list of claims # @note The Rackspace Cloud does not currently provide a way to retrieve claims as such this list is maintained by fog. Claims are added to the claim collection # as they are created. # @return [Fog::Rackspace::Queues::Claims] Retrieves a collection of claims. # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] def all self end # This operation claims a set of messages (up to the value of the limit parameter) from oldest to newest and skips any messages that are already claimed. # @return [Fog::Rackspace::Queues::Claim] Returns a claim # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/POST_claimMessages__version__queues__queue_name__claims_claims-operations-dle001.html def create(attributes = {}) object = new(attributes) if object.save object else false end end # This operation queries the specified claim for the specified queue. Claims with malformed IDs or claims that are not found by ID are ignored. # # @param [Integer] claim_id Specifies the claim ID. # @return [Fog::Rackspace::Queues::Claim] Returns a claim # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_queryClaim__version__queues__queue_name__claims__claimId__claims-operations-dle001.html def get(claim_id) requires :queue data = service.get_claim(queue.identity, claim_id).body new(data) rescue Fog::Rackspace::Queues::NotFound nil # HACK - This has been escalated to the Rackspace Queues team, as this # behavior is not normal HTTP behavior. rescue Fog::Rackspace::Queues::ServiceError nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/queues/queue.rb0000644000004100000410000001414613411315054023776 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Queues class Queue < Fog::Model # @!attribute [rw] name # @return [String] name of queue identity :name # Returns list of messages in the queue # # @return [Fog::Rackspace::Queues::Messages] Retrieves a collection of messages. # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_getMessages__version__queues__queue_name__messages_message-operations-dle001.html def messages @messages ||= begin Fog::Rackspace::Queues::Messages.new({ :service => service, :queue => self, :client_id => service.client_id, :echo => true }) end end # Returns queue statistics, including how many messages are in the queue, categorized by status. # # @return [Hash] Retrieves a collection of messages. # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_getQueueStats__version__queues__queue_name__stats_queue-operations-dle001.html def stats service.get_queue_stats(name).body['messages'] end # Returns list of claims # @note The Rackspace Cloud does not currently provide a way to retrieve claims as such this list is maintained by fog. Claims are added to the claim collection # as they are created. # @return [Fog::Rackspace::Queues::Claims] Retrieves a collection of claims. # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] def claims @claims ||= begin Fog::Rackspace::Queues::Claims.new({ :service => service, :queue => self }) end end # Helper method to enqueue a single message # # @param [String, Hash, Array] body The body attribute specifies an arbitrary document that constitutes the body of the message being sent. The size of this body is limited to 256 KB, excluding whitespace. The document must be valid JSON. # @param [Integer] ttl The ttl attribute specifies how long the server waits before releasing the claim. The ttl value must be between 60 and 43200 seconds (12 hours). # @param [Hash] options # @return [Boolean] returns true if message has been succesfully enqueued # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/POST_postMessage__version__queues__queue_name__messages_message-operations-dle001.html def enqueue(body, ttl, options = {}) messages.create(options.merge({:body => body, :ttl => ttl})) end # Helper method to claim (dequeue) a single message, yield the message, and then destroy it # # @param [Integer] ttl The ttl attribute specifies how long the server waits before releasing the claim. The ttl value must be between 60 and 43200 seconds (12 hours). # @param [Integer] grace The grace attribute specifies the message grace period in seconds. The value of grace value must be between 60 and 43200 seconds (12 hours). # @param [Hash] options # @yieldparam message claimed [Fog::Rackspace::Queues::Message] # @return [Boolean] Returns true if claim was successfully made # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] def dequeue(ttl, grace, options = {}, &block) claim = claims.create( options.merge( { :limit => 1, :ttl => ttl, :grace => grace })) if claim message = claim.messages.first yield message if block_given? message.destroy true else false end end # Creates queue # Requires name attribute to be populated # # @return [Boolean] returns true if queue has been succesfully saved # # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/POST_postMessage__version__queues__queue_name__messages_message-operations-dle001.html def save requires :name data = service.create_queue(name) true end # Destroys queue # # @return [Boolean] returns true if queue is deleted # # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/DELETE_deleteQueue__version__queues__queue_name__queue-operations-dle001.html def destroy requires :name service.delete_queue(name) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/queues/claim.rb0000644000004100000410000001252613411315054023737 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class Queues class Claim < Fog::Model # @!attribute [r] identity # @return [String] The claim's id identity :identity # @!attribute [rw] grace # @return [Integer] The grace attribute specifies the message grace period in seconds. The value of grace value must be between 60 and 43200 seconds (12 hours). # You must include a value for this attribute in your request. To deal with workers that have stopped responding (for up to 1209600 seconds or 14 days, including # claim lifetime), the server extends the lifetime of claimed messages to be at least as long as the lifetime of the claim itself, plus the specified grace period. # If a claimed message would normally live longer than the grace period, its expiration is not adjusted. attribute :grace # @!attribute [rw] ttl # @return [Integer] The ttl attribute specifies how long the server waits before releasing the claim. The ttl value must be between 60 and 43200 seconds (12 hours). attribute :ttl # @!attribute [rw] limit # @return [Integer] Specifies the number of messages to return, up to 20 messages. If limit is not specified, limit defaults to 10. attribute :limit # @!attribute [r] limit # @return [Array, Array] Specifies the number of messages to return, up to 20 messages. # If limit is not specified, limit defaults to 10. attribute :messages alias_method :id, :identity # Creates or updates a claim # # @return [Boolean] returns true if claim is being created # # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/POST_claimMessages__version__queues__queue_name__claims_claims-operations-dle001.html # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/PATCH_updateClaim__version__queues__queue_name__claims__claimId__claims-operations-dle001.html def save if identity.nil? create else update end end # Destroys Claim # # @return [Boolean] returns true if claim is deleted # # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/DELETE_deleteClaim__version__queues__queue_name__claims__claimId__claims-operations-dle001.html def destroy requires :identity, :queue service.delete_claim(queue.name, identity) #Since Claims aren't a server side collection, we should remove # the claim from the collection. collection.delete(self) true end def messages=(messages) #HACK - Models require a collection, but I don't really want to expose # the messages collection to users here. message_collection = Fog::Rackspace::Queues::Messages.new({ :service => service, :queue => queue, :client_id => service.client_id, :echo => true }) attributes[:messages] = messages.map do |message| if message.instance_of? Fog::Rackspace::Queues::Message message.claim_id = self.id message else Fog::Rackspace::Queues::Message.new( message.merge({ :service => service, :collection => message_collection, :claim_id => self.id }.merge(message)) ) end end end def initialize(new_attributes = {}) # A hack in support of the #messages= hack up above. #messages= requires #collection to # be populated first to succeed, which is always the case in modern Rubies that preserve # Hash ordering, but not in 1.8.7. @collection = new_attributes.delete(:collection) super(new_attributes) end private def queue collection.queue end def create requires :queue, :ttl, :grace, :collection options = {} options[:limit] = limit unless limit.nil? response = service.create_claim(queue.identity, ttl, grace, options) if [200, 201].include? response.status self.identity = response.get_header('Location').split('/').last self.messages = response.body #Since Claims aren't a server side collection, we need to # add the claim to the collection collection << self true else false end end def update requires :identity, :queue, :ttl service.update_claim(queue.identity, identity, ttl) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/queues/queues.rb0000644000004100000410000000335013411315054024154 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/queues/queue' module Fog module Rackspace class Queues class Queues < Fog::Collection model Fog::Rackspace::Queues::Queue # Returns list of queues # # @return [Fog::Rackspace::Queues::Queues] Retrieves a collection of queues. # @raise [Fog::Rackspace::Queues::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_listQueues__version__queues_.html def all response = service.list_queues if service.list_queues.status == 204 data = [] else data = service.list_queues.body['queues'] end load(data) end # This operation queries the specified queue. # # @param [String] queue_name Specifies the queue name # @return [Fog::Rackspace::Queues::Queue] Returns a queue # @raise [Fog::Rackspace::Queues::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Queues::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Queues::ServiceError] # @see http://docs.rackspace.com/queues/api/v1.0/cq-devguide/content/GET_checkQueueExists__version__queues__queue_name__queue-operations-dle001.html def get(queue_name) #204 no content is returned on success. That's why no data is passed # from the GET to the constructor. service.get_queue(queue_name) new({:name => queue_name}) rescue Fog::Rackspace::Queues::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/0000755000004100000410000000000013411315054023127 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/group_config.rb0000644000004100000410000000510313411315054026134 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class AutoScale class GroupConfig < Fog::Model # @!attribute [r] group # @return [Fog::Rackspace::AutoScale::Group] The parent group attribute :group # @!attribute [r] name # @return [String] The name of the group attribute :name # @!attribute [r] cooldown # @return [String] The group's cooldown attribute :cooldown # @!attribute [r] min_entities # @return [Fixnum] The minimum amount of units which should exist in the group attribute :min_entities, :aliases => 'minEntities' # @!attribute [r] max_entities # @return [Fixnum] The maximum amount of units which should exist in the group attribute :max_entities, :aliases => 'maxEntities' # @!attribute [r] metadata # @return [Hash] The group's metadata attribute :metadata # Update this group's configuration # # @return [Boolean] returns true if group config has been updated # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/PUT_putGroupConfig_v1.0__tenantId__groups__groupId__config_Configurations.html def update options = {} options['name'] = name unless name.nil? options['cooldown'] = cooldown unless cooldown.nil? options['minEntities'] = min_entities options['maxEntities'] = max_entities options['metadata'] = metadata unless metadata.nil? service.update_group_config(group.id, options) true end # Saves group configuration. # This method will only save existing group configurations. New group configurations are created when a scaling group is created # # @return [Boolean] true if group config was saved def save if group.id update true else raise "New #{self.class} are created when a new Fog::Rackspace::AutoScale::Group is created" end end # Reloads group configuration def reload if group.id data = service.get_group_config(group.id) merge_attributes data.body['groupConfiguration'] end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/group.rb0000644000004100000410000002156013411315054024614 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/auto_scale/group_config' require 'fog/rackspace/models/auto_scale/launch_config' require 'fog/rackspace/models/auto_scale/policies' module Fog module Rackspace class AutoScale class Group < Fog::Model # @!attribute [r] id # @return [String] The autoscale group's id identity :id # @!attribute [r] links # @return [Array] group links. attribute :links # Gets the group configuration for this autoscale group. The configuration describes the # minimum number of entities in the group, the maximum number of entities in the group, # the global cooldown time for the group, and other metadata. # # @return [Fog::Rackspace::AutoScale::GroupConfiguration] group_config if found # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/GET_getGroupConfig_v1.0__tenantId__groups__groupId__config_Configurations.html def group_config if attributes[:group_config].nil? && persisted? data = service.get_group_config(identity) attributes[:group_config] = load_model('GroupConfig', data.body['groupConfiguration']) end attributes[:group_config] end # Sets the configuration when this object is populated. # # @param object [Hash] Object which will stock the object def group_config=(object = {}) if object.is_a?(Hash) attributes[:group_config] = load_model('GroupConfig', object) else attributes[:group_config] = object end end # Gets the launch configuration for this autoscale group. The launch configuration describes # the details of how to create a server, from what image to create a server, which load balancers # to join the server to, which networks to add the server to, and other metadata. # # @return [Fog::Rackspace::AutoScale::LaunchConfiguration] group_config if found # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/GET_getLaunchConfig_v1.0__tenantId__groups__groupId__launch_Configurations.html def launch_config if attributes[:launch_config].nil? && persisted? data = service.get_launch_config(identity) attributes[:launch_config] = load_model('LaunchConfig', data.body['launchConfiguration']) end attributes[:launch_config] end # Sets the configuration when this object is populated. # # @param object [Hash] Object which will stock the object def launch_config=(object={}) if object.is_a?(Hash) attributes[:launch_config] = load_model('LaunchConfig', object) else attributes[:launch_config] = object end end # For the specified autoscaling group, this operation returns a list of the scaling policies # that are available to the group. Each policy is described in terms of an ID, name, type, # adjustment, cooldown time, and links. # # @return [Fog::Rackspace::AutoScale::Policies] policies # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/GET_getPolicies_v1.0__tenantId__groups__groupId__policies_Policies.html def policies return @policies if @policies if persisted? @policies = load_model('Policies') else @policies = Fog::Rackspace::AutoScale::Policies.new(:service => service, :group => self) @policies.clear end @policies # return nil unless persisted? # @policies ||= load_model('Policies') end # Creates group # * requires attributes: :launch_config, :group_config, :policies # # @return [Boolean] returns true if group is being created # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see Groups#create # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/POST_createGroup_v1.0__tenantId__groups_Groups.html def save requires :launch_config, :group_config, :policies raise Fog::Errors::Error.new("You should update launch_config and group_config directly") if persisted? launch_config_hash = { 'args' => launch_config.args, 'type' => launch_config.type } group_config_hash = { 'name' => group_config.name, 'cooldown' => group_config.cooldown, 'maxEntities' => group_config.max_entities, 'minEntities' => group_config.min_entities } group_config_hash['metadata'] = group_config.metadata if group_config.metadata data = service.create_group(launch_config_hash, group_config_hash, policies) merge_attributes(data.body['group']) true end # Destroy the group # # @return [Boolean] returns true if group has started deleting # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/DELETE_deleteGroup_v1.0__tenantId__groups__groupId__Groups.html def destroy requires :identity service.delete_group(identity) true end # Get the current state of the autoscale group # # @return [String] the state of the group # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/GET_getGroupState_v1.0__tenantId__groups__groupId__state_Groups.html def state requires :identity data = service.get_group_state(identity) data.body['group'] end # This operation pauses all execution of autoscaling policies. # # @note NOT IMPLEMENTED YET # @return [Boolean] returns true if paused # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/POST_pauseGroup_v1.0__tenantId__groups__groupId__pause_Groups.html def pause requires :identity data = service.pause_group_state(identity) true end # This operation resumes all execution of autoscaling policies. # # @note NOT IMPLEMENTED YET # @return [Boolean] returns true if resumed # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/POST_resumeGroup_v1.0__tenantId__groups__groupId__resume_Groups.html def resume requires :identity data = service.resume_group_state(identity) true end private def load_model(class_name, attrs = nil) model = Fog::Rackspace::AutoScale.const_get(class_name).new({ :service => @service, :group => self }) if service && attrs model.merge_attributes(attrs) end model end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/policy.rb0000644000004100000410000001751213411315054024761 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/auto_scale/webhooks' module Fog module Rackspace class AutoScale class Policy < Fog::Model # @!attribute [r] id # @return [String] The policy id identity :id # @!attribute [r] group # @return [Group] The autoscale group attribute :group # @!attribute [r] links # @return [Array] Policy links attribute :links # @!attribute [r] name # @return [String] The policy's name attribute :name # @!attribute [r] change # @return [Fixnum] The fixed change to the autoscale group's number of units attribute :change # @!attribute [r] changePercent # @return [Fixnum] The percentage change to the autoscale group's number of units attribute :change_percent, :aliases => 'changePercent' # @!attribute [r] cooldown # @return [Fixnum] The policy's cooldown attribute :cooldown # @!attribute [r] type # @note Can only be "webhook", "schedule" or "cloud_monitoring" # @return [String] The policy's type attribute :type # @!attribute [r] args # @example See below: # - "cron": "23 * * * *" # - "at": "2013-06-05T03:12Z" # - "check": { # "label": "Website check 1", # "type": "remote.http", # "details": { # "url": "http://www.example.com", # "method": "GET" # }, # "monitoring_zones_poll": [ # "mzA" # ], # "timeout": 30, # "period": 100, # "target_alias": "default" # }, # "alarm_criteria": { # "criteria": "if (metric[\"duration\"] >= 2) { return new AlarmStatus(OK); } return new AlarmStatus(CRITICAL);" # } # # @return [String] Arguments used for the policy attribute :args # @!attribute [r] desiredCapacity # @return [Fixnum] The desired capacity of the group attribute :desired_capacity, :aliases => 'desiredCapacity' # Basic sanity check to make sure attributes are valid # # @raise ArgumentError If no type is set # @raise ArgumentError If args attribute is missing required keys (if type == 'schedule') # @return [Boolean] Returns true if the check passes def check_attributes raise ArgumentError, "This #{self.name} resource requires the #{type} argument" if type.nil? if type == 'schedule' raise ArgumentError, "This #{self.name} resource requires the args[cron] OR args[at] argument" if args['cron'].nil? && args['at'].nil? end true end def group=(group) attributes[:group] = group.is_a?(Group) ? group : service.groups.new(:id => group) end # Creates policy # * requires attributes: :name, :type, :cooldown # # @return [Boolean] returns true if policy is being created # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see Policies#create # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/POST_createPolicies_v1.0__tenantId__groups__groupId__policies_Policies.html def create requires :name, :type, :cooldown check_attributes options = {} options['name'] = name unless name.nil? options['change'] = change unless change.nil? options['changePercent'] = change_percent unless change_percent.nil? options['cooldown'] = cooldown unless cooldown.nil? options['type'] = type unless type.nil? options['desiredCapacity'] = desired_capacity unless desired_capacity.nil? if type == 'schedule' options['args'] = args end data = service.create_policy(group.id, options) merge_attributes(data.body['policies'][0]) true end # Updates the policy # # @return [Boolean] returns true if policy has started updating # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/PUT_putPolicy_v1.0__tenantId__groups__groupId__policies__policyId__Policies.html def update requires :identity check_attributes options = {} options['name'] = name unless name.nil? options['change'] = change unless change.nil? options['changePercent'] = change_percent unless change_percent.nil? options['cooldown'] = cooldown unless cooldown.nil? options['type'] = type unless type.nil? options['desiredCapacity'] = desired_capacity unless desired_capacity.nil? if type == 'schedule' options['args'] = args end data = service.update_policy(group.id, identity, options) merge_attributes(data.body) true end # Saves the policy # Creates policy if it is new, otherwise it will update it # @return [Boolean] true if policy has saved def save if persisted? update else create end true end # Destroy the policy # # @return [Boolean] returns true if policy has started deleting # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/DELETE_deletePolicy_v1.0__tenantId__groups__groupId__policies__policyId__Policies.html def destroy requires :identity service.delete_policy(group.id, identity) true end # Executes the scaling policy # # @return [Boolean] returns true if policy has been executed # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/POST_executePolicy_v1.0__tenantId__groups__groupId__policies__policyId__execute_Policies.html def execute requires :identity service.execute_policy(group.id, identity) true end # Gets the associated webhooks for this policy # # @return [Fog::Rackspace::AutoScale::Webhooks] returns Webhooks # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] def webhooks requires :identity @webhooks ||= Fog::Rackspace::AutoScale::Webhooks.new({ :service => service, :policy => self, :group => group }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/groups.rb0000644000004100000410000000323613411315054024777 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/auto_scale/group' module Fog module Rackspace class AutoScale class Groups < Fog::Collection model Fog::Rackspace::AutoScale::Group # Returns list of autoscale groups # # @return [Fog::Rackspace::AutoScale::Groups] Retrieves a list groups. # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/GET_getGroups_v1.0__tenantId__groups_Groups.html def all data = service.list_groups.body['groups'] load(data) end # Returns an individual autoscale group # # @return [Fog::Rackspace::AutoScale::Group] Retrieves a list groups. # @return nil if not found # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/GET_getGroupManifest_v1.0__tenantId__groups__groupId__Groups.html def get(group_id) data = service.get_group(group_id).body['group'] new(data) rescue Fog::Rackspace::AutoScale::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/webhooks.rb0000644000004100000410000000436513411315054025305 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/auto_scale/webhook' module Fog module Rackspace class AutoScale class Webhooks < Fog::Collection model Fog::Rackspace::AutoScale::Webhook attr_accessor :group attr_accessor :policy # Returns list of autoscale webhooks # # @return [Fog::Rackspace::AutoScale::Policies] Retrieves webhooks # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] def all data = service.list_webhooks(group.id, policy.id).body['webhooks'] load(data) end # Returns an individual webhook # # @return [Fog::Rackspace::AutoScale::Webhook] Retrieves a webhook # @return nil if not found # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/GET_getWebhook_v1.0__tenantId__groups__groupId__policies__policyId__webhooks__webhookId__Webhooks.html def get(webhook_id) data = service.get_webhook(group.id, policy.id, webhook_id).body['webhook'] new(data) rescue Fog::Rackspace::AutoScale::NotFound nil end # Create a webhook # # @return [Fog::Rackspace::AutoScale::Webhook] Returns the new webhook # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] def create(attributes = {}) super(attributes) end def new(attributes = {}) super({:group => group, :policy => policy}.merge(attributes)) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/webhook.rb0000644000004100000410000000720413411315054025115 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class AutoScale class Webhook < Fog::Model # @!attribute [r] id # @return [String] The webhook id identity :id # @!attribute [r] group # @return [String] The associated group attribute :group # @!attribute [r] policy # @return [String] The associated policy attribute :policy # @!attribute [r] name # @return [String] The webhook name attribute :name # @!attribute [r] metadata # @return [Hash] The metadata attribute :metadata # @!attribute [r] links # @return [Array] The webhook links attribute :links # Create webhook # * requires attribute: :name # # @return [Boolean] returns true if webhook is being created # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see Webhooks#create # @see def create requires :name options = {} options['name'] = name if name options['metadata'] = metadata if metadata data = service.create_webhook(group.id, policy.id, options) merge_attributes(data.body['webhooks'][0]) true end # Updates the webhook # # @return [Boolean] returns true if webhook has started updating # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/PUT_putWebhook_v1.0__tenantId__groups__groupId__policies__policyId__webhooks__webhookId__Webhooks.html def update requires :identity options = { 'name' => name, 'metadata' => metadata } data = service.update_webhook(group.id, policy.id, identity, options) merge_attributes(data.body) true end # Saves the webhook # Creates hook if it is new, otherwise it will update it # @return [Boolean] true if policy has saved def save if persisted? update else create end true end # Destroy the webhook # # @return [Boolean] returns true if webhook has started deleting # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/DELETE_deleteWebhook_v1.0__tenantId__groups__groupId__policies__policyId__webhooks__webhookId__Webhooks.html def destroy requires :identity service.delete_webhook(group.id, policy.id, identity) true end # Retrieves the URL for anonymously executing the policy webhook # @return [String] the URL def execution_url requires :links link = links.find { |l| l['rel'] == 'capability' } link['href'] rescue nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/group_builder.rb0000644000004100000410000000633013411315054026320 0ustar www-datawww-datarequire 'fog/core/model' require 'fog/rackspace/models/auto_scale/group_config' require 'fog/rackspace/models/auto_scale/launch_config' require 'fog/rackspace/models/auto_scale/policies' module Fog module Rackspace class AutoScale class GroupBuilder class << self def build(service, attributes) service.groups.new :group_config => build_group_config(attributes), :launch_config => build_server_launch_config(attributes) end def build_group_config(attributes) Fog::Rackspace::AutoScale::GroupConfig.new :max_entities => attributes[:max_entities], :min_entities => attributes[:min_entities], :cooldown => attributes[:cooldown], :name => attributes[:name], :metadata => attributes[:metadata] || {} end def build_server_launch_config(attributes) return nil unless attributes[:launch_config_type] == :launch_server args = {"server" => build_server_template(attributes) } args["loadBalancers"] = build_load_balancers(attributes) if attributes[:load_balancers] Fog::Rackspace::AutoScale::LaunchConfig.new :type => :launch_server, :args => args end private def build_load_balancers(attributes) return nil unless attributes[:load_balancers] load_balancers = attributes[:load_balancers].is_a?(Array) ? attributes[:load_balancers] : [attributes[:load_balancers]] load_balancers.map do |obj| obj.is_a?(Hash) ? obj : load_balancer_to_hash(obj) end end def load_balancer_to_hash(lb) raise ArgumentError.new("Expected LoadBalancer") unless lb.respond_to?(:id) && lb.respond_to?(:port) { "port" => lb.port, "loadBalancerId" => lb.id } end def build_server_template(attributes) image_id = get_id(:image, attributes) flavor_id = get_id(:flavor, attributes) server_template = { "name" => attributes[:server_name], "imageRef" => image_id, "flavorRef" => flavor_id, "OS-DCF =>diskConfig" => attributes[:disk_config] || "MANUAL", "metadata" => attributes[:server_metadata] || {} } server_template["personality"] = attributes[:personality] if attributes[:personality] server_template["user_data"] = [attributes[:user_data]].pack('m') if attributes[:user_data] server_template["config_drive"] = 'true' if attributes[:config_drive] server_template["networks"] = networks_to_hash(attributes[:networks]) if attributes[:networks] server_template end def model?(obj) obj.class.ancestors.include?(Fog::Model) end def get_id(type, attributes) id = attributes["#{type}_id".to_sym] type_key = type.to_sym id ||= model?(attributes[type_key]) ? attributes[type_key].id : attributes[type_key] end def networks_to_hash(networks) networks.map {|n| {"uuid" => n}} end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/policies.rb0000644000004100000410000000475213411315054025273 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/auto_scale/policy' module Fog module Rackspace class AutoScale class Policies < Fog::Collection model Fog::Rackspace::AutoScale::Policy attr_accessor :group # Returns list of autoscale policies # # @return [Fog::Rackspace::AutoScale::Policies] Retrieves policies # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/GET_getPolicies_v1.0__tenantId__groups__groupId__policies_Policies.html def all data = service.list_policies(group.id).body['policies'] load(data) end # Returns an individual autoscale policy # # @return [Fog::Rackspace::AutoScale::Group] Retrieves a policy # @return nil if not found # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/GET_getPolicy_v1.0__tenantId__groups__groupId__policies__policyId__Policies.html def get(policy_id) data = service.get_policy(group.id, policy_id).body['policy'] new(data) rescue Fog::Rackspace::AutoScale::NotFound nil end # Create an autoscale policy # # @return [Fog::Rackspace::AutoScale::Policy] Returns the new policy # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/POST_createPolicies_v1.0__tenantId__groups__groupId__policies_Policies.html def create(attributes = {}) super(attributes) end def new(attributes = {}) super({:group => group}.merge(attributes)) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/auto_scale/launch_config.rb0000644000004100000410000000405013411315054026252 0ustar www-datawww-datarequire 'fog/core/model' module Fog module Rackspace class AutoScale class LaunchConfig < Fog::Model # @!attribute [r] group # @return [Fog::Rackspace::AutoScale::Group] The parent group attribute :group # @!attribute [r] type # @return [Fog::Rackspace::AutoScale::Group] The type of operation (usually "launch_server") attribute :type # @!attribute [r] args # @return [Fog::Rackspace::AutoScale::Group] The arguments for the operation attribute :args # Update this group's launch configuration # # @return [Boolean] returns true if launch config has been updated # # @raise [Fog::Rackspace::AutoScale:::NotFound] - HTTP 404 # @raise [Fog::Rackspace::AutoScale:::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::AutoScale:::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::AutoScale:::ServiceError] # # @see http://docs.rackspace.com/cas/api/v1.0/autoscale-devguide/content/PUT_putLaunchConfig_v1.0__tenantId__groups__groupId__launch_Configurations.html def update options = {} options['type'] = type unless type.nil? options['args'] = args unless args.nil? service.update_launch_config(group.id, options) true end # Saves group launch configuration. # This method will only save existing group configurations. New group configurations are created when a scaling group is created # # @return [Boolean] true if launch group was saved def save if group.id update true else raise "New #{self.class} are created when a new Fog::Rackspace::AutoScale::Group is created" end end # Reloads group launch configuration def reload if group.id data = service.get_launch_config(group.id) merge_attributes data.body['launchConfiguration'] end end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking/0000755000004100000410000000000013411315054023177 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/models/networking/virtual_interfaces.rb0000644000004100000410000000353113411315054027417 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/networking/virtual_interface' require 'fog/rackspace/models/compute_v2/server' module Fog module Rackspace class Networking class VirtualInterfaces < Fog::Collection model Fog::Rackspace::Networking::VirtualInterface # Returns list of virtual interfaces for a server # @return [Fog::Rackspace::Networking::Servers] Retrieves a list virtual interfaces for server. # @raise [Fog::Rackspace::Networking::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Networking::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Networking::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Networking::ServiceError] # @note Fog's current implementation only returns 1000 servers # @note The filter parameter on the method is just to maintain compatability with other providers that support filtering. # @see http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Servers-d1e2078.html # @see Fog::Rackspace::Networking::Server#virtual_interfaces def all(options={}) server = server(options[:server]) data = service.list_virtual_interfaces(server.id).body['virtual_interfaces'] objects = load(data) objects.each{ |obj| obj.attributes[:server] = server } objects end private def server(obj) server = case obj.class.to_s when "Fog::Compute::RackspaceV2::Server" then obj when "String" then Fog::Compute::RackspaceV2::Server.new(:id => obj, :service => service) else raise "Please pass in :server (either id or Fog::Compute::RackspaceV2::Server)" end raise "Server (#{server}) not found" unless server.present? server end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking/virtual_interface.rb0000644000004100000410000000664613411315054027246 0ustar www-datawww-datarequire 'fog/core/collection' require 'fog/rackspace/models/networking/virtual_interface' module Fog module Rackspace class Networking class VirtualInterface < Fog::Model # @!attribute [r] id # @return [String] The virtual interface id identity :id # @!attribute [r] mac_address # @return [String] The Media Access Control (MAC) address for the virtual interface. # A MAC address is a unique identifier assigned to network interfaces for communications on the physical network segment. attribute :mac_address # @!attribute [r] ip_addresses # @return [Array] returns an array of hashes containing information about allocated ip addresses and their associated networks # @example # [ # { # "address": "2001:4800:7810:0512:d87b:9cbc:ff04:850c", # "network_id": "ba122b32-dbcc-4c21-836e-b701996baeb3", # "network_label": "public" # }, # { # "address": "64.49.226.149", # "network_id": "ba122b32-dbcc-4c21-836e-b701996baeb3", # "network_label": "public" # } # ] attribute :ip_addresses # Saves the virtual interface. # This method can only create a virtual interface. Attempting to update interface will result an exception # @return [Boolean] true if virtual interface has been saved def save(attributes = {}) if persisted? raise Fog::Errors::Error.new("This virtual interface has already been created and it cannot be updated") else create end true end # Creates Virtual interface for server # * requires attributes: :network # @return [Boolean] returns true if virtual network interface is being created # @raise [Fog::Rackspace::Networking::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Networking::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Networking::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Networking::ServiceError] # @example To create a virtual interface; # my_server.virtual_interfaces.create :network => my_network # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/api_create_virtual_interface.html def create data = service.create_virtual_interface(server_id, network_id) merge_attributes(data.body['virtual_interfaces'].first) end # Destroy the virtual interface # @return [Boolean] returns true if virtual interface has been destroyed # @raise [Fog::Rackspace::Networking::NotFound] - HTTP 404 # @raise [Fog::Rackspace::Networking::BadRequest] - HTTP 400 # @raise [Fog::Rackspace::Networking::InternalServerError] - HTTP 500 # @raise [Fog::Rackspace::Networking::ServiceError] # @see http://docs.rackspace.com/servers/api/v2/cn-devguide/content/delete_virt_interface_api.html def destroy service.delete_virtual_interface(server_id, id) true end private def server_id attributes[:server].is_a?(Fog::Compute::RackspaceV2::Server) ? attributes[:server].id : attributes[:server] end def network_id attributes[:network].is_a?(Network) ? attributes[:network].id : attributes[:network] end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking/network.rb0000644000004100000410000000074513411315054025223 0ustar www-datawww-datamodule Fog module Rackspace class Networking class Network < Fog::Model identity :id attribute :label attribute :cidr def save requires :label, :cidr data = service.create_network(label, cidr) merge_attributes(data.body['network']) true end def destroy requires :identity service.delete_network(identity) true end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/models/networking/networks.rb0000644000004100000410000000076513411315054025410 0ustar www-datawww-datarequire 'fog/rackspace/models/compute_v2/network' module Fog module Rackspace class Networking class Networks < Fog::Collection model Fog::Rackspace::Networking::Network def all data = service.list_networks.body['networks'] load(data) end def get(id) data = service.get_network(id).body['network'] new(data) rescue Fog::Rackspace::Networking::NotFound nil end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/dns.rb0000644000004100000410000001301313411315054020634 0ustar www-datawww-data module Fog module DNS class Rackspace < Fog::Service include Fog::Rackspace::Errors class ServiceError < Fog::Rackspace::Errors::ServiceError; end class InternalServerError < Fog::Rackspace::Errors::InternalServerError; end class BadRequest < Fog::Rackspace::Errors::BadRequest; end class Conflict < Fog::Rackspace::Errors::Conflict; end class ServiceUnavailable < Fog::Rackspace::Errors::ServiceUnavailable; end class CallbackError < Fog::Errors::Error attr_reader :response, :message, :details def initialize(response) @response = response @message = response.body['error']['message'] @details = response.body['error']['details'] end end US_ENDPOINT = 'https://dns.api.rackspacecloud.com/v1.0' UK_ENDPOINT = 'https://lon.dns.api.rackspacecloud.com/v1.0' requires :rackspace_api_key, :rackspace_username recognizes :rackspace_auth_url, :rackspace_auth_token, :rackspace_dns_endpoint, :rackspace_dns_url, :rackspace_region model_path 'fog/rackspace/models/dns' model :record collection :records model :zone collection :zones request_path 'fog/rackspace/requests/dns' #TODO - Import/Export, modify multiple domains, modify multiple records request :callback request :list_domains request :list_domain_details request :modify_domain request :create_domains request :remove_domain request :remove_domains request :list_subdomains request :list_records request :list_record_details request :modify_record request :remove_record request :remove_records request :add_records class Mock < Fog::Rackspace::Service def initialize(options={}) @rackspace_api_key = options[:rackspace_api_key] @rackspace_username = options[:rackspace_username] @rackspace_auth_url = options[:rackspace_auth_url] @connection_options = options[:connection_options] || {} end def self.data @data ||= { } end def self.reset @data = nil end def data self.class.data end def reset_data self.class.reset end end class Real < Fog::Rackspace::Service def service_name :cloudDNS end def region #Note: DNS does not currently support multiple regions @rackspace_region end def initialize(options={}) @rackspace_api_key = options[:rackspace_api_key] @rackspace_username = options[:rackspace_username] @rackspace_auth_url = options[:rackspace_auth_url] @connection_options = options[:connection_options] || {} @rackspace_endpoint = Fog::Rackspace.normalize_url(options[:rackspace_dns_url] || options[:rackspace_dns_endpoint]) @rackspace_region = options[:rackspace_region] authenticate deprecation_warnings(options) @persistent = options[:persistent] || false @connection = Fog::Core::Connection.new(endpoint_uri.to_s, @persistent, @connection_options) end def endpoint_uri(service_endpoint_url=nil) @uri = super(@rackspace_endpoint || service_endpoint_url, :rackspace_dns_url) end private def request(params, parse_json = true) super rescue Excon::Errors::NotFound => error raise NotFound.slurp(error, self) rescue Excon::Errors::BadRequest => error raise BadRequest.slurp(error, self) rescue Excon::Errors::InternalServerError => error raise InternalServerError.slurp(error, self) rescue Excon::Errors::ServiceUnavailable => error raise ServiceUnavailable.slurp(error, self) rescue Excon::Errors::Conflict => error raise Conflict.slurp(error, self) rescue Excon::Errors::HTTPStatusError => error raise ServiceError.slurp(error, self) end def array_to_query_string(arr) return "" unless arr query_array = arr.map do | k, v | val_str = v.is_a?(Array) ? v.join(",") : v.to_s "#{k}=#{val_str}" end query_array.join('&') end def validate_path_fragment(name, fragment) if fragment.nil? or fragment.to_s.empty? raise ArgumentError.new("#{name} cannot be null or empty") end end private def deprecation_warnings(options) Fog::Logger.deprecation("The :rackspace_dns_endpoint option is deprecated. Please use :rackspace_dns_url for custom endpoints") if options[:rackspace_dns_endpoint] end def setup_endpoint(credentials) account_id = credentials['X-Server-Management-Url'].match(/.*\/([\d]+)$/)[1] @uri = URI.parse(@rackspace_endpoint || US_ENDPOINT) @uri.path = "#{@uri.path}/#{account_id}" end def authenticate_v1(options) credentials = Fog::Rackspace.authenticate(options, @connection_options) setup_endpoint credentials @auth_token = credentials['X-Auth-Token'] end def authenticate(options={}) super({ :rackspace_api_key => @rackspace_api_key, :rackspace_username => @rackspace_username, :rackspace_auth_url => @rackspace_auth_url, :connection_options => @connection_options }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/cdn.rb0000644000004100000410000001454313411315054020625 0ustar www-datawww-data module Fog module CDN class Rackspace < Fog::Service requires :rackspace_api_key, :rackspace_username recognizes :rackspace_auth_url, :persistent, :rackspace_cdn_ssl, :rackspace_region, :rackspace_cdn_url request_path 'fog/rackspace/requests/cdn' request :get_containers request :head_container request :post_container request :put_container request :delete_object module Base URI_HEADERS = { "X-Cdn-Ios-Uri" => :ios_uri, "X-Cdn-Uri" => :uri, "X-Cdn-Streaming-Uri" => :streaming_uri, "X-Cdn-Ssl-Uri" => :ssl_uri }.freeze def apply_options(options) # api_key and username missing from instance variable sets @rackspace_api_key = options[:rackspace_api_key] @rackspace_username = options[:rackspace_username] @connection_options = options[:connection_options] || {} @rackspace_auth_url = options[:rackspace_auth_url] @rackspace_cdn_url = options[:rackspace_cdn_url] @rackspace_region = options[:rackspace_region] end def service_name :cloudFilesCDN end def region @rackspace_region end def request_id_header "X-Trans-Id" end # Returns true if CDN service is enabled # @return [Boolean] def enabled? @enabled end def endpoint_uri(service_endpoint_url=nil) @uri = super(@rackspace_cdn_url || service_endpoint_url, :rackspace_cdn_url) end # Publish container to CDN # @param [Fog::Storage::Rackspace::Directory] container directory to publish # @param [Boolean] publish If true directory is published. If false directory is unpublished. # @return [Hash] hash containing urls for published container # @raise [Fog::Storage::Rackspace::NotFound] - HTTP 404 # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] def publish_container(container, publish = true) enabled = publish ? 'True' : 'False' response = put_container(container.key, 'X-Cdn-Enabled' => enabled) return {} unless publish urls_from_headers(response.headers) end # Returns hash of urls for container # @param [Fog::Storage::Rackspace::Directory] container to retrieve urls for # @return [Hash] hash containing urls for published container # @raise [Fog::Storage::Rackspace::BadRequest] - HTTP 400 # @raise [Fog::Storage::Rackspace::InternalServerError] - HTTP 500 # @raise [Fog::Storage::Rackspace::ServiceError] # @note If unable to find container or container is not published this method will return an empty hash. def urls(container) begin response = head_container(container.key) return {} unless response.headers['X-Cdn-Enabled'] == 'True' urls_from_headers response.headers rescue Fog::Service::NotFound {} end end private def urls_from_headers(headers) h = {} URI_HEADERS.keys.each do | header | key = URI_HEADERS[header] h[key] = headers[header] end h end end class Mock < Fog::Rackspace::Service include Base def self.data @data ||= Hash.new do |hash, key| hash[key] = {} end end def self.reset @data = nil end def initialize(options={}) apply_options(options) authenticate(options) @enabled = !! endpoint_uri end def data self.class.data[@rackspace_username] end def purge(object) return true if object.is_a? Fog::Storage::Rackspace::File raise Fog::Errors::NotImplemented.new("#{object.class} does not support CDN purging") if object end def reset_data self.class.data.delete(@rackspace_username) end end class Real < Fog::Rackspace::Service include Base def initialize(options={}) apply_options(options) authenticate(options) @enabled = false @persistent = options[:persistent] || false if endpoint_uri @connection = Fog::Core::Connection.new(endpoint_uri.to_s, @persistent, @connection_options) @enabled = true end end # Resets CDN connection def reload @cdn_connection.reset end # Purges File # @param [Fog::Storage::Rackspace::File] file to be purged from the CDN # @raise [Fog::Errors::NotImplemented] returned when non file parameters are specified def purge(file) unless file.is_a? Fog::Storage::Rackspace::File raise Fog::Errors::NotImplemented.new("#{object.class} does not support CDN purging") if object end delete_object file.directory.key, file.key true end def request(params, parse_json = true) super rescue Excon::Errors::NotFound => error raise Fog::Storage::Rackspace::NotFound.slurp(error, self) rescue Excon::Errors::BadRequest => error raise Fog::Storage::Rackspace::BadRequest.slurp(error, self) rescue Excon::Errors::InternalServerError => error raise Fog::Storage::Rackspace::InternalServerError.slurp(error, self) rescue Excon::Errors::HTTPStatusError => error raise Fog::Storage::Rackspace::ServiceError.slurp(error, self) end private def authenticate_v1(options) credentials = Fog::Rackspace.authenticate(options, @connection_options) endpoint_uri credentials['X-CDN-Management-Url'] @auth_token = credentials['X-Auth-Token'] end # Fix for invalid auth_token, likely after 24 hours. def authenticate(options={}) super({ :rackspace_api_key => @rackspace_api_key, :rackspace_username => @rackspace_username, :rackspace_auth_url => @rackspace_auth_url, :connection_options => @connection_options }) end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/errors.rb0000644000004100000410000000721013411315054021366 0ustar www-datawww-datamodule Fog module Rackspace module Errors def self.included(mod) mod.class_eval <<-'EOS', __FILE__, __LINE__ class NotFound < Fog::Service::NotFound attr_reader :region, :status_code, :transaction_id def to_s status = status_code ? "HTTP #{status_code}" : "HTTP " message = region ? "resource not found in #{region} region" : super "[#{status} | #{transaction_id}] #{message}" end def self.slurp(error, service=nil) exception = NotFound.new exception.instance_variable_set(:@region, service.region) if service && service.respond_to?(:region) exception.instance_variable_set(:@status_code, error.response.status) rescue nil exception.set_transaction_id(error, service) exception end def set_transaction_id(error, service) return unless service && service.respond_to?(:request_id_header) && error.response @transaction_id = error.response.headers[service.request_id_header] end end EOS end class ServiceError < Fog::Errors::Error attr_reader :response_data, :status_code, :transaction_id def to_s status = status_code ? "HTTP #{status_code}" : "HTTP " "[#{status} | #{transaction_id}] #{super}" end def self.slurp(error, service=nil) data = nil message = nil status_code = nil if error.response status_code = error.response.status unless error.response.body.empty? begin data = Fog::JSON.decode(error.response.body) message = extract_message(data) rescue => e Fog::Logger.warning("Received exception '#{e}' while decoding>> #{error.response.body}") message = error.response.body data = error.response.body end end end new_error = super(error, message) new_error.instance_variable_set(:@response_data, data) new_error.instance_variable_set(:@status_code, status_code) new_error.set_transaction_id(error, service) new_error end def set_transaction_id(error, service) return unless service && service.respond_to?(:request_id_header) && error.response @transaction_id = error.response.headers[service.request_id_header] end def self.extract_message(data) if data.is_a?(Hash) message = data.values.first['message'] if data.values.first.is_a?(Hash) message ||= data['message'] end message || data.inspect end end class InternalServerError < ServiceError; end class Conflict < ServiceError; end class ServiceUnavailable < ServiceError; end class MethodNotAllowed < ServiceError; end class BadRequest < ServiceError attr_reader :validation_errors def to_s "#{super} - #{validation_errors}" end def self.slurp(error, service=nil) new_error = super(error) unless new_error.response_data.nil? or new_error.response_data['badRequest'].nil? new_error.instance_variable_set(:@validation_errors, new_error.response_data['badRequest']['validationErrors']) end status_code = error.response ? error.response.status : nil new_error.instance_variable_set(:@status_code, status_code) new_error.set_transaction_id(error, service) new_error end end end end end fog-rackspace-0.1.6/lib/fog/rackspace/examples/0000755000004100000410000000000013411315054021343 5ustar www-datawww-datafog-rackspace-0.1.6/lib/fog/rackspace/examples/README.md0000644000004100000410000000303113411315054022617 0ustar www-datawww-data# Getting Started Examples ## Download Examples using the Rackspace Open Cloud and Fog can be found in the [fog repository](https://github.com/fog/fog) under the directory `fog/lib/fog/rackspace/examples`. This repository can be downloaded via `git` by executing the following: git clone git://github.com/fog/fog.git Optionally you can download a zip by clicking on this [link](https://github.com/fog/fog/archive/master.zip). ## Requirements Examples require the following: * Rackspace Open Cloud account * Ruby 1.8.x or 1.9.x * `fog` gem For more information please refer to the [Getting Started with Fog and the Rackspace Open Cloud](https://github.com/fog/fog/blob/master/lib/fog/rackspace/docs/getting_started.md) document. ## Credentials Examples will prompt for Rackspace Open Cloud credentials. Prompts can be skipped by creating a `.fog` file in the user's home directory. This is an example of a `.fog` file for the Rackspace Open Cloud: default: rackspace_username: RACKSPACE_USERNAME rackspace_api_key: RACKSPACE_API_KEY **Note:** Replace capitalized values with the appropriate credential information. ## Executing To execute scripts using `bundler`: bundle exec ruby